<commit_before>var map;
var chart;
var puma_layer;
var leaflet_features = {};
var chart_series = {};
var feature_color = '';
var puma_lookup = {};

$(window).resize(function () {
  var h = $(window).height(),
    offsetTop = 240; // Calculate the top offset

  $('#chart').css('height', (h - offsetTop - 40));
  $('#map').css('height', (h - offsetTop));
}).resize();

$(function () {

    // logic for iframe view
    var is_iframe = false;
    if (window.location.href.indexOf("iframe=1") >= 0) {
      is_iframe = true;
      $("#topNav").hide();
      $("#chart").css("top", "0");
      $("#map").css("top", "0");
    }

    init_chart();
    $('#indicators_table span').popover({trigger: "hover", placement: "top"})

});

function init_chart(){

  $.when($.get('/data/cook_puma_trend_by_quarter.csv')).then(
    function(data){
      var puma_data = $.csv.toObjects(data);
      var series_data = [];

      $.each(puma_data, function(k, v){
        puma_lookup[v['PumaID']] = v;
        var data = [];
        for (var year = 2000; year < 2015; year++) {
          for (var quarter = 1; quarter < 5; quarter++) {
            data.push(parseFloat(v[ year + 'Q' + quarter ]));
          }
        }

        chart_series[v['PumaID']] = k;
        series_data.push({name: v['PumaID'], data: data, lineWidth: 2});

      });

      init_map();
      init_table();

      // initialize chart
      chart = new Highcharts.Chart({
        chart: {
            renderTo: 'chart'
        },
        title: {
            text: null,
            x: -20 //center
        },
        credits: { enabled: false },
        xAxis: { type: 'datetime' },
        yAxis: {
            title: {
                text: 'Price Change Since 2000'
            },
            labels: {
                formatter: function() {
                    return this.value + ' %';
                }
            },
        },
        tooltip: {
          crosshairs: true,
          formatter: function() {
            var val = this.y;
            if (this.y >= 0)
              val = "+" + this.y;
            var s = "" + puma_lookup[this.series.name].Name + "
" + Highcharts.dateFormat("%B %Y", this.x) + "
Price change since 2000: " + val + "%";

            return s;
          }
        },
        legend: {
          enabled: false
        },
        plotOptions: {
          series: {
            marker: {
              radius: 0,
              states: {
                hover: {
                  enabled: true,
                  radius: 5
                }
              }
            },
            pointInterval: (3 * 30.4 * 24 * 3600 * 1000),
            pointStart: Date.UTC(2000, 2, 15),
            shadow: false,
            states: {
               hover: {
                  lineWidth: 10
               }
            },
            events: {
              mouseOver: function () {
                chart.series[this.index].group.toFront();
                map._layers[leaflet_features[this.name]].fireEvent('mouseover');
                map._layers[leaflet_features[this.name]].setStyle({fillColor: this.color});
              },
              mouseOut: function () {
                map._layers[leaflet_features[this.name]].fireEvent('mouseout');
              }
            }
          }
        },
        series: series_data
      });
    });
}

function init_map() {

    map = L.map('map', { scrollWheelZoom: false }).setView([41.79998325207397, -87.87277221679688], 9);

    L.tileLayer('https://{s}.tiles.mapbox.com/v3/datamade.hn83a654/{z}/{x}/{y}.png', {
        maxZoom: 18,
        attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA',
        id: 'datamade.hn83a654',
        detectRetina: true
    }).addTo(map);

    // control that shows state info on hover
    var info = L.control();

    info.onAdd = function (map) {
      this._div = L.DomUtil.create('div', 'info');
      this.update();
      return this._div;
    };

    info.update = function (props) {
      this._div.innerHTML = (props ?
        '' + puma_lookup[props.PUMACE10].Name + ''
        : 'Hover over an area');
    };

    info.addTo(map);

    function puma_style(feature){
        var style = {
            "color": "white",
            "fillColor": "#0855CD",
            "opacity": 1,
            "weight": 1,
            "fillOpacity": 0.5,
        }
        return style;
    }

    function resetHighlight(e) {
      var layer = e.target;
      puma_layer.resetStyle(layer);
      if (layer.feature.properties.PUMACE10 == "03525")
        layer.setStyle({fillColor: '#ccc'});
      else
        chart.series[chart_series[layer.feature.properties.PUMACE10]].setState();
      info.update();
    }

    function highlightFeature(e) {
      var layer = e.target;
      var color = '#ccc';
      if (chart.series[chart_series[layer.feature.properties.PUMACE10]] != undefined) {
        color = chart.series[chart_series[layer.feature.properties.PUMACE10]].color;
        chart.series[chart_series[layer.feature.properties.PUMACE10]].setState('hover');
        chart.series[chart_series[layer.feature.properties.PUMACE10]].group.toFront();
      }

      layer.setStyle({
        weight: 5,
        color: '#fff',
        dashArray: '',
        fillOpacity: 0.7,
        fillColor: color
      });

      if (!L.Browser.ie && !L.Browser.opera) {
        layer.bringToFront();
      }

      info.update(layer.feature.properties);
    }

    function onEachFeature(feature, layer) {
      layer.on({
        mouseover: highlightFeature,
        mouseout: resetHighlight
      });
    }

    $.when($.getJSON('data/pumas.geojson')).then(
      function(pumas){
        puma_layer = L.geoJson(pumas, {
            style: puma_style,
            onEachFeature: onEachFeature
        }).addTo(map);

        puma_layer.eachLayer(function (layer) {
          if (layer.feature.properties.PUMACE10 == "03525")
            layer.setStyle({fillColor: '#ccc'});
          leaflet_features[layer.feature.properties.PUMACE10] = layer._leaflet_id;
        });

        map.fitBounds(puma_layer.getBounds());
    });
}

function init_table() {
  $.each(puma_lookup, function(k,v){
    var row = "\

\
        " + v.Name + "	\
        " + table_row(v['Change Since 2000']) + "\
        " + table_row(v['Change Peak to Current']) + "\
        " + table_row(v['Change Bottom to Current']) + "\

";

    $('#indicators_table tbody').append(row);

  });

  $('#indicators_table').dataTable( {
    "aaSorting": [ [1,'desc'] ],
    "aoColumns": [
        null,
        null,
        null,
        null
    ],
    "bInfo": false,
    "bPaginate": false,
    "bFilter": false
  });
}

function table_row(value) {
  var style = 'danger';
  if (value >= 0) {
    style = 'success';
    value = "+" + value;
  }
  return "" + value + "%	";
}<commit_msg>note for loop not having enough data<commit_after>var map;
var chart;
var puma_layer;
var leaflet_features = {};
var chart_series = {};
var feature_color = '';
var puma_lookup = {};

$(window).resize(function () {
  var h = $(window).height(),
    offsetTop = 240; // Calculate the top offset

  $('#chart').css('height', (h - offsetTop - 40));
  $('#map').css('height', (h - offsetTop));
}).resize();

$(function () {

    // logic for iframe view
    var is_iframe = false;
    if (window.location.href.indexOf("iframe=1") >= 0) {
      is_iframe = true;
      $("#topNav").hide();
      $("#chart").css("top", "0");
      $("#map").css("top", "0");
    }

    init_chart();
    $('#indicators_table span').popover({trigger: "hover", placement: "top"})

});

function init_chart(){

  $.when($.get('/data/cook_puma_trend_by_quarter.csv')).then(
    function(data){
      var puma_data = $.csv.toObjects(data);
      var series_data = [];

      $.each(puma_data, function(k, v){
        puma_lookup[v['PumaID']] = v;
        var data = [];
        for (var year = 2000; year < 2015; year++) {
          for (var quarter = 1; quarter < 5; quarter++) {
            data.push(parseFloat(v[ year + 'Q' + quarter ]));
          }
        }

        chart_series[v['PumaID']] = k;
        series_data.push({name: v['PumaID'], data: data, lineWidth: 2});

      });

      init_map();
      init_table();

      // initialize chart
      chart = new Highcharts.Chart({
        chart: {
            renderTo: 'chart'
        },
        title: {
            text: null,
            x: -20 //center
        },
        credits: { enabled: false },
        xAxis: { type: 'datetime' },
        yAxis: {
            title: {
                text: 'Price Change Since 2000'
            },
            labels: {
                formatter: function() {
                    return this.value + ' %';
                }
            },
        },
        tooltip: {
          crosshairs: true,
          formatter: function() {
            var val = this.y;
            if (this.y >= 0)
              val = "+" + this.y;
            var s = "" + puma_lookup[this.series.name].Name + "
" + Highcharts.dateFormat("%B %Y", this.x) + "
Price change since 2000: " + val + "%";

            return s;
          }
        },
        legend: {
          enabled: false
        },
        plotOptions: {
          series: {
            marker: {
              radius: 0,
              states: {
                hover: {
                  enabled: true,
                  radius: 5
                }
              }
            },
            pointInterval: (3 * 30.4 * 24 * 3600 * 1000),
            pointStart: Date.UTC(2000, 2, 15),
            shadow: false,
            states: {
               hover: {
                  lineWidth: 10
               }
            },
            events: {
              mouseOver: function () {
                chart.series[this.index].group.toFront();
                map._layers[leaflet_features[this.name]].fireEvent('mouseover');
                map._layers[leaflet_features[this.name]].setStyle({fillColor: this.color});
              },
              mouseOut: function () {
                map._layers[leaflet_features[this.name]].fireEvent('mouseout');
              }
            }
          }
        },
        series: series_data
      });
    });
}

function init_map() {

    map = L.map('map', { scrollWheelZoom: false }).setView([41.79998325207397, -87.87277221679688], 9);

    L.tileLayer('https://{s}.tiles.mapbox.com/v3/datamade.hn83a654/{z}/{x}/{y}.png', {
        maxZoom: 18,
        attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA',
        id: 'datamade.hn83a654',
        detectRetina: true
    }).addTo(map);

    // control that shows state info on hover
    var info = L.control();

    info.onAdd = function (map) {
      this._div = L.DomUtil.create('div', 'info');
      this.update();
      return this._div;
    };

    info.update = function (props) {
      var text = 'Hover over an area';
      if (props) {
        if (puma_lookup[props.PUMACE10])
          text = puma_lookup[props.PUMACE10].Name
        else
          text = "Chicago--Loop (not enough data)";
      }
      this._div.innerHTML = '' + text + '';
    };

    info.addTo(map);

    function puma_style(feature){
        var style = {
            "color": "white",
            "fillColor": "#0855CD",
            "opacity": 1,
            "weight": 1,
            "fillOpacity": 0.5,
        }
        return style;
    }

    function resetHighlight(e) {
      var layer = e.target;
      puma_layer.resetStyle(layer);
      if (layer.feature.properties.PUMACE10 == "03525")
        layer.setStyle({fillColor: '#ccc'});
      else
        chart.series[chart_series[layer.feature.properties.PUMACE10]].setState();
      info.update();
    }

    function highlightFeature(e) {
      var layer = e.target;
      var color = '#ccc';
      if (chart.series[chart_series[layer.feature.properties.PUMACE10]] != undefined) {
        color = chart.series[chart_series[layer.feature.properties.PUMACE10]].color;
        chart.series[chart_series[layer.feature.properties.PUMACE10]].setState('hover');
        chart.series[chart_series[layer.feature.properties.PUMACE10]].group.toFront();
      }

      layer.setStyle({
        weight: 5,
        color: '#fff',
        dashArray: '',
        fillOpacity: 0.7,
        fillColor: color
      });

      if (!L.Browser.ie && !L.Browser.opera) {
        layer.bringToFront();
      }

      info.update(layer.feature.properties);
    }

    function onEachFeature(feature, layer) {
      layer.on({
        mouseover: highlightFeature,
        mouseout: resetHighlight
      });
    }

    $.when($.getJSON('data/pumas.geojson')).then(
      function(pumas){
        puma_layer = L.geoJson(pumas, {
            style: puma_style,
            onEachFeature: onEachFeature
        }).addTo(map);

        puma_layer.eachLayer(function (layer) {
          if (layer.feature.properties.PUMACE10 == "03525")
            layer.setStyle({fillColor: '#ccc'});
          leaflet_features[layer.feature.properties.PUMACE10] = layer._leaflet_id;
        });

        map.fitBounds(puma_layer.getBounds());
    });
}

function init_table() {
  $.each(puma_lookup, function(k,v){
    var row = "\

\
        " + v.Name + "	\
        " + table_row(v['Change Since 2000']) + "\
        " + table_row(v['Change Peak to Current']) + "\
        " + table_row(v['Change Bottom to Current']) + "\

";

    $('#indicators_table tbody').append(row);

  });

  $('#indicators_table').dataTable( {
    "aaSorting": [ [1,'desc'] ],
    "aoColumns": [
        null,
        null,
        null,
        null
    ],
    "bInfo": false,
    "bPaginate": false,
    "bFilter": false
  });
}

function table_row(value) {
  var style = 'danger';
  if (value >= 0) {
    style = 'success';
    value = "+" + value;
  }
  return "" + value + "%	";
}<|endoftext|>


<commit_before>/*
Conditions:
- A person cannot receive a gift from herself
- A person cannot receive more than one gift
- A person cannot have more than one wish list

BONUS:
- ability to exclude certain matches (e.g., spouse)

1. Assign Santas
    Given a list of people's names:
    - Iterate over list to select "santa"
    - Remove santa from list
    - Match santa with a random recipient from remaining list
    - Return list of santa and recipient pairs
*/

function assignSantas(array) {
  if(!array || !array.length) {
    return null;
  }

  var matches     = [];
  var recipients  = array.slice();

  for(var i=0; i<array.length; i++) {
    var santa     = array[i];
    var random    = Math.floor(Math.random() * array.length);
    var recipient = recipients[random];

    if(santa !== recipient) {
      matches.push([santa, recipient]);
      recipients.splice(recipients.indexOf(recipient), 1);
    } else {
      recipient = recipients[random]
    }
  }

  return matches;
};

module.exports.assignSantas = assignSantas;
<commit_msg>Fix scope<commit_after>/*
Conditions:
- A person cannot receive a gift from herself
- A person cannot receive more than one gift
- A person cannot have more than one wish list

BONUS:
- ability to exclude certain matches (e.g., spouse)

1. Assign Santas
    Given a list of people's names:
    - Iterate over list to select "santa"
    - Remove santa from list
    - Match santa with a random recipient from remaining list
    - Return list of santa and recipient pairs
*/

var matches = [];

function assignSantas(array) {
  if(!array || !array.length) {
    return null;
  }

  var recipients  = array.slice();

  for(var i=0; i<array.length; i++) {
    var santa     = array[i];
    var random    = Math.floor(Math.random() * array.length);
    var recipient = recipients[random];

    if(santa !== recipient) {
      matches.push([santa, recipient]);
      recipients.splice(recipients.indexOf(recipient), 1);
    } else {
      recipient = recipients[random]
    }
  }

  return matches;
};

module.exports.assignSantas = assignSantas;
<|endoftext|>


<commit_before>var apiURL = 'http://whatsinstandard.com/api/4/sets.json'
var symbol = Vue.component('edition-symbol', {
  props: ['symbol'],
  template: '',
  data: function () {
    return {
      imsym: 'ss-' + this.symbol.toLowerCase()
    }
  },
})

var app = new Vue({
  el: '#vue-container',

  data: {
    editions: null,
    blockeditions: null
  },

  created: function () {
    this.fetchData()
  },

  filters: {
    moment: function (date) {
      return moment(date).format('MMMM Do YYYY');
    }
  },

  methods: {
    fetchData: function () {
      var xhr = new XMLHttpRequest()
      var self = this;
      var blockeditions = {};
      xhr.open('GET', apiURL);
      xhr.onload = function () {
        self.editions = JSON.parse(xhr.responseText)

        for(var i=0; i<self.editions.length; i++) {
          if(!blockeditions[self.editions[i].block]) {
            blockeditions[self.editions[i].block] = [];
          }

          blockeditions[self.editions[i].block].push(self.editions[i]);
        }
        self.blockeditions = blockeditions;
      };
      xhr.send();
    },

    isNotReleased: function (release_date) {
      return Date.parse(release_date) > Date.now();
    },

    getFirstNotReleasedSet: function (block) {
      for(var i=0; i < block.length; i++) {
        if(this.isNotReleased(block[i].enter_date)) {
          return block[i].name + " releases " + moment(block[i].enter_date).format('MMMM Do YYYY');
        }
      }
    }
  }
});
<commit_msg>Fix double tooltips appearing (vue + native)<commit_after>var apiURL = 'http://whatsinstandard.com/api/4/sets.json'
var symbol = Vue.component('edition-symbol', {
  props: ['symbol'],
  template: '',
  data: function () {
    return {
      imsym: 'ss-' + this.symbol.toLowerCase()
    }
  },
})

var app = new Vue({
  el: '#vue-container',

  data: {
    editions: null,
    blockeditions: null
  },

  created: function () {
    this.fetchData()
  },

  filters: {
    moment: function (date) {
      return moment(date).format('MMMM Do YYYY');
    }
  },

  methods: {
    fetchData: function () {
      var xhr = new XMLHttpRequest()
      var self = this;
      var blockeditions = {};
      xhr.open('GET', apiURL);
      xhr.onload = function () {
        self.editions = JSON.parse(xhr.responseText)

        for(var i=0; i<self.editions.length; i++) {
          if(!blockeditions[self.editions[i].block]) {
            blockeditions[self.editions[i].block] = [];
          }

          blockeditions[self.editions[i].block].push(self.editions[i]);
        }
        self.blockeditions = blockeditions;
      };
      xhr.send();
    },

    isNotReleased: function (release_date) {
      return Date.parse(release_date) > Date.now();
    },

    getFirstNotReleasedSet: function (block) {
      for(var i=0; i < block.length; i++) {
        if(this.isNotReleased(block[i].enter_date)) {
          return block[i].name + " releases " + moment(block[i].enter_date).format('MMMM Do YYYY');
        }
      }
    }
  }
});
<|endoftext|>


<commit_before>var map;

function main() {

  var options = {
    center: [-42.27730877423707, 172.63916015625],
    zoom: 6,
    zoomControl: false,  // dont add the zoom overlay (it is added by default)
    loaderControl: false //dont show tiles loader
  };

  cartodb.createVis('map', 'http://cityresearch.cartodb.com/api/v2/viz/5c39067a-b3aa-11e4-a01f-0e9d821ea90d/viz.json', options)
    .done(function(vis, layers) {
      // there are two layers, base layer and points layer
      var sublayer = layers[1].getSubLayer(0);
      sublayer.set({ 'interactivity': ['cartodb_id', 'name_to_display', 'description'] });

      // Set the custom infowindow template defined on the html
      sublayer.infowindow.set('template', $('#infowindow_template').html());

      // add the tooltip show when hover on the point
      vis.addOverlay({
        type: 'tooltip',
        position: 'top|center',
        template: '
{{name_to_display}}
'
      });

      vis.addOverlay({
        type: 'infobox',
        template: '
{{name_to_display}}

{{description}}
',
        width: 200,
        position: 'bottom|right'
      });

    });

}

window.onload = main;
<commit_msg>Update app.js<commit_after>var map;

function main() {

  var options = {
    center: [38.2500, 85.766],
    zoom: 6,
    zoomControl: false,  // dont add the zoom overlay (it is added by default)
    loaderControl: false //dont show tiles loader
  };

  cartodb.createVis('map', 'http://cityresearch.cartodb.com/api/v2/viz/5c39067a-b3aa-11e4-a01f-0e9d821ea90d/viz.json', options)
    .done(function(vis, layers) {
      // there are two layers, base layer and points layer
      var sublayer = layers[1].getSubLayer(0);
      sublayer.set({ 'interactivity': ['cartodb_id', 'name_to_display', 'description'] });

      // Set the custom infowindow template defined on the html
      sublayer.infowindow.set('template', $('#infowindow_template').html());

      // add the tooltip show when hover on the point
      vis.addOverlay({
        type: 'tooltip',
        position: 'top|center',
        template: '
{{name_to_display}}
'
      });

      vis.addOverlay({
        type: 'infobox',
        template: '
{{name_to_display}}

{{description}}
',
        width: 200,
        position: 'bottom|right'
      });

    });

}

window.onload = main;
<|endoftext|>


<commit_before>/*!
 * Version: 0.2.2
 * Updated: 16/01/2017
 *
 * @license Copyright (c) 2017. All rights reserved.
 * @author: Emanuele Manco, me@emanuelemanco.com
 */

/*jslint browser: true*/

(function() {

    // put your Google Experiment ID here
    var $experimentID = 'Lo1rjfmpRxuVEP00nWv-XA';

    // load method for javascript libraries
    function loadJS(url) {
        var obj = document.createElement("SCRIPT");
        obj.src = url;
        obj.type = 'text/javascript';
        document.getElementsByTagName("head")[0].appendChild(obj);
    }

    // load libraries
    loadJS('//cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js');
    loadJS('//www.google-analytics.com/cx/api.js?experiment='+$experimentID);
    loadJS('//cdnjs.cloudflare.com/ajax/libs/gsap/1.19.0/TweenMax.min.js');

    // check if the libraries are loaded and ready
    var ready = function(callback) {
        if (window.jQuery && window.cxApi && window.TweenMax) {
            callback(jQuery);
        } else {
            window.setTimeout(function() { ready(callback); }, 100);
        }
    };

    // we are ready to go from here, let's rock!
    ready(function($) {

        var chosenVariant = cxApi.chooseVariation(), // get the analytics variant id
            $w = 0;                                  // window width

        // All methods for the test are included inside this array
        var test = {

            // get the id and link it to the correct function
            init: function(id) {
                 console.log('initializing '+id);

                 test.current = parseInt(id);

                 switch (test.current) {
                      case 0:
                          test.original();
                      break;
                      case 1:
                          test.a();
                      break;
                      case 2:
                          test.b();
                      break;
                  }
            },

            // Don't do anything, just display the original
            original: function() {
                console.log('A/B Test: Original Variant. Nothing changes.');
            },

            // Run test A and arrange everything
            a: function() {
                console.log('A/B test: Variant A running...');

                // generic fixes

                $('.trailers').find('.icon-block').remove();

                $('.overlay--text-pull-down.overlay--with-icon .overlay__text__inner, .overlay--text-pull-down.overlay--with-details .overlay__text__inner, .overlay--with-icon .overlay__text__inner, .overlay--with-details .overlay__text__inner').css({
                   verticalAlign: "middle",
                   paddingBottom: "50px"
                });

                $('.overlay--with-icon .overlay__text, .overlay--with-details .overlay__text').css({
                   padding: "0 10px"
                });

                // loop through all thumbnail containers
                $('.thumbnail-item').each(function(){

                    // find all objects in the DOM first
                    var $this = $(this),
                        $des = $this.children('.thumbnail-item__desc'),
                        $type = $des.children('.typo--robin'),
                        $title = $des.children('h3'),
                        $sub = $des.children('.thumbnail-item__subtitle'),
                        $thumb = $this.children('.thumbnail-item__img'),
                        $img = $thumb.children('.rs-image').children('picture').children('img'),
                        $over = $thumb.children('.thumbnail-item__overlay'),
                        $iconBlock = $this.find('.icon-block'),
                        $iconLabel = $this.find('.thumbnail-item__icon__label');

                        // fix height of the thumbnail container
                        $this.css({
                           height: 'auto'
                        });

                        // set black background for the play icon
                        $iconBlock.css({
                           backgroundColor:"#000"
                        });

                        // remove the label from the icon container
                        $iconLabel.remove();

                        // stylize the overlay container
                        $over.css({
                            opacity: 1,
                            position: 'relative',
                            width: '100%',
                            height: '130px',
                            display: 'inline-block'
                        });

                        // fix the type text with a span to allow proper display
                        $type.children('.thumbnail-item__desc__label').contents().wrap('');

                        // and style it
                        $type.find('span').css({
                                fontSize: "10px",
                                display: "inline-block",
                                backgroundColor: "#f54997",
                                color: "#fff",
                                paddingLeft: "2px",
                                paddingRight: "2px"
                        });

                        // style title container
                        $title.css({
                                marginTop: "2px"
                        });

                        // and fix the title contents
                        $title.contents().wrap('').css({
                                backgroundColor: "rgba(0,0,0,0.8)",
                                padding: "2px",
                                paddingLeft: "3px",
                                paddingRight: "2px"
                        });

                        // wrap the subtitle
                        $sub.contents().wrap('');

                        // and style it
                        $sub.find('span').css({
                                fontSize: "13px",
                                backgroundColor: "rgba(0,0,0,0.6)",
                                padding: "2px"
                        });

                        // move description container
                        $des.appendTo($thumb);

                        // move overlay container
                        $over.appendTo($this);

                        $des.css({
                           position: 'absolute',
                           bottom: 0,
                           padding: '0.7em'
                        });

                    // hover effect, zooms images in and colors the icon
                    $this.hover(function(){
                        //console.log('over');
                        TweenMax.to($img, 0.5, {scale:1.1, ease:Cubic.easeInOut});
                        TweenMax.to($iconBlock, 0.5, {backgroundColor: "#f54997"});
                    },function(){
                        //console.log('out');
                        TweenMax.to($img, 0.5, {scale:1, ease:Cubic.easeInOut});
                        TweenMax.to($iconBlock, 0.5, {backgroundColor: "#000"});
                    });

                });

                test.arrange();
            },

            // Run test B and arrange
            b: function() {
                console.log('A/B test: Variant B running...');

                // loop through all thumbnail containers
                $('.thumbnail-item').each(function(){

                    // get all needed objects from the DOM
                    var $this = $(this),
                        $thumb = $this.children('.thumbnail-item__img'),
                        $des = $this.children('.thumbnail-item__desc'),
                        $type = $des.children('.typo--robin'),
                        $title = $des.find('h3'),
                        $sub = $des.children('.thumbnail-item__subtitle'),
                        $img = $thumb.children('.rs-image').children('picture').children('img'),
                        $over = $thumb.children('.thumbnail-item__overlay'),
                        $overText = $over.find('.overlay__text'),
                        $iconBlock = $this.find('.icon-block');

                        // style the type text
                        $type.css({
                            fontSize: '11px'
                        });

                        // style the title, slightly bigger
                        $title.css({
                           fontSize: '18px',
                           lineHeight: '1.1'
                        });

                        // style subtitle with a nice border on top
                        $sub.css({
                           borderTop: '1px solid rgba(255,255,255,0.1)',
                           paddingTop: '6px',
                           marginTop: '5px'
                        });

                        // zoom all images slightly in
                        TweenMax.set($img, {scale:1.1, y:'5%', ease:Cubic.easeInOut});

                        // style overlay container
                        $over.css({
                           opacity: 1,
                           height: '48px',
                           top: 'auto'
                        });

                        // remove the overlay text for more breathing space
                        $overText.remove();

                        // set the icon background color
                        $iconBlock.css({
                           backgroundColor:"#000"
                        });

                        // hover effect, zooms images out and colors the icon
                        $this.hover(function(){
                            //console.log('over');
                            TweenMax.to($img, 0.5, {scale:1, y:'0%',ease:Cubic.easeInOut});
                            TweenMax.to($iconBlock, 0.5, {backgroundColor: "#f54997"});
                        },function(){
                            //console.log('out');
                            TweenMax.to($img, 0.5, {scale:1.1, y:'5%', ease:Cubic.easeInOut});
                            TweenMax.to($iconBlock, 0.5, {backgroundColor: "#000"});
                        });

                });

                 test.arrange();

            },

            // Fixes resizing issues and layout glitches
            arrange: function() {
                $w = $(window).width();

                //console.log('arranging, width: '+$w);

                // assuming bbc uses as breakpoint 600px for mobile, style accordingly
                if ($w<=600) {
                        if (!$('body').hasClass('mobile')) {
                            $('body').addClass('mobile');

                        }

                        // apply this only for the first test
                        if (test.current==1) {
                            $('.thumbnail-item').each(function(){
                                    var $j = $(this).find('.thumbnail-item__subtitle');

                                    $j.css({display: 'none'});

                                    $(this).find('.thumbnail-item__overlay').css({
                                       height: '0px',
                                       float: 'left'
                                    });

                                    $(this).find('.overlay__icon').css({
                                       left: 'auto',
                                       right: 0
                                    });
                                });
                        }

                } else {
                        if ($('body').hasClass('mobile')) {
                            $('body').removeClass('mobile');
                        }

                        $('.thumbnail-item').each(function(){
                                var $t = $(this).find('.thumbnail-item__subtitle');

                                $t.css({display: 'block'});

                                // only for first test
                                if (test.current==1) {
                                    $(this).find('.thumbnail-item__overlay').css({
                                       height: '130px',
                                       float: 'none'
                                    });
                                }

                                $(this).find('.overlay__icon').css({
                                   left: 0,
                                   right: 'auto'
                                });
                            });
                }
            },

            current:0
        };

        // resize listener
        $(window).resize(function () {
            test.arrange();
        });

        // grab the var from the url
        function getUrlVars() {
            var vars = {};
            var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
            vars[key] = value;
            });
            return vars;
        }

        var v = getUrlVars()["variant"];

        // check if var is set
        if (v!== '' && v !== null && v !== undefined && v >=0 && v <=2) {

            //console.log('Calling variant from var: '+v);
            test.init(v);

        // if not let Google Analytics decide
        } else {

            //console.log('Calling variant chosen by Google Analytics: '+chosenVariant);
            test.init(chosenVariant);
        }
    });
})();<commit_msg>0.2.2<commit_after>/*!
 * Version: 0.2.2
 * Updated: 16/01/2017
 *
 * @license Copyright (c) 2017. All rights reserved.
 * @author: Emanuele Manco, me@emanuelemanco.com
 */

/*jslint browser: true*/

(function() {

    // put your Google Experiment ID here
    var $experimentID = 'Lo1rjfmpRxuVEP00nWv-XA';

    // load method for javascript libraries
    function loadJS(url) {
        var obj = document.createElement("SCRIPT");
        obj.src = url;
        obj.type = 'text/javascript';
        document.getElementsByTagName("head")[0].appendChild(obj);
    }

    // load libraries
    loadJS('//cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js');
    loadJS('//www.google-analytics.com/cx/api.js?experiment='+$experimentID);
    loadJS('//cdnjs.cloudflare.com/ajax/libs/gsap/1.19.0/TweenMax.min.js');

    // check if the libraries are loaded and ready
    var ready = function(callback) {
        if (window.jQuery && window.cxApi && window.TweenMax) {
            callback(jQuery);
        } else {
            window.setTimeout(function() { ready(callback); }, 100);
        }
    };

    // we are ready to go from here, let's rock!
    ready(function($) {

        var chosenVariant = cxApi.chooseVariation(), // get the analytics variant id
            $w = 0;                                  // window width

        // All methods for the test are included inside this array
        var test = {

            // get the id and link it to the correct function
            init: function(id) {
                 console.log('initializing '+id);

                 test.current = parseInt(id);

                 switch (test.current) {
                      case 0:
                          test.original();
                      break;
                      case 1:
                          test.a();
                      break;
                      case 2:
                          test.b();
                      break;
                  }
            },

            // Don't do anything, just display the original
            original: function() {
                console.log('A/B Test: Original Variant. Nothing changes.');
            },

            // Run test A and arrange everything
            a: function() {
                console.log('A/B test: Variant A running...');

                // generic fixes

                $('.trailers').find('.icon-block').remove();

                $('.overlay--text-pull-down.overlay--with-icon .overlay__text__inner, .overlay--text-pull-down.overlay--with-details .overlay__text__inner, .overlay--with-icon .overlay__text__inner, .overlay--with-details .overlay__text__inner').css({
                   verticalAlign: "middle",
                   paddingBottom: "50px"
                });

                $('.overlay--with-icon .overlay__text, .overlay--with-details .overlay__text').css({
                   padding: "0 10px"
                });

                // loop through all thumbnail containers
                $('.thumbnail-item').each(function(){

                    // find all objects in the DOM first
                    var $this = $(this),
                        $des = $this.children('.thumbnail-item__desc'),
                        $type = $des.children('.typo--robin'),
                        $title = $des.children('h3'),
                        $sub = $des.children('.thumbnail-item__subtitle'),
                        $thumb = $this.children('.thumbnail-item__img'),
                        $img = $thumb.children('.rs-image').children('picture').children('img'),
                        $over = $thumb.children('.thumbnail-item__overlay'),
                        $iconBlock = $this.find('.icon-block'),
                        $iconLabel = $this.find('.thumbnail-item__icon__label');

                        // fix height of the thumbnail container
                        $this.css({
                           height: 'auto'
                        });

                        // set black background for the play icon
                        $iconBlock.css({
                           backgroundColor:"#000"
                        });

                        // remove the label from the icon container
                        $iconLabel.remove();

                        // stylize the overlay container
                        $over.css({
                            opacity: 1,
                            position: 'relative',
                            width: '100%',
                            height: '130px',
                            display: 'inline-block'
                        });

                        // fix the type text with a span to allow proper display
                        $type.children('.thumbnail-item__desc__label').contents().wrap('');

                        // and style it
                        $type.find('span').css({
                                fontSize: "10px",
                                display: "inline-block",
                                backgroundColor: "#f54997",
                                color: "#fff",
                                paddingLeft: "2px",
                                paddingRight: "2px"
                        });

                        // style title container
                        $title.css({
                                marginTop: "2px"
                        });

                        // and fix the title contents
                        $title.contents().wrap('').css({
                                backgroundColor: "rgba(0,0,0,0.8)",
                                padding: "2px",
                                paddingLeft: "3px",
                                paddingRight: "2px"
                        });

                        // wrap the subtitle
                        $sub.contents().wrap('');

                        // and style it
                        $sub.find('span').css({
                                fontSize: "13px",
                                backgroundColor: "rgba(0,0,0,0.6)",
                                padding: "2px"
                        });

                        // move description container
                        $des.appendTo($thumb);

                        // move overlay container
                        $over.appendTo($this);

                        $des.css({
                           position: 'absolute',
                           bottom: 0,
                           padding: '0.7em'
                        });

                    // hover effect, zooms images in and colors the icon
                    $this.hover(function(){
                        //console.log('over');
                        TweenMax.to($img, 0.5, {scale:1.1, ease:Cubic.easeInOut});
                        TweenMax.to($iconBlock, 0.5, {backgroundColor: "#f54997"});
                    },function(){
                        //console.log('out');
                        TweenMax.to($img, 0.5, {scale:1, ease:Cubic.easeInOut});
                        TweenMax.to($iconBlock, 0.5, {backgroundColor: "#000"});
                    });

                });

                test.arrange();
            },

            // Run test B and arrange
            b: function() {
                console.log('A/B test: Variant B running...');

                // loop through all thumbnail containers
                $('.thumbnail-item').each(function(){

                    // get all needed objects from the DOM
                    var $this = $(this),
                        $thumb = $this.children('.thumbnail-item__img'),
                        $des = $this.children('.thumbnail-item__desc'),
                        $type = $des.children('.typo--robin'),
                        $title = $des.find('h3'),
                        $sub = $des.children('.thumbnail-item__subtitle'),
                        $img = $thumb.children('.rs-image').children('picture').children('img'),
                        $over = $thumb.children('.thumbnail-item__overlay'),
                        $overText = $over.find('.overlay__text'),
                        $iconBlock = $this.find('.icon-block');

                        // style the type text
                        $type.css({
                            fontSize: '11px'
                        });

                        // style the title, slightly bigger
                        $title.css({
                           fontSize: '18px',
                           lineHeight: '1.1'
                        });

                        // style subtitle with a nice border on top
                        $sub.css({
                           borderTop: '1px solid rgba(255,255,255,0.1)',
                           paddingTop: '6px',
                           marginTop: '5px'
                        });

                        // zoom all images slightly in
                        TweenMax.set($img, {scale:1.1, y:'5%', ease:Cubic.easeInOut});

                        // style overlay container
                        $over.css({
                           opacity: 1,
                           height: '48px',
                           top: 'auto'
                        });

                        // remove the overlay text for more breathing space
                        $overText.remove();

                        // set the icon background color
                        $iconBlock.css({
                           backgroundColor:"#000"
                        });

                        // hover effect, zooms images out and colors the icon
                        $this.hover(function(){
                            //console.log('over');
                            TweenMax.to($img, 0.5, {scale:1, y:'0%',ease:Cubic.easeInOut});
                            TweenMax.to($iconBlock, 0.5, {backgroundColor: "#f54997"});
                        },function(){
                            //console.log('out');
                            TweenMax.to($img, 0.5, {scale:1.1, y:'5%', ease:Cubic.easeInOut});
                            TweenMax.to($iconBlock, 0.5, {backgroundColor: "#000"});
                        });

                });

                 test.arrange();

            },

            // Fixes resizing issues and layout glitches
            arrange: function() {
                $w = $(window).width();

                //console.log('arranging, width: '+$w);

                // assuming bbc uses as breakpoint 600px for mobile, style accordingly
                if ($w<=600) {
                        if (!$('body').hasClass('mobile')) {
                            $('body').addClass('mobile');

                        }

                        // apply this only for the first test
                        if (test.current==1) {
                            $('.thumbnail-item').each(function(){
                                    var $j = $(this).find('.thumbnail-item__subtitle');

                                    $j.css({display: 'none'});

                                    $(this).find('.thumbnail-item__overlay').css({
                                       height: '0px',
                                       float: 'left'
                                    });

                                    $(this).find('.overlay__icon').css({
                                       left: 'auto',
                                       right: 0
                                    });
                                });
                        }

                } else {
                        if ($('body').hasClass('mobile')) {
                            $('body').removeClass('mobile');
                        }

                        $('.thumbnail-item').each(function(){
                                var $t = $(this).find('.thumbnail-item__subtitle');

                                $t.css({display: 'block'});

                                // only for first test
                                if (test.current==1) {
                                    $(this).find('.thumbnail-item__overlay').css({
                                       height: '130px',
                                       float: 'none'
                                    });
                                }

                                $(this).find('.overlay__icon').css({
                                   left: 0,
                                   right: 'auto'
                                });
                            });
                }
            },

            current:0
        };

        // resize listener
        $(window).resize(function () {
            test.arrange();
        });

        // grab the var from the url
        function getUrlVars() {
            var vars = {};
            var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
            vars[key] = value;
            });
            return vars;
        }

        var v = getUrlVars()["variant"];    // parse var

        // check if var is set
        if (v!== '' && v !== null && v !== undefined && v >=0 && v <=2) {
            test.init(v);
        // if not let Google Analytics decide
        } else {
            test.init(chosenVariant);
        }
    });
})();<|endoftext|>


<commit_before>/**
 * Created by Lukas on 15.01.2016.
 */
var app = angular.module('how2', ['ngMaterial']);

app.config(
    function($mdThemingProvider) {
        $mdThemingProvider.theme('default')
            .primaryPalette('deep-purple')
            .accentPalette('cyan')
            .dark();
    }
);

app.controller('AppController', function($http, $location, $window, $mdToast) {
    var vm = this;
    vm.loaded = false;
    vm.uploader = true;
    vm.readFile = readFile;
    vm.file = {
        index: [],
        content: []
    };
    var url = $location.absUrl();
    if(url.indexOf('?log=')!=-1){
        console.log('External log detected');
        var log = url.substr(url.indexOf('?log=')+5);
        console.log(log);
        $http.get('http://bochen415.info/loggify.php?url='+log).then(function (res) {
            console.log(res.data);
            readFile(res.data);
        });
    }

    $window.Dropzone.options.upload = {
        accept: function (file, done) {
            console.log(file);
            if(file.name.indexOf('.log')!= -1){
                var reader = new FileReader;
                reader.readAsText(file);
                reader.onload = function () {
                    readFile(reader.result);
                }
            } else {
                $mdToast.showSimple("File isn't a logfile");
                done("File isn't a logfile");
            }
        }
    };

    function readFile (text) {
        vm.uploader = false;
        var file = angular.copy(text);
        var lines;
        lines = _.split(file, /\n/);
        var launcherline = lines[lines.length-2];
        vm.launcherBuild = launcherline.substr(launcherline.indexOf('[')+2, launcherline.indexOf(']')-2);
        var sortedLines = {
            0: []
        };
        var launch = 0;
        var crashFlag = false;
        var causeFlag = false;
        var javaFlag = false;
        lines.forEach(function (line) {
            var saveLine = {
                text: line
            };
            if(line.indexOf('Forge Mod Loader version')!= -1 && line.indexOf('loading')!= -1){
                launch++;
                sortedLines[launch] = [];
            }
            sortedLines[launch].push(saveLine);
        });
        sortedLines[launch].forEach(function (lineObject) {
            var line = lineObject.text;
            if(javaFlag){
                lineObject.mark = 1;
                javaFlag = false;
                vm.javaError[1] = line;
            }
            if(line.indexOf('OS:')!= -1){
                vm.os = line.substr(line.indexOf('OS:')+4);
            }
            if(line.indexOf('Xmx')!= -1){
                vm.ram = line.substr(line.indexOf('Xmx')+3,5);
                vm.ramC = line.substr(line.indexOf('Xmx')+3,4);
            }
            if(line.indexOf('modpacks')!= -1){
                var packPath = line.substr(line.indexOf('modpacks')+9);
                console.log(packPath);
                vm.pack = packPath.substr(0, packPath.indexOf('\\'));
            }
            if(line.indexOf('jre')!= -1){
                var jrePath = line.substr(line.indexOf('jre'));
                vm.jre = jrePath.substr(0, jrePath.indexOf('\\'));
            }
            if(line.indexOf('---- Minecraft Crash Report ----')!= -1){
                crashFlag = true;
            }
            if(line.indexOf('Error occurred')!= -1){
                lineObject.mark = 1;
                javaFlag = true;
                vm.javaError = [];
                vm.javaError[0] = line;
            }
            if(line.indexOf('[java.lang.Throwable$WrappedPrintStream:println:-1]: java.lang.NoSuchMethodError: com.google.common.io.CharSource.readLines(Lcom/google/common/io/LineProcessor;)Ljava/lang/Object;')!= -1){
                vm.crack = true;
                lineObject.mark = 2;
            }
            if(line.indexOf('Caused by:')!= -1){
                causeFlag = true;
                lineObject.mark = 1;
                vm.cause = line;
            }
            if(line.indexOf('Program Files (x86)')!= -1){
                vm.falseJava = true;
            }
            if(line.indexOf('...')!= -1){
                causeFlag = false;
            }
            if(line.indexOf('at')!= -1 && causeFlag){
                lineObject.mark = 1;
            }
            if(line.indexOf('Starting download of')!= -1 || line.indexOf('Expected MD5:')!= -1){
                lineObject.mark = 3;
            }
            if(line.indexOf('[WARNING]')!= -1){
                lineObject.mark = 4;
            }
            if(line.indexOf('org.lwjgl.LWJGLException: Pixel format not accelerated')!= -1 ){
                vm.notAcc = true;
            }
            if(line.indexOf('[STDOUT]')!= -1 && crashFlag){
                lineObject.mark = 1;
            }
        });
        console.log(lines);
        console.log(vm.launcherBuild);
        console.log(sortedLines);
        vm.launches = launch;
        vm.latest = sortedLines[launch];
        vm.loaded = true;
        var url = 'http://api.technicpack.net/modpack/'+vm.pack+'?build=99';
        $http.get('http://bochen415.info/loggify.php?url='+url).then(function (res) {
            vm.packInfo = res.data;
            if(vm.packInfo.solder){
                $http.get('http://bochen415.info/loggify.php?url='+vm.packInfo.solder+'modpack/'+vm.packInfo.name).then(function (res) {
                    vm.packInfo.solderD = res.data;
                });
            }
        })
    }
});

app.directive('onReadFile', function ($parse) {
    return {
        restrict: 'A',
        scope: false,
        link: function(scope, element, attrs) {
            var fn = $parse(attrs.onReadFile);

            element.on('change', function(onChangeEvent) {
                var reader = new FileReader();

                reader.onload = function(onLoadEvent) {
                    scope.$apply(function() {
                        fn(scope, {$fileContent:onLoadEvent.target});
                    });
                };

                reader.readAsText((onChangeEvent.srcElement || onChangeEvent.target).files[0]);
                console.log((onChangeEvent.srcElement || onChangeEvent.target).files[0]);
                console.log(reader);
                reader.file=(onChangeEvent.srcElement || onChangeEvent.target).files[0];
            });
        }
    };
});<commit_msg>Fixes #2<commit_after>/**
 * Created by Lukas on 15.01.2016.
 */
var app = angular.module('how2', ['ngMaterial']);

app.config(
    function($mdThemingProvider) {
        $mdThemingProvider.theme('default')
            .primaryPalette('deep-purple')
            .accentPalette('cyan')
            .dark();
    }
);

app.controller('AppController', function($http, $location, $window, $mdToast) {
    var vm = this;
    vm.loaded = false;
    vm.uploader = true;
    vm.readFile = readFile;
    vm.file = {
        index: [],
        content: []
    };
    var url = $location.absUrl();
    if(url.indexOf('?log=')!=-1){
        console.log('External log detected');
        var log = url.substr(url.indexOf('?log=')+5);
        console.log(log);
        $http.get('http://bochen415.info/loggify.php?url='+log).then(function (res) {
            console.log(res.data);
            readFile(res.data);
        });
    }

    $window.Dropzone.options.upload = {
        accept: function (file, done) {
            console.log(file);
            if(file.name.indexOf('.log')!= -1){
                var reader = new FileReader;
                reader.readAsText(file);
                reader.onload = function () {
                    readFile(reader.result);
                }
            } else {
                $mdToast.showSimple("File isn't a logfile");
                done("File isn't a logfile");
            }
        }
    };

    function readFile (text) {
        vm.uploader = false;
        var file = angular.copy(text);
        var lines;
        lines = _.split(file, /\n/);
        var launcherline = lines[lines.length-2];
        vm.launcherBuild = launcherline.substr(launcherline.indexOf('[')+2, launcherline.indexOf(']')-2);
        var sortedLines = {
            0: []
        };
        var launch = 0;
        var crashFlag = false;
        var causeFlag = false;
        var javaFlag = false;
        lines.forEach(function (line) {
            var saveLine = {
                text: line
            };
            if(line.indexOf('Forge Mod Loader version')!= -1 && line.indexOf('loading')!= -1){
                launch++;
                sortedLines[launch] = [];
            }
            sortedLines[launch].push(saveLine);
        });
        var lineNum = 1;
        sortedLines[launch].forEach(function (lineObject) {
            lineObject.text = lineNum+" "+lineObject.text;
            var line = lineObject.text;
            if(javaFlag){
                lineObject.mark = 1;
                javaFlag = false;
                vm.javaError[1] = line;
            }
            if(line.indexOf('OS:')!= -1){
                vm.os = line.substr(line.indexOf('OS:')+4);
            }
            if(line.indexOf('Xmx')!= -1){
                vm.ram = line.substr(line.indexOf('Xmx')+3,5);
                vm.ramC = line.substr(line.indexOf('Xmx')+3,4);
            }
            if(line.indexOf('modpacks')!= -1){
                var packPath = line.substr(line.indexOf('modpacks')+9);
                console.log(packPath);
                vm.pack = packPath.substr(0, packPath.indexOf('\\'));
            }
            if(line.indexOf('jre')!= -1){
                var jrePath = line.substr(line.indexOf('jre'));
                vm.jre = jrePath.substr(0, jrePath.indexOf('\\'));
            }
            if(line.indexOf('---- Minecraft Crash Report ----')!= -1){
                crashFlag = true;
            }
            if(line.indexOf('Error occurred')!= -1){
                lineObject.mark = 1;
                javaFlag = true;
                vm.javaError = [];
                vm.javaError[0] = line;
            }
            if(line.indexOf('[java.lang.Throwable$WrappedPrintStream:println:-1]: java.lang.NoSuchMethodError: com.google.common.io.CharSource.readLines(Lcom/google/common/io/LineProcessor;)Ljava/lang/Object;')!= -1){
                vm.crack = true;
                lineObject.mark = 2;
            }
            if(line.indexOf('Caused by:')!= -1){
                causeFlag = true;
                lineObject.mark = 1;
                vm.cause = line;
            }
            if(line.indexOf('Program Files (x86)')!= -1){
                vm.falseJava = true;
            }
            if(line.indexOf('...')!= -1){
                causeFlag = false;
            }
            if(line.indexOf('at')!= -1 && causeFlag){
                lineObject.mark = 1;
            }
            if(line.indexOf('Starting download of')!= -1 || line.indexOf('Expected MD5:')!= -1){
                lineObject.mark = 3;
            }
            if(line.indexOf('[WARNING]')!= -1){
                lineObject.mark = 4;
            }
            if(line.indexOf('org.lwjgl.LWJGLException: Pixel format not accelerated')!= -1 ){
                vm.notAcc = true;
            }
            if(line.indexOf('[STDOUT]')!= -1 && crashFlag){
                lineObject.mark = 1;
            }
            lineNum++;
        });
        console.log(lines);
        console.log(vm.launcherBuild);
        console.log(sortedLines);
        vm.launches = launch;
        vm.latest = sortedLines[launch];
        vm.loaded = true;
        var url = 'http://api.technicpack.net/modpack/'+vm.pack+'?build=99';
        $http.get('http://bochen415.info/loggify.php?url='+url).then(function (res) {
            vm.packInfo = res.data;
            if(vm.packInfo.solder){
                $http.get('http://bochen415.info/loggify.php?url='+vm.packInfo.solder+'modpack/'+vm.packInfo.name).then(function (res) {
                    vm.packInfo.solderD = res.data;
                });
            }
        })
    }
});

app.directive('onReadFile', function ($parse) {
    return {
        restrict: 'A',
        scope: false,
        link: function(scope, element, attrs) {
            var fn = $parse(attrs.onReadFile);

            element.on('change', function(onChangeEvent) {
                var reader = new FileReader();

                reader.onload = function(onLoadEvent) {
                    scope.$apply(function() {
                        fn(scope, {$fileContent:onLoadEvent.target});
                    });
                };

                reader.readAsText((onChangeEvent.srcElement || onChangeEvent.target).files[0]);
                console.log((onChangeEvent.srcElement || onChangeEvent.target).files[0]);
                console.log(reader);
                reader.file=(onChangeEvent.srcElement || onChangeEvent.target).files[0];
            });
        }
    };
});<|endoftext|>


<commit_before>var pk = pk || {};
(function(pk) {
    pk.carousel = function(opt) {
        var el = opt.element,
            options = opt.options || [],
            value = opt.value || 0,
            delay = opt.delay || 4000,
            timer = true,
            inputTabIndex = opt.tabindex || el.getAttribute('tabindex') || 0;

        if (options.length === 0 && el.nodeName === "UL") {
            for (var i = 0; i < el.children.length; i++) {
                options.push(el.children[i].innerHTML);
            }
        }
        var tpl = "

",
            navEl = [],
            optionEl = [];
        for (var o = 0; o < options.length; o++) {
            optionEl.push(pk.createEl("
" + options[o] + "
"));
            navEl.push(pk.createEl("" + o + ""));
        }
        tpl += "

";

        el.innerHTML = '';
        el = pk.replaceEl(el, tpl);
        for (o = 0; o < options.length; o++) {
            el.children[0].appendChild(optionEl[o]);
            el.appendChild(navEl[o]);
        }

        function clickHandler(e) {
            obj.val(pk.attribute(e.target, 'data-nav'));
        }
        for (var c in el.children) {
            if (pk.attribute(el.children[c], 'data-nav')) {
                pk.bindEvent('click', el.children[c], clickHandler);
            }
        }

        pk.bindEvent("mousewheel", el, function(e) {
            pk.preventBubble(e);
            obj.val((e.wheelDelta > 0 || e.detail < 0) ? '-1' : '+1');
        });

        pk.bindEvent('keydown', el, function(e) {
            switch (e.keyCode) {
                case 34: //page down
                case 40: //down cursor
                case 37: //left cursor
                    obj.val('-1');
                    break;
                case 33: //page up
                case 32: //spacebar
                case 38: //up cursor
                case 39: //right cursor
                    obj.val('+1');
                    break;
                case 36: //home
                    obj.val(0);
                    break;
                case 35: //end
                    obj.val(options.length - 1);
                    break;
            }
            pk.preventBubble(e);
        });
        var oldVal;
        var obj = {
            val: function(val) {
                val = val.toString();
                if (val === undefined) {
                    return value;
                }
                var inClass = '',
                    outClass = '';
                if (val.indexOf("-") !== -1) {
                    value = value - parseInt(val.replace('-', ''), 0) < 0 ? options.length - 1 : --value;
                    inClass = 'left';
                    outClass = 'right';
                } else if (val.indexOf("+") !== -1) {
                    value = value + parseInt(val.replace('+', ''), 0) > options.length - 1 ? 0 : ++value;
                    inClass = 'right';
                    outClass = 'left';
                } else {
                    value = parseInt(val.replace('=', ''), 0);
                    value = value < 0 ? 0 : value > options.length - 1 ? options.length - 1 : value;
                    if (oldVal !== undefined && value > oldVal) {
                        inClass = 'right';
                        outClass = 'left';
                    } else {
                        inClass = 'left';
                        outClass = 'right';
                    }
                }
                for (o = 0; o < options.length; o++) {
                    if (oldVal !== undefined && oldVal === o) {
                        pk.addClass(optionEl[o], 'pk-carousel-out-' + outClass);
                    } else if (oldVal !== undefined) {
                        pk.removeClass(optionEl[o], 'pk-carousel-out-left');
                        pk.removeClass(optionEl[o], 'pk-carousel-out-right');
                    }
                    if (parseInt(o, 0) === value) {
                        // add the selected class to the current iteration
                        pk.addClass(optionEl[o], 'pk-selected');
                        pk.addClass(navEl[o], 'pk-selected');
                        if (oldVal !== undefined) {
                            pk.addClass(optionEl[o], 'pk-carousel-in-' + inClass);
                        }
                    } else {
                        pk.removeClass(optionEl[o], 'pk-selected');
                        pk.removeClass(optionEl[o], 'pk-carousel-in-right');
                        pk.removeClass(optionEl[o], 'pk-carousel-in-left');
                        pk.removeClass(navEl[o], 'pk-selected');
                    }
                }
                oldVal = value;
                timer = false;
            }
        };
        obj.val(value);

        if (delay) {
            setInterval(function() {
                if (timer) {
                    obj.val('+1');
                }
                timer = true;
            }, delay);
        }

        return obj;
    };
    return pk;
})(pk);
<commit_msg>Update carousel.js<commit_after>var pk = pk || {};
(function(pk) {
    pk.carousel = function(opt) {
        var el = opt.element,
            options = opt.options || [],
            value = opt.value || 0,
            delay = opt.delay || 4000,
            timer = true,
            inputTabIndex = opt.tabindex || el.getAttribute('tabindex') || 0;

        if (options.length === 0 && el.nodeName === "UL") {
            for (var i = 0; i < el.children.length; i++) {
                options.push(el.children[i].innerHTML);
            }
        }
        var tpl = "

",
            navEl = [],
            optionEl = [];
        for (var o = 0; o < options.length; o++) {
            optionEl.push(pk.createEl("
" + options[o] + "
"));
            navEl.push(pk.createEl("" + o + ""));
        }
        tpl += "

";

        el.innerHTML = '';
        el = pk.replaceEl(el, tpl);
        for (o = 0; o < options.length; o++) {
            el.children[0].appendChild(optionEl[o]);
            el.appendChild(navEl[o]);
        }

        function clickHandler(e) {
            obj.val(pk.attribute(e.target, 'data-nav'));
        }
        for (var c in el.children) {
            if (pk.attribute(el.children[c], 'data-nav')) {
                pk.bindEvent('click', el.children[c], clickHandler);
            }
        }

        pk.bindEvent("mousewheel", el, function(e) {
            pk.preventBubble(e);
            obj.val((e.wheelDelta > 0 || e.detail < 0) ? '-1' : '+1');
        });

        pk.bindEvent('keydown', el, function(e) {
            switch (e.keyCode) {
                case 34: //page down
                case 40: //down cursor
                case 37: //left cursor
                    obj.val('-1');
                    break;
                case 33: //page up
                case 32: //spacebar
                case 38: //up cursor
                case 39: //right cursor
                    obj.val('+1');
                    break;
                case 36: //home
                    obj.val(0);
                    break;
                case 35: //end
                    obj.val(options.length - 1);
                    break;
            }
            pk.preventBubble(e);
        });
        var oldVal;
        var obj = {
            val: function(val) {
                val = val.toString();
                if (val === undefined) {
                    return value;
                }
                var inClass = '',
                    outClass = '';
                if (val.indexOf("-") !== -1) {
                    value = value - parseInt(val.replace('-', ''), 0) < 0 ? options.length - 1 : --value;
                    inClass = 'left';
                    outClass = 'right';
                } else if (val.indexOf("+") !== -1) {
                    value = value + parseInt(val.replace('+', ''), 0) > options.length - 1 ? 0 : ++value;
                    inClass = 'right';
                    outClass = 'left';
                } else {
                    value = parseInt(val.replace('=', ''), 0);
                    value = value < 0 ? 0 : value > options.length - 1 ? options.length - 1 : value;
                    if (oldVal !== undefined && value > oldVal) {
                        inClass = 'right';
                        outClass = 'left';
                    } else {
                        inClass = 'left';
                        outClass = 'right';
                    }
                }
                for (o = 0; o < options.length; o++) {
                    if (oldVal !== undefined && oldVal === o) {
                        pk.addClass(optionEl[o], 'pk-carousel-out-' + outClass);
                    } else if (oldVal !== undefined) {
                        pk.removeClass(optionEl[o], 'pk-carousel-out-left');
                        pk.removeClass(optionEl[o], 'pk-carousel-out-right');
                    }
                    if (parseInt(o, 0) === value) {
                        // add the selected class to the current iteration
                        pk.addClass(optionEl[o], 'pk-selected');
                        pk.addClass(navEl[o], 'pk-selected');
                        if (oldVal !== undefined) {
                            pk.addClass(optionEl[o], 'pk-carousel-in-' + inClass);
                        }
                    } else {
                        pk.removeClass(optionEl[o], 'pk-selected');
                        pk.removeClass(optionEl[o], 'pk-carousel-in-right');
                        pk.removeClass(optionEl[o], 'pk-carousel-in-left');
                        pk.removeClass(navEl[o], 'pk-selected');
                    }
                }
                oldVal = value;
                timer = false;
            }
        };
        obj.val(value);

        if (delay) {
            setInterval(function() {
                if (timer) {
                    obj.val('+1');
                }
                timer = true;
            }, delay);
        }

        return obj;
    };
    return pk;
})(pk);
<|endoftext|>


<commit_before>var basemap = new L.TileLayer(baseUrl, {maxZoom: maxZoom, minZoom: minZoom, attribution: baseAttribution, subdomains: subdomains, opacity: opacity});

var popupOpts = {
    autoPanPadding: new L.Point(5, 50),
    autoPan: true
};

var railwaystation = L.geoCsv (null, {
    firstLineTitles: true,
    fieldSeparator: fieldSeparator,
    onEachFeature: function (feature, layer) {
        popupGenerator(feature, layer);
    },
    pointToLayer: function (feature, latlng) {
        return L.marker(latlng, { icon: stationMarker });
    },
    filter: function (feature, layer) {
        return feature.properties.type === "railwaystation";
    }
});

var airport = L.geoCsv (null, {
    firstLineTitles: true,
    fieldSeparator: fieldSeparator,
    onEachFeature: function (feature, layer) {
        popupGenerator(feature, layer);
    },
    pointToLayer: function (feature, latlng) {
        return L.marker(latlng, { icon: airportMarker });
    },
    filter: function (feature, layer) {
        return feature.properties.type === "airport";
    }
});

var city = L.geoCsv (null, {
    firstLineTitles: true,
    fieldSeparator: fieldSeparator,
    onEachFeature: function (feature, layer) {
        popupGenerator(feature, layer);
    },
    pointToLayer: function (feature, latlng) {
        return L.marker(latlng, { icon: cityMarker });
    },
    filter: function (feature, layer) {
        return feature.properties.type === "city" || feature.properties.type === "am3rd" || feature.properties.type === "am2nd" || feature.properties.type === "am1st";
    }
});

var generic = L.geoCsv (null, {
    firstLineTitles: true,
    fieldSeparator: fieldSeparator,
    onEachFeature: function (feature, layer) {
        popupGenerator(feature, layer);
    },
    pointToLayer: function (feature, latlng) {
        return L.marker(latlng, { icon: blueMarker });
    },
    filter: function (feature, layer) {
        return feature.properties.type === "landmark" || feature.properties.type === "undefined";
    }
});

var map = new L.Map('map', {
    center: new L.LatLng(0, 0),
    zoom: zoom,
    maxZoom: maxZoom,
    minZoom: minZoom,
    layers: [basemap]
});

var markers = new L.MarkerClusterGroup();
var dataCsv;

var addCsvMarkers = function() {

    map.removeLayer(markers);
    railwaystation.clearLayers();
    airport.clearLayers();

    markers = new L.MarkerClusterGroup(clusterOptions);

    //creo layers
    //XXX double call to make it works
    airport.addData(dataCsv);
    railwaystation.addData(dataCsv);
    railwaystation.addData(dataCsv);
    city.addData(dataCsv);
    city.addData(dataCsv);
    generic.addData(dataCsv);
    generic.addData(dataCsv);

    //aggrego layers in markers
    markers.addLayer(airport);
    markers.addLayer(railwaystation);
    markers.addLayer(city);
    markers.addLayer(generic);

    map.addLayer(markers);
    try {
        var bounds = markers.getBounds();
        if (bounds) {
            map.fitBounds(bounds);
        }
    } catch(err) {
        // pass
    }
    return false;
};

var popupGenerator = function(feature, layer) {
    var popup = '
';
    var title = feature.properties.title;
    layer.bindLabel(feature.properties.title, {className: 'map-label'});
    var prop;
    codes.some(function (obj) {
        if (obj.id === feature.properties.code) {
            prop = obj;
            return true;
        }
    });
    if (prop.id !== "999") {
        popup += ''+ title + ' ['+prop.prj+']';
    } else {
        popup += ''+ title + ' ['+prop.prj+']';
    }
    if (prop.source !== null)
        popup += '
From: '+ prop.source + '';
    popup += "</popup-content>";
    layer.bindPopup(popup, popupOpts);
}

/* CSV LOADING */

$(document).ready( function() {
    $.ajax ({
        type:'GET',
        dataType:'text',
        url: dataUrl,
        contentType: "text/csv; charset=utf-8",
        error: function() {
            alert('Error retrieving csv file');
        },
        success: function(csv) {
            dataCsv = csv;
            addCsvMarkers();
        }
    });
});

/* LAYERS CONTROL */ //XXX too much hardwritten

var overlayMaps = {};
var emptyLayers = {
    "Airports":  new L.layerGroup().addTo(map),
    "City":  new L.layerGroup().addTo(map),
    "Railwaystations":  new L.layerGroup().addTo(map),
    "Uncategorized":  new L.layerGroup().addTo(map)
};
for (var index in emptyLayers) {
    overlayMaps[index] = emptyLayers[index];
}

var control = L.control.layers(null, overlayMaps);
control.addTo(map);

map.on('overlayadd', function (a) {
    if (a.name === "Airports") {
        markers.addLayer(airport);
    } else if (a.name === "City") {
        markers.addLayer(city);
    } else if (a.name === "Railwaystations") {
        markers.addLayer(railwaystation);
    } else if (a.name === "Uncategorized") {
        markers.addLayer(generic);
    }
});
map.on('overlayremove', function (a) {
    if (a.name === "Airports") {
        markers.removeLayer(airport);
    } else if (a.name === "City") {
        markers.removeLayer(city);
    } else if (a.name === "Railwaystations") {
        markers.removeLayer(railwaystation);
    } else if (a.name === "Uncategorized") {
        markers.removeLayer(generic);
    }
});

/* BUTTONS */

L.easyButton('fa-info', function() {
    bootbox.dialog({
        title: "Wiki Needs Pictures",
        message: '
Many Wikipedia articles have no images or only few. Some of them talking about things that are out there, ready to be photographed. Find them all!

' +
                 '
Each suggestion has a link to it\'s Wikipedia or Wikidata page and to the reason why is present here. If you want to make a pin disappear you have to resolve it\'s problem (e.g. removing the warning template in it\'s page or adding the image to Wikidata).
' +
                 '
For any trouble or suggestion write on this page. This is an open source project! Let\'s code together in this Github repository.
' +
                 '
The tool updates the view once a day. Please be patient, it takes a while to load all the data.
'
    });
}, "Info", { position: 'bottomleft' }).addTo(map);

L.easyButton('fa-compass', function (){
    map.locate({setView: true});
}, "Interact with the map", { position: 'bottomright' }).addTo(map);
<commit_msg>when opens it asks for your location, be kind!<commit_after>var basemap = new L.TileLayer(baseUrl, {maxZoom: maxZoom, minZoom: minZoom, attribution: baseAttribution, subdomains: subdomains, opacity: opacity});

var popupOpts = {
    autoPanPadding: new L.Point(5, 50),
    autoPan: true
};

var railwaystation = L.geoCsv (null, {
    firstLineTitles: true,
    fieldSeparator: fieldSeparator,
    onEachFeature: function (feature, layer) {
        popupGenerator(feature, layer);
    },
    pointToLayer: function (feature, latlng) {
        return L.marker(latlng, { icon: stationMarker });
    },
    filter: function (feature, layer) {
        return feature.properties.type === "railwaystation";
    }
});

var airport = L.geoCsv (null, {
    firstLineTitles: true,
    fieldSeparator: fieldSeparator,
    onEachFeature: function (feature, layer) {
        popupGenerator(feature, layer);
    },
    pointToLayer: function (feature, latlng) {
        return L.marker(latlng, { icon: airportMarker });
    },
    filter: function (feature, layer) {
        return feature.properties.type === "airport";
    }
});

var city = L.geoCsv (null, {
    firstLineTitles: true,
    fieldSeparator: fieldSeparator,
    onEachFeature: function (feature, layer) {
        popupGenerator(feature, layer);
    },
    pointToLayer: function (feature, latlng) {
        return L.marker(latlng, { icon: cityMarker });
    },
    filter: function (feature, layer) {
        return feature.properties.type === "city" || feature.properties.type === "am3rd" || feature.properties.type === "am2nd" || feature.properties.type === "am1st";
    }
});

var generic = L.geoCsv (null, {
    firstLineTitles: true,
    fieldSeparator: fieldSeparator,
    onEachFeature: function (feature, layer) {
        popupGenerator(feature, layer);
    },
    pointToLayer: function (feature, latlng) {
        return L.marker(latlng, { icon: blueMarker });
    },
    filter: function (feature, layer) {
        return feature.properties.type === "landmark" || feature.properties.type === "undefined";
    }
});

var map = new L.Map('map', {
    center: new L.LatLng(0, 0),
    zoom: zoom,
    maxZoom: maxZoom,
    minZoom: minZoom,
    layers: [basemap]
});

var markers = new L.MarkerClusterGroup();
var dataCsv;

var addCsvMarkers = function() {

    map.removeLayer(markers);
    railwaystation.clearLayers();
    airport.clearLayers();

    markers = new L.MarkerClusterGroup(clusterOptions);

    //creo layers
    //XXX double call to make it works
    airport.addData(dataCsv);
    railwaystation.addData(dataCsv);
    railwaystation.addData(dataCsv);
    city.addData(dataCsv);
    city.addData(dataCsv);
    generic.addData(dataCsv);
    generic.addData(dataCsv);

    //aggrego layers in markers
    markers.addLayer(airport);
    markers.addLayer(railwaystation);
    markers.addLayer(city);
    markers.addLayer(generic);

    map.addLayer(markers);
    try {
        var bounds = markers.getBounds();
        if (bounds) {
            map.fitBounds(bounds);
        }
    } catch(err) {
        // pass
    }
    return false;
};

var popupGenerator = function(feature, layer) {
    var popup = '
';
    var title = feature.properties.title;
    layer.bindLabel(feature.properties.title, {className: 'map-label'});
    var prop;
    codes.some(function (obj) {
        if (obj.id === feature.properties.code) {
            prop = obj;
            return true;
        }
    });
    if (prop.id !== "999") {
        popup += ''+ title + ' ['+prop.prj+']';
    } else {
        popup += ''+ title + ' ['+prop.prj+']';
    }
    if (prop.source !== null)
        popup += '
From: '+ prop.source + '';
    popup += "</popup-content>";
    layer.bindPopup(popup, popupOpts);
}

/* CSV LOADING */

$(document).ready( function() {
    $.ajax ({
        type:'GET',
        dataType:'text',
        url: dataUrl,
        contentType: "text/csv; charset=utf-8",
        error: function() {
            alert('Error retrieving csv file');
        },
        success: function(csv) {
            dataCsv = csv;
            addCsvMarkers();
        }
    });
});

/* LAYERS CONTROL */ //XXX too much hardwritten

var overlayMaps = {};
var emptyLayers = {
    "Airports":  new L.layerGroup().addTo(map),
    "City":  new L.layerGroup().addTo(map),
    "Railwaystations":  new L.layerGroup().addTo(map),
    "Uncategorized":  new L.layerGroup().addTo(map)
};
for (var index in emptyLayers) {
    overlayMaps[index] = emptyLayers[index];
}

var control = L.control.layers(null, overlayMaps);
control.addTo(map);

map.on('overlayadd', function (a) {
    if (a.name === "Airports") {
        markers.addLayer(airport);
    } else if (a.name === "City") {
        markers.addLayer(city);
    } else if (a.name === "Railwaystations") {
        markers.addLayer(railwaystation);
    } else if (a.name === "Uncategorized") {
        markers.addLayer(generic);
    }
});
map.on('overlayremove', function (a) {
    if (a.name === "Airports") {
        markers.removeLayer(airport);
    } else if (a.name === "City") {
        markers.removeLayer(city);
    } else if (a.name === "Railwaystations") {
        markers.removeLayer(railwaystation);
    } else if (a.name === "Uncategorized") {
        markers.removeLayer(generic);
    }
});

/* BUTTONS */

L.easyButton('fa-info', function() {
    bootbox.dialog({
        title: "Wiki Needs Pictures",
        message: '
Many Wikipedia articles have no images or only few. Some of them talking about things that are out there, ready to be photographed. Find them all!

' +
                 '
Each suggestion has a link to it\'s Wikipedia or Wikidata page and to the reason why is present here. If you want to make a pin disappear you have to resolve it\'s problem (e.g. removing the warning template in it\'s page or adding the image to Wikidata).
' +
                 '
For any trouble or suggestion write on this page. This is an open source project! Let\'s code together in this Github repository.
' +
                 '
The tool updates the view once a day. Please be patient, it takes a while to load all the data.
'
    });
}, "Info", { position: 'bottomleft' }).addTo(map);

L.easyButton('fa-compass', function (){
    map.locate({setView: true});
}, "Interact with the map", { position: 'bottomright' }).addTo(map);

map.locate({setView: true});
<|endoftext|>


<commit_before>var pk = pk || {};
(function (pk) {
    pk.carousel = function (opt) {

        var el = opt.element,
            options = opt.options || [],
            value=opt.value || 0;

        if (options.length === 0 && el.nodeName === "UL") {
            for (var i = 0; i < el.children.length; i++) {
                options.push(el.children[i].innerHTML);
            }
        }

        var tpl = "

", navEl=[], optionEl=[];
        for (var o=0;o<options.length;o++) {
            optionEl.push(pk.createEl("
" + options[o] + "
"));
            navEl.push(pk.createEl(""));
        }
        tpl += "

";

        el.innerHTML = '';
        el = pk.replaceEl(el, tpl);
        for (o=0;o<options.length;o++) {
            el.children[0].appendChild(optionEl[o]);
          	el.appendChild(navEl[o]);
        }

        function clickHandler(e){
            obj.value(pk.attribute(e.target, 'data-nav'));
        }
        for(var c in el.children){
            if(pk.attribute(el.children[c], 'data-nav')){
                  pk.bindEvent('click', el.children[c], clickHandler);
            }
        }
        var obj={
            value:function(val){
                val = val.toString();
                if(val===undefined){return value;}
                if(val.indexOf("-")!==-1){
                    value = value-parseInt(val.replace('-', ''),0) < 0 ? options.length-1 : --value;
                }else if(val.indexOf("+")!==-1){
                    value = value+parseInt(val.replace('+', ''),0) > options.length-1 ? 0 : ++value;
                }else{
                    value = parseInt(val.replace('=', ''),0);
                    value = value < 0 ? 0 : value > options.length-1 ? options.length-1 : value;
                }
                for (o=0;o<options.length;o++) {
                    if(parseInt(o, 0)===value){
                        pk.addClass(optionEl[o], 'pk-selected');
                        pk.addClass(navEl[o], 'pk-selected');
                    }else{
                        pk.removeClass(optionEl[o], 'pk-selected');
                        pk.removeClass(navEl[o], 'pk-selected');
                    }
                }
            }
        };
        obj.value(value);
        return obj;
    };
    return pk;
})(pk);
<commit_msg>Update carousel.js<commit_after>var pk = pk || {};
(function(pk) {
    pk.carousel = function(opt) {

        var el = opt.element,
            options = opt.options || [],
            value = opt.value || 0,
			inputTabIndex = opt.tabindex || el.getAttribute('tabindex') || 0;

        if (options.length === 0 && el.nodeName === "UL") {
            for (var i = 0; i < el.children.length; i++) {
                options.push(el.children[i].innerHTML);
            }
        }

        var tpl = "

",
            navEl = [],
            optionEl = [];
        for (var o = 0; o < options.length; o++) {
            optionEl.push(pk.createEl("
" + options[o] + "
"));
            navEl.push(pk.createEl(""));
        }
        tpl += "

";

        el.innerHTML = '';
        el = pk.replaceEl(el, tpl);
        for (o = 0; o < options.length; o++) {
            el.children[0].appendChild(optionEl[o]);
            el.appendChild(navEl[o]);
        }

        function clickHandler(e) {
            obj.val(pk.attribute(e.target, 'data-nav'));
        }
        for (var c in el.children) {
            if (pk.attribute(el.children[c], 'data-nav')) {
                pk.bindEvent('click', el.children[c], clickHandler);
            }
        }

		pk.bindEvent("mousewheel", el, function(e) {
            pk.preventBubble(e);
            obj.val((e.wheelDelta > 0 || e.detail < 0) ? '-1' : '+1');
        });

		pk.bindEvent('keydown', el, function(e) {
            switch (e.keyCode) {
				case 34: //page down
				case 40: //down cursor
				case 37: //left cursor
					obj.val('-1');
					break;
				case 33: //page up
				case 32: //spacebar
				case 38: //up cursor
				case 39: //right cursor
					obj.val('+1');
					break;
				case 36: //home
					obj.val(0);
					break;
				case 35: //end
					obj.val(options.length-1);
					break;
			}
            pk.preventBubble(e);
        });

        var obj = {
            val: function(val) {
                val = val.toString();
                if (val === undefined) {
                    return value;
                }
                if (val.indexOf("-") !== -1) {
                    value = value - parseInt(val.replace('-', ''), 0) < 0 ? options.length - 1 : --value;
                } else if (val.indexOf("+") !== -1) {
                    value = value + parseInt(val.replace('+', ''), 0) > options.length - 1 ? 0 : ++value;
                } else {
                    value = parseInt(val.replace('=', ''), 0);
                    value = value < 0 ? 0 : value > options.length - 1 ? options.length - 1 : value;
                }
                for (o = 0; o < options.length; o++) {
                    if (parseInt(o, 0) === value) {
                        pk.addClass(optionEl[o], 'pk-selected');
                        pk.addClass(navEl[o], 'pk-selected');
                    } else {
                        pk.removeClass(optionEl[o], 'pk-selected');
                        pk.removeClass(navEl[o], 'pk-selected');
                    }
                }
            }
        };
        obj.val(value);
        return obj;
    };
    return pk;
})(pk);
<|endoftext|>


<commit_before>var map;

function main() {

  var options = {
    center: [38.2500, -85.7667],
    zoom: 12,
    zoomControl: false,  // dont add the zoom overlay (it is added by default)
    loaderControl: false //dont show tiles loader
  };

  cartodb.createVis('map', 'http://cityresearch.cartodb.com/api/v2/viz/5c39067a-b3aa-11e4-a01f-0e9d821ea90d/viz.json', options)
        .done(function(vis, layers) {
      // there are two layers, base layer and points layer

      // add the tooltip show when hover on the point
      vis.addOverlay({
        type: 'tooltip',
        position: 'top|center',
        template: '
{{name_to_display}}
'
      });

      vis.addOverlay({
        type: 'infobox',
        template: '
{{name_to_display}}

{{description}}
',
        width: 200,
        position: 'bottom|right'
      });

    });

}

window.onload = main;
<commit_msg>Update app.js<commit_after>var map;

function main() {

  var options = {
    center: [38.2500, -85.7667],
    zoom: 12,
    zoomControl: false,  // dont add the zoom overlay (it is added by default)
    loaderControl: false //dont show tiles loader
  };

  cartodb.createVis('map', 'http://cityresearch.cartodb.com/api/v2/viz/5c39067a-b3aa-11e4-a01f-0e9d821ea90d/viz.json', options)
        .done(function(vis, layers) {
      // there are two layers, base layer and points layer

      // add the tooltip show when hover on the point
      vis.addOverlay({
        type: 'tooltip',
        position: 'top|center',
        template: '
{{name_to_display}}
'
      });

    });

}

window.onload = main;
<|endoftext|>


<commit_before>/*
 * Developed by Radu Puspana
 * Date August 2017
 * Version 1.0
 */

// App controller for communicating between the budgetController and the UIconroller
var controller = (function(budgetCtrl, UIctrl) {

    // private function to place the event listeners and the HTML tags' classes
    var prvSetupEventListeners = function() {

        // object containing the class names in the index.html and style.css
        var DOMstrings = uiController.pblGetDOMstrings();

         // register click event for the input validation popup's X button
        document.getElementById("alertBox_close").addEventListener("click", function () {

            // hide the modal window when it's X button is clicked
            document.getElementById("alertBox_container").style.visibility = "hidden";
        });

        // add event listener for the .container div to catch the click event that bubbles up from the
        // .item__delete__btn <button> tag
        document.querySelector(DOMstrings.transactionContainer).addEventListener("click", prvDeleteItem);

        // register click event for the button with the tick sign
        document.querySelector(DOMstrings.inputButton).addEventListener("click", prvAddItem, false);

        // register Enter keypress event for the global object. Used only for the ENTER key
        document.getElementById("enterSum").addEventListener("keypress", function(event) {

            // use event.which to assure comptatibility with IE 9..11, Edge 14, UC Browser for Android 11.4
            // code 13 is returned when the "ENTER" key is pressed
            if (event.key === "Enter" || event.which === 13) { prvAddItem(); }

        }, false);
    };

    // get tine and date of the local time to record the creation of a transaction
    // return dateAndTime String time and date formated as YYYY-MM-DD HH:MM:SS local time
    // return String HH:MM  DD-MM-YYYY local time
    var prvGetLocalTimeAndDate = function() {
        var date = new Date;

        var hour = date.getHours();
        var minutes = date.getMinutes();
        if (minutes < 10) {
            minutes = '0' + minutes;
        }
        var seconds = date.getSeconds();

        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var day = date.getDate();

        var dateAndTime = "" + hour + ":" + minutes + ":" + seconds +
                          "  "  + day + "-" + month + "-" + year + "  ";

        return dateAndTime;
    }

    // calculate the budget based on the last submited or selected transaction and display it on the UI
    var prvUpdateBudget = function() {

        // object holding:
        // the budget after the last transaction, total expenses, total incomes,
        // how much of the budget in % the expenses represent
        var budgetIncExpExppercentage;

        // calculate the budget taking into account the submited transaction
        budgetController.pblCalculateBudget();

        // return the new budget
        budgetIncExpExppercentage = budgetController.pblGetBudgetExpIncExpPercentage();

        // display the newly calculated budget on the UI
        console.info(budgetIncExpExppercentage);
        uiController.pblDisplayTransactionOverview(budgetIncExpExppercentage);

    };

    // private function for receiving the user input from the UI,
    // entering the new transaction under the income or expense column on the UI, a
    // djusting the budget according to the user's transaction
    var prvAddItem = function() {
        var userInput, newTransaction, localTimeAndDate;

        console.log("You pressed enter and an item will be added to one of the tables and the budget will be updated");

        // get the user input data from the UI. This input will be called a transcation
        userInput = uiController.pblGetInput();
        console.log("userInput = %O", userInput);

        // input form validation for the description and value fields
        if (userInput.description.trim().length > 2 && !isNaN(userInput.value) && userInput.value > 0) {

            // add the transaction to the budget controller
            newTransaction = budgetController.pblAddItem(userInput.type, userInput.description, userInput.value);
            console.info("newTransaction = %O", newTransaction);

            // TO BE REMOVED. Inspect the prvData structure
            budgetController.pblTestGetDataStr();

            localTimeAndDate = prvGetLocalTimeAndDate();

            // add the transaction to the UI in the Income or Expense comumn depending on the transaction's type
            uiController.pblAddListItem(newTransaction, userInput.type, localTimeAndDate);

            // after transaction submit, clear the transaction's details from the transaction input form
            uiController.pblClearTransFormFields();

            // calculate the budget and display it on the UI
            prvUpdateBudget();
        }
        else {

             // HTML to replace the content(if any) of the alertBox_text div
            var modalWindowInnerHTML = "
The description should have at least three characters." +
                " The value should have at least one digit, excluding  0, before submiting the transaction.
";

            // display custom modal window with this text, type and width
            uiController.pblDisplayPopup(modalWindowInnerHTML, "err", "22%");

            // make the modal window visible
            document.getElementById("alertBox_container").style.visibility = "visible";
        }
    };

    // function for deleting a submited transaction from the income or expense columns
    // event   click event  an event that was fired up from below the .container div tag
    var prvDeleteItem = function(event) {

        var transactionIdStr, strList, transactionType, transactionIdNumber;

        console.info(event.target.parentNode.parentNode.parentNode.parentNode);

        // return
...
 when
        // the user clicks the .continer div and any of it's children
        // The instr is safe to use because in uiController.pblAddListItem() we used a

        // structure that matches the instruction below to insert an income/expense trasaction
        // in the income/expense columns
        transactionIdStr = event.target.parentNode.parentNode.parentNode.parentNode.id;

        // this will coert to true or false if an id attribute exists inside the node that transactionId points to
        if (transactionIdStr) {

            // transform the string primitive into an object and call the split method
            // return a list holding the trasaction type and the index of the trasaction in it's corresponding array
            strList = transactionIdStr.split("-");

            // select the trasacton's type
            transactionType = strList[0];

            // select the trasaction's id
            transactionIdNumber = parseInt(strList[1]);

            if (!isNaN(transactionIdNumber))
            {
                // delete the trasaction from the appropiate transaction array
                budgetCtrl.pblDeleteItem(transactionType, transactionIdNumber);

                // delete the transaction from the UI
                uiController.pblDeleteListItem(transactionIdStr);

                // update and show the new budget, total income, total expenses, expense percentage out of income
                prvUpdateBudget();
            }
            else {
                console.err("The value of the id attribute of %O, doesn't containg a number." +
                            "\nThe trasanction will not be removed from budgetController.prvData.allItems[%s]." +
                            "\nThe transaction will not dissapear from the UI." +
                            "\nThe financial situation overview panel from the UI will not change.", event.target.parentNode.parentNode.parentNode.parentNode,
                            transactionType);
            }

        }
    };

    return {
        initialiseVarsAndEvents: function() {
            console.log("App has started.");
            prvSetupEventListeners();
        }
    }

})(budgetController, uiController);

// start the app
controller.initialiseVarsAndEvents();

// *** App function library ***

// return a number with rounded n-th decimal
// value      Number  the floating point number to be rounded
// precision  Number  the position of the decimal to be rounded
//   E.g  precision = 1, the first digit shuld be rounded
//   E.g  precision = 2, the second digit shuld be rounded
function roundDecimal(value, precision) {
    var multiplier = Math.pow(10, precision || 0);
    return Math.round(value * multiplier) / multiplier;
}
<commit_msg>Rename file: from  js/app.js to js/controller.js<commit_after><|endoftext|>