<commit_before>var Radium = require('index.js');
var React = require('react/addons');

var {PrintStyleSheet} = Radium;
var {Component, PropTypes} = React;
var TestUtils = React.addons.TestUtils;

var getRenderOutput = function (element) {
  var renderer = TestUtils.createRenderer();
  renderer.render(element);
  return renderer.getRenderOutput();
};

describe('Radium blackbox tests', () => {
  it('merges styles', () => {
    @Radium
    class TestComponent extends Component {
      render () {
        return (

        );
      }
    }

    var output = getRenderOutput(<TestComponent />);

    expect(output.props.style).to.deep.equal(
      {color: 'blue', background: 'red'}
    );
  });

  it('merges nested styles', () => {
    @Radium
    class TestComponent extends Component {
      render () {
        return (

        );
      }
    }

    var output = getRenderOutput(<TestComponent />);

    expect(output.props.style).to.deep.equal(
      {color: 'blue', background: 'red', height: '2px', padding: '9px'}
    );
  });

  it('resolves styles on props', () => {
    class InnerComponent extends Component {}

    @Radium
    class TestComponent extends Component {
      render () {
        return (
          <InnerComponent header={

          } />
        );
      }
    }

    var output = getRenderOutput(<TestComponent />);

    expect(output.props.header.props.style).to.deep.equal(
      {color: 'blue', background: 'red'}
    );
  });

  it('resolves styles on props', () => {
    class InnerComponent extends Component {
      render () {
        return this.props.stuff;
      }
    }

    @Radium
    class TestComponent extends Component {
      render () {
        return (
          <InnerComponent stuff={

          } />
        );
      }
    }

    var output = TestUtils.renderIntoDocument(<TestComponent />);

    var div = React.findDOMNode(
      TestUtils.findRenderedDOMComponentWithTag(output, 'div')
    );

    expect(div.style.color).to.equal('blue');
    expect(div.style.background).to.equal('red');

    TestUtils.Simulate.mouseDown(div);

    expect(div.style.color).to.equal('green');
  });

  it('resolves styles on functions', () => {
    class InnerComponent extends Component {
      render () {
        return this.props.children('arg');
      }
    }

    @Radium
    class TestComponent extends Component {
      render () {
        return (
          <InnerComponent>{arg =>

              {arg}

          }</InnerComponent>
        );
      }
    }

    var output = TestUtils.renderIntoDocument(<TestComponent />);

    var div = React.findDOMNode(
      TestUtils.findRenderedDOMComponentWithTag(output, 'div')
    );

    expect(div.style.color).to.equal('blue');
    expect(div.style.background).to.equal('red');
    expect(div.textContent).to.equal('arg');

    TestUtils.Simulate.mouseDown(div);

    expect(div.style.color).to.equal('green');
  });

  it('adds hover styles', () => {
    @Radium
    class TestComponent extends Component {
      render () {
        return (

        );
      }
    }

    var output = TestUtils.renderIntoDocument(<TestComponent />);

    var div = React.findDOMNode(
      TestUtils.findRenderedDOMComponentWithTag(output, 'div')
    );

    expect(div.style.color).to.equal('blue');
    expect(div.style.background).to.equal('red');

    TestUtils.SimulateNative.mouseOver(div);

    expect(div.style.color).to.equal('green');
  });

  it('adds active styles', () => {
    @Radium
    class TestComponent extends Component {
      render () {
        return (

        );
      }
    }

    var output = TestUtils.renderIntoDocument(<TestComponent />);

    var div = React.findDOMNode(
      TestUtils.findRenderedDOMComponentWithTag(output, 'div')
    );

    expect(div.style.color).to.equal('blue');
    expect(div.style.background).to.equal('red');

    TestUtils.Simulate.mouseDown(div);

    expect(div.style.color).to.equal('green');
  });

  it('resolves styles on multiple elements nested far down, Issue #307', () => {
    @Radium
    class TestComponent extends Component {
      render () {
        return (

        );
      }
    }

    var output = TestUtils.renderIntoDocument(<TestComponent />);

    var header = React.findDOMNode(
      TestUtils.findRenderedDOMComponentWithTag(output, 'header')
    );
    expect(header.style.color).to.equal('yellow');

    var footer = React.findDOMNode(
      TestUtils.findRenderedDOMComponentWithTag(output, 'footer')
    );
    expect(footer.style.color).to.equal('green');

    TestUtils.SimulateNative.mouseOver(header);
    TestUtils.SimulateNative.mouseOver(footer);

    expect(header.style.color).to.equal('blue');
    expect(footer.style.color).to.equal('red');
  });

  it('applies print styles through the PrintStyle component', () => {
    Radium(React.createClass({
      displayName: 'TestComponent',

      statics: {
        printStyles: {
          foo: {color: 'blue'},
          bar: {background: 'red'}
        }
      },

      render () {
        return (

        );
      }
    }));

    class TestComponent2 extends Component {
      render () {
        return
;
      }
    }

    TestComponent2.displayName = 'TestComponent2';
    TestComponent2.printStyles = {
      main: {color: 'black'}
    };
    Radium(TestComponent2);

    var output = TestUtils.renderIntoDocument(<PrintStyleSheet />);

    var style = React.findDOMNode(
      TestUtils.findRenderedDOMComponentWithTag(output, 'style')
    );

    expect(style.innerText).to.equal(
      '@media print{' +
      '.Radium-TestComponent-foo{color: blue !important;}' +
      '.Radium-TestComponent-bar{background: red !important;}' +
      '.Radium-TestComponent2-main{color: black !important;}' +
      '}'
    );
  });

  it('resolves styles if an element has element children and spreads props', () => {
    @Radium
    class Inner extends Component {
      propTypes = { children: PropTypes.node }
      render () {
        return (

            {this.props.children}

        );
      }
    }

    @Radium
    class Outer extends Component {
      render () {
        return (
          <Inner>
            We will break you.
          </Inner>
        );
      }
    }

    var output = TestUtils.renderIntoDocument(<Outer />);

    var div = React.findDOMNode(
      TestUtils.findRenderedDOMComponentWithTag(output, 'div')
    );

    expect(div.style.color).to.equal('blue');
    expect(div.style.background).to.equal('red');
  });

  it('accepts a config', () => {
    var truthyMatchMedia = function () {
      return {
        matches: true,
        addListener: function () {},
        removeListener: function () {}
      };
    };

    @Radium({
      matchMedia: truthyMatchMedia
    })
    class TestComponent extends Component {
      render () {
        return (

        );
      }
    }

    var output = getRenderOutput(<TestComponent />);

    expect(output.props.style).to.deep.equal(
      {color: 'blue'}
    );
  });
});
<commit_msg>Fix child component getting _radiumDidResolveStyles and not running Radium<commit_after>var Radium = require('index.js');
var React = require('react/addons');

var {PrintStyleSheet} = Radium;
var {Component, PropTypes} = React;
var TestUtils = React.addons.TestUtils;

var getRenderOutput = function (element) {
  var renderer = TestUtils.createRenderer();
  renderer.render(element);
  return renderer.getRenderOutput();
};

describe('Radium blackbox tests', () => {
  it('merges styles', () => {
    @Radium
    class TestComponent extends Component {
      render () {
        return (

        );
      }
    }

    var output = getRenderOutput(<TestComponent />);

    expect(output.props.style).to.deep.equal(
      {color: 'blue', background: 'red'}
    );
  });

  it('merges nested styles', () => {
    @Radium
    class TestComponent extends Component {
      render () {
        return (

        );
      }
    }

    var output = getRenderOutput(<TestComponent />);

    expect(output.props.style).to.deep.equal(
      {color: 'blue', background: 'red', height: '2px', padding: '9px'}
    );
  });

  it('resolves styles on props', () => {
    class InnerComponent extends Component {}

    @Radium
    class TestComponent extends Component {
      render () {
        return (
          <InnerComponent header={

          } />
        );
      }
    }

    var output = getRenderOutput(<TestComponent />);

    expect(output.props.header.props.style).to.deep.equal(
      {color: 'blue', background: 'red'}
    );
  });

  it('resolves styles on props', () => {
    class InnerComponent extends Component {
      render () {
        return this.props.stuff;
      }
    }

    @Radium
    class TestComponent extends Component {
      render () {
        return (
          <InnerComponent stuff={

          } />
        );
      }
    }

    var output = TestUtils.renderIntoDocument(<TestComponent />);

    var div = React.findDOMNode(
      TestUtils.findRenderedDOMComponentWithTag(output, 'div')
    );

    expect(div.style.color).to.equal('blue');
    expect(div.style.background).to.equal('red');

    TestUtils.Simulate.mouseDown(div);

    expect(div.style.color).to.equal('green');
  });

  it('resolves styles on functions', () => {
    class InnerComponent extends Component {
      render () {
        return this.props.children('arg');
      }
    }

    @Radium
    class TestComponent extends Component {
      render () {
        return (
          <InnerComponent>{arg =>

              {arg}

          }</InnerComponent>
        );
      }
    }

    var output = TestUtils.renderIntoDocument(<TestComponent />);

    var div = React.findDOMNode(
      TestUtils.findRenderedDOMComponentWithTag(output, 'div')
    );

    expect(div.style.color).to.equal('blue');
    expect(div.style.background).to.equal('red');
    expect(div.textContent).to.equal('arg');

    TestUtils.Simulate.mouseDown(div);

    expect(div.style.color).to.equal('green');
  });

  it('adds hover styles', () => {
    @Radium
    class TestComponent extends Component {
      render () {
        return (

        );
      }
    }

    var output = TestUtils.renderIntoDocument(<TestComponent />);

    var div = React.findDOMNode(
      TestUtils.findRenderedDOMComponentWithTag(output, 'div')
    );

    expect(div.style.color).to.equal('blue');
    expect(div.style.background).to.equal('red');

    TestUtils.SimulateNative.mouseOver(div);

    expect(div.style.color).to.equal('green');
  });

  it('adds active styles', () => {
    @Radium
    class TestComponent extends Component {
      render () {
        return (

        );
      }
    }

    var output = TestUtils.renderIntoDocument(<TestComponent />);

    var div = React.findDOMNode(
      TestUtils.findRenderedDOMComponentWithTag(output, 'div')
    );

    expect(div.style.color).to.equal('blue');
    expect(div.style.background).to.equal('red');

    TestUtils.Simulate.mouseDown(div);

    expect(div.style.color).to.equal('green');
  });

  it('resolves styles on multiple elements nested far down, Issue #307', () => {
    @Radium
    class TestComponent extends Component {
      render () {
        return (

        );
      }
    }

    var output = TestUtils.renderIntoDocument(<TestComponent />);

    var header = React.findDOMNode(
      TestUtils.findRenderedDOMComponentWithTag(output, 'header')
    );
    expect(header.style.color).to.equal('yellow');

    var footer = React.findDOMNode(
      TestUtils.findRenderedDOMComponentWithTag(output, 'footer')
    );
    expect(footer.style.color).to.equal('green');

    TestUtils.SimulateNative.mouseOver(header);
    TestUtils.SimulateNative.mouseOver(footer);

    expect(header.style.color).to.equal('blue');
    expect(footer.style.color).to.equal('red');
  });

  it('applies print styles through the PrintStyle component', () => {
    Radium(React.createClass({
      displayName: 'TestComponent',

      statics: {
        printStyles: {
          foo: {color: 'blue'},
          bar: {background: 'red'}
        }
      },

      render () {
        return (

        );
      }
    }));

    class TestComponent2 extends Component {
      render () {
        return
;
      }
    }

    TestComponent2.displayName = 'TestComponent2';
    TestComponent2.printStyles = {
      main: {color: 'black'}
    };
    Radium(TestComponent2);

    var output = TestUtils.renderIntoDocument(<PrintStyleSheet />);

    var style = React.findDOMNode(
      TestUtils.findRenderedDOMComponentWithTag(output, 'style')
    );

    expect(style.innerText).to.equal(
      '@media print{' +
      '.Radium-TestComponent-foo{color: blue !important;}' +
      '.Radium-TestComponent-bar{background: red !important;}' +
      '.Radium-TestComponent2-main{color: black !important;}' +
      '}'
    );
  });

  it('resolves styles if an element has element children and spreads props', () => {
    @Radium
    class Inner extends Component {
      propTypes = { children: PropTypes.node }
      render () {
        return (

            {this.props.children}

        );
      }
    }

    @Radium
    class Outer extends Component {
      render () {
        return (
          <Inner>
            We will break you.
          </Inner>
        );
      }
    }

    var output = TestUtils.renderIntoDocument(<Outer />);

    var div = React.findDOMNode(
      TestUtils.findRenderedDOMComponentWithTag(output, 'div')
    );

    expect(div.style.color).to.equal('blue');
    expect(div.style.background).to.equal('red');
  });

  it('accepts a config', () => {
    var truthyMatchMedia = function () {
      return {
        matches: true,
        addListener: function () {},
        removeListener: function () {}
      };
    };

    @Radium({
      matchMedia: truthyMatchMedia
    })
    class TestComponent extends Component {
      render () {
        return (

        );
      }
    }

    var output = getRenderOutput(<TestComponent />);

    expect(output.props.style).to.deep.equal(
      {color: 'blue'}
    );
  });

  it('resolves styles if an element has element children and spreads props', () => {
    @Radium
    class Inner extends Component {
      render () {
        return (

            {this.props.children}

        );
      }
    }

    @Radium
    class Outer extends Component {
      render () {
        return (
          <Inner>
            We will break you.
          </Inner>
        );
      }
    }

    var output = TestUtils.renderIntoDocument(<Outer />);

    var div = React.findDOMNode(
      TestUtils.findRenderedDOMComponentWithTag(output, 'div')
    );

    expect(div.style.color).to.equal('blue');
    expect(div.style.background).to.equal('red');
  });
});
<|endoftext|>


<commit_before>var osm = {cpan: {}, leftpan: {on: false}, mappan: {}, ui: {fs: false}, layers:{}};
var search = {};

function $(id) { return document.getElementById(id); }

function setView(position) {
  osm.map.setView(new L.LatLng(position.coords.latitude, position.coords.longitude), 10);
}

function init() {
  parseGET();
  var w;
  if (self.innerHeight) w = self.innerWidth;
  else if (document.documentElement && document.documentElement.clientHeight) w = document.documentElement.clientWidth;
  else if (document.body) w = document.body.clientWidth;
  osm.layers.layerOSM = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {maxZoom: 18, attribution: 'Map data © OpenStreetMap contributors'});
  osm.map = new L.Map('map', {zoomControl: true, center: new L.LatLng(62.0, 88.0), zoom: (w > 1200 ? 3 : 2), layers: [osm.layers.layerOSM]});

  osm.layers.search_marker = new L.LayerGroup();
  osm.layers.osb = new L.OpenStreetBugs();
  osm.map.addLayer(osm.layers.search_marker);
  osm.map.control_layers = new L.Control.Layers({'OSM':osm.layers.layerOSM}, {'отметки поиска':osm.layers.search_marker, 'Bugs':osm.layers.osb});
  osm.map.addControl(osm.map.control_layers);

  osm.leftpan.panel = $('leftpan');
  osm.leftpan.content = $('content_pan');
  osm.mappan.panel = $('mappan');
  osm.input = $('qsearch');
  osm.search_marker = new L.LayerGroup();
  osm.map.addLayer(osm.search_marker);

  osm.map.addControl(new L.Control.Permalink());

  search.inLoad();
  osm.setLinkOSB();
};

osm.setLinkOSB = function() {
  if (parseInt(get['bugid'])) {
    osm.map.addLayer(osm.layers.osb);
    osm.map.control_layers._update();
  }
};

osm.leftpan.toggle = function(on) {
  if (typeof on == "undefined") on = !this.on;
  var center = osm.map.getCenter();
  if (on != this.on) {
    if (on) {
      this.on = true;
      $('downpan').className = '';
    }
    else {
      this.on = false;
      $('downpan').className = 'left-on';
    }
    osm.map.invalidateSize();
  }
};

search.processResults = function() {
  try {
    if (this.request.readyState == 4) {
      if (this.request.status == 200) {
        var results = eval('(' + this.request.responseText + ')');
        if (results.find==0) {
          osm.leftpan.content.innerHTML='Ничего не найдено по запросу "' + (results.search)  + '"';
        }
        else if (results.find==1 && results.accuracy_find==0) {
          osm.leftpan.content.innerHTML='Пожалуйста, уточните запрос "' + (results.search) + '"';
        }
        else {
          //var results = eval('(' + this.request.responseText + ')');
          var content = '
';
          osm.layers.search_marker.clearLayers();
          var MyIcon = L.Icon.extend({
            iconUrl: '../img/marker.png',
            shadowUrl: '../img/marker-shadow.png',
            iconSize: new L.Point(18, 29),
            shadowSize: new L.Point(29, 29),
            iconAnchor: new L.Point(8, 29),
            popupAnchor: new L.Point(-8, -50)
          });
          var icon = new MyIcon();
          var matches=results.matches;
          for (var i in matches) {
            content += ('
' + matches[i].display_name + '
');
            marker = new L.Marker(new L.LatLng(matches[i].lat, matches[i].lon),{icon: icon});
            marker.bindPopup("Адрес:
 " + matches[i].display_name);
            osm.layers.search_marker.addLayer(marker);
          }
          osm.map.setView(new L.LatLng(matches[0].lat, matches[0].lon), 11);
          content += '
';
          osm.leftpan.content.innerHTML = content;
        }
      }
    }
  }
  catch(e) {
      osm.leftpan.content.innerHTML = 'Ошибка: ' + e.description + '
 Ответ поиск.серв.: '+this.request.responseText;
  }
};

search.search = function(inQuery) {
  inQuery = inQuery || osm.input.value;
  osm.input.value = inQuery;
  if (inQuery.length < 1)
    return false;
  mapCenter=osm.map.getCenter();
  osm.leftpan.toggle(true);
  this.request = new XMLHttpRequest();
  //this.request.open('GET', 'http://nominatim.openstreetmap.org/search?q=' + encodeURIComponent(osm.input.value) + '&format=json');
  this.request.open('GET', '/api/search?q=' + encodeURIComponent(inQuery) + '&accuracy=1' + '&lat=' + mapCenter.lat + '&lon=' + mapCenter.lng);
  this.request.onreadystatechange = function(){search.processResults(this)};
  this.request.send(null);
  return false;
};

search.inLoad = function() {
  var query = get['q'] || '';
  if (query != '')
    search.search(query);
};

function parseGET() {
  var tmp = new Array();
  var tmp2 = new Array();
  get = new Array();
  var url = location.search;
  if(url != '') {
    tmp = (url.substr(1)).split('&');
    for(var i=0; i < tmp.length; i++) {
      tmp2 = tmp[i].split('=');
      get[tmp2[0]] = decodeURIComponent(tmp2[1].replace(/\+/g, " ")).split(",");
    }
  }
};

osm.onPermalink = function () {
  mapCenter=osm.map.getCenter();
  osm.permalink.href = 'http://' + location.host + '?lat=' + mapCenter.lat + '&lon=' + mapCenter.lng + '&zoom=' + osm.map._zoom;
};

osm.ui.whereima = function() {
  navigator.geolocation.getCurrentPosition(setView);
};

osm.ui.togglefs = function() {
  if (osm.ui.fs) {
    document.body.className = '';
    $('fsbutton').innerHTML = '↑';
  }
  else {
    document.body.className = 'fs';
    $('fsbutton').innerHTML = '↓';
  }
  osm.ui.fs = !osm.ui.fs;
};

osm.ui.searchsubmit = function() {
  return search.search($('qsearch').value);
}<commit_msg>Add more default OSM layers (osmarender & cyclemap)<commit_after>var osm = {cpan: {}, leftpan: {on: false}, mappan: {}, ui: {fs: false}, layers:{}};
var search = {};

function $(id) { return document.getElementById(id); }

function setView(position) {
  osm.map.setView(new L.LatLng(position.coords.latitude, position.coords.longitude), 10);
}

function init() {
  parseGET();
  var w;
  if (self.innerHeight) w = self.innerWidth;
  else if (document.documentElement && document.documentElement.clientHeight) w = document.documentElement.clientWidth;
  else if (document.body) w = document.body.clientWidth;
  osm.layers.layerMapnik = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {maxZoom: 18, attribution: 'Map data © OpenStreetMap contributors'});
  osm.layers.layerTAH = new L.TileLayer('http://{s}.tah.openstreetmap.org/Tiles/tile/{z}/{x}/{y}.png', {maxZoom: 18, attribution: 'Map data © OpenStreetMap contributors'});
  osm.layers.layerCycle = new L.TileLayer('http://{s}.tile.opencyclemap.org/cycle/{z}/{x}/{y}.png', {maxZoom: 18, attribution: 'Map data © OpenStreetMap contributors'});
  osm.map = new L.Map('map', {zoomControl: true, center: new L.LatLng(62.0, 88.0), zoom: (w > 1200 ? 3 : 2), layers: [osm.layers.layerMapnik]});

  osm.layers.search_marker = new L.LayerGroup();
  osm.layers.osb = new L.OpenStreetBugs();
  osm.map.addLayer(osm.layers.search_marker);
  osm.map.control_layers = new L.Control.Layers({'Mapnik':osm.layers.layerMapnik, 'Osmarender':osm.layers.layerTAH, 'Карта для велосипедистов':osm.layers.layerCycle}, {'отметки поиска':osm.layers.search_marker, 'Bugs':osm.layers.osb});
  osm.map.addControl(osm.map.control_layers);

  osm.leftpan.panel = $('leftpan');
  osm.leftpan.content = $('content_pan');
  osm.mappan.panel = $('mappan');
  osm.input = $('qsearch');
  osm.search_marker = new L.LayerGroup();
  osm.map.addLayer(osm.search_marker);

  osm.map.addControl(new L.Control.Permalink());

  search.inLoad();
  osm.setLinkOSB();
};

osm.setLinkOSB = function() {
  if (parseInt(get['bugid'])) {
    osm.map.addLayer(osm.layers.osb);
    osm.map.control_layers._update();
  }
};

osm.leftpan.toggle = function(on) {
  if (typeof on == "undefined") on = !this.on;
  var center = osm.map.getCenter();
  if (on != this.on) {
    if (on) {
      this.on = true;
      $('downpan').className = '';
    }
    else {
      this.on = false;
      $('downpan').className = 'left-on';
    }
    osm.map.invalidateSize();
  }
};

search.processResults = function() {
  try {
    if (this.request.readyState == 4) {
      if (this.request.status == 200) {
        var results = eval('(' + this.request.responseText + ')');
        if (results.find==0) {
          osm.leftpan.content.innerHTML='Ничего не найдено по запросу "' + (results.search)  + '"';
        }
        else if (results.find==1 && results.accuracy_find==0) {
          osm.leftpan.content.innerHTML='Пожалуйста, уточните запрос "' + (results.search) + '"';
        }
        else {
          //var results = eval('(' + this.request.responseText + ')');
          var content = '
';
          osm.layers.search_marker.clearLayers();
          var MyIcon = L.Icon.extend({
            iconUrl: '../img/marker.png',
            shadowUrl: '../img/marker-shadow.png',
            iconSize: new L.Point(18, 29),
            shadowSize: new L.Point(29, 29),
            iconAnchor: new L.Point(8, 29),
            popupAnchor: new L.Point(-8, -50)
          });
          var icon = new MyIcon();
          var matches=results.matches;
          for (var i in matches) {
            content += ('
' + matches[i].display_name + '
');
            marker = new L.Marker(new L.LatLng(matches[i].lat, matches[i].lon),{icon: icon});
            marker.bindPopup("Адрес:
 " + matches[i].display_name);
            osm.layers.search_marker.addLayer(marker);
          }
          osm.map.setView(new L.LatLng(matches[0].lat, matches[0].lon), 11);
          content += '
';
          osm.leftpan.content.innerHTML = content;
        }
      }
    }
  }
  catch(e) {
      osm.leftpan.content.innerHTML = 'Ошибка: ' + e.description + '
 Ответ поиск.серв.: '+this.request.responseText;
  }
};

search.search = function(inQuery) {
  inQuery = inQuery || osm.input.value;
  osm.input.value = inQuery;
  if (inQuery.length < 1)
    return false;
  mapCenter=osm.map.getCenter();
  osm.leftpan.toggle(true);
  this.request = new XMLHttpRequest();
  //this.request.open('GET', 'http://nominatim.openstreetmap.org/search?q=' + encodeURIComponent(osm.input.value) + '&format=json');
  this.request.open('GET', '/api/search?q=' + encodeURIComponent(inQuery) + '&accuracy=1' + '&lat=' + mapCenter.lat + '&lon=' + mapCenter.lng);
  this.request.onreadystatechange = function(){search.processResults(this)};
  this.request.send(null);
  return false;
};

search.inLoad = function() {
  var query = get['q'] || '';
  if (query != '')
    search.search(query);
};

function parseGET() {
  var tmp = new Array();
  var tmp2 = new Array();
  get = new Array();
  var url = location.search;
  if(url != '') {
    tmp = (url.substr(1)).split('&');
    for(var i=0; i < tmp.length; i++) {
      tmp2 = tmp[i].split('=');
      get[tmp2[0]] = decodeURIComponent(tmp2[1].replace(/\+/g, " ")).split(",");
    }
  }
};

osm.onPermalink = function () {
  mapCenter=osm.map.getCenter();
  osm.permalink.href = 'http://' + location.host + '?lat=' + mapCenter.lat + '&lon=' + mapCenter.lng + '&zoom=' + osm.map._zoom;
};

osm.ui.whereima = function() {
  navigator.geolocation.getCurrentPosition(setView);
};

osm.ui.togglefs = function() {
  if (osm.ui.fs) {
    document.body.className = '';
    $('fsbutton').innerHTML = '↑';
  }
  else {
    document.body.className = 'fs';
    $('fsbutton').innerHTML = '↓';
  }
  osm.ui.fs = !osm.ui.fs;
};

osm.ui.searchsubmit = function() {
  return search.search($('qsearch').value);
}
<|endoftext|>


<commit_before>(function (global){
  'use strict';

  global.angular.module('components.task', [])
    // Configuration
    .constant('ApiConfig', {
      BASE_URL: global.config.apiUrl
    })

    // Resource
    .factory('TaskModel', ['$resource', 'ApiConfig', function TaskModel($resource, ApiConfig) {

      var taskResource = $resource(ApiConfig.BASE_URL + '/tasks/:taskId',
        {
          taskId: '@_id'
        },
        {
          save: {
            method: 'PUT'
          }
        }
      );

      return taskResource;
    }])

    // Directive viewer
    .directive('task', ['TaskModel', function Task(TaskModel) {

      function link(scope) {
        scope.editTask = function editTask() {
          if(scope.task.done) {
            return;
          }

          scope.edit(scope.task);
        };

        scope.$watch('task.done', function process() {
          scope.task.$save();
        });
      }

      return {
        restrict: 'EA',
        templateUrl: 'components/task/task.html',
        link: link,
        scope: {
          task: '=model',
          edit: '=onEdit'
        }
      };
    }])

    // Directive editor
    .directive('taskEditor', ['TaskModel', function Task(TaskModel) {

      function link(scope) {

        scope.editTitle = scope.task.title;
        scope.editBody  = scope.task.body;

        scope.save = function save() {
          scope.task.body  = scope.editBody;
          scope.task.title = scope.editTitle;
          scope.task.$save();
          scope.cancel();
        };
      }

      return {
        restrict: 'EA',
        templateUrl: 'components/task/task-editor.html',
        link: link,
        scope: {
          task: '=model',
          cancel: '=onCancel'
        }
      };
    }]);
}(window));<commit_msg>Add create POST method to Task resource<commit_after>(function (global){
  'use strict';

  global.angular.module('components.task', [])
    // Configuration
    .constant('ApiConfig', {
      BASE_URL: global.config.apiUrl
    })

    // Resource
    .factory('TaskModel', ['$resource', 'ApiConfig', function TaskModel($resource, ApiConfig) {

      var taskResource = $resource(ApiConfig.BASE_URL + '/tasks/:taskId',
        {
          taskId: '@_id'
        },
        {
          save: {
            method: 'PUT'
          },
          create: {
            method: 'POST'
          }
        }
      );

      return taskResource;
    }])

    // Directive viewer
    .directive('task', ['TaskModel', function Task(TaskModel) {

      function link(scope) {
        scope.editTask = function editTask() {
          if(scope.task.done) {
            return;
          }

          scope.edit(scope.task);
        };

        scope.$watch('task.done', function process() {
          scope.task.$save();
        });
      }

      return {
        restrict: 'EA',
        templateUrl: 'components/task/task.html',
        link: link,
        scope: {
          task: '=model',
          edit: '=onEdit'
        }
      };
    }])

    // Directive editor
    .directive('taskEditor', ['TaskModel', function Task(TaskModel) {

      function link(scope) {

        scope.editTitle = scope.task.title;
        scope.editBody  = scope.task.body;

        scope.save = function save() {
          scope.task.body  = scope.editBody;
          scope.task.title = scope.editTitle;
          scope.task.$save();
          scope.cancel();
        };
      }

      return {
        restrict: 'EA',
        templateUrl: 'components/task/task-editor.html',
        link: link,
        scope: {
          task: '=model',
          cancel: '=onCancel'
        }
      };
    }]);
}(window));<|endoftext|>


<commit_before>
angular.module('forms', [
	'duScroll', 'ngResource', 'NodeForm.templates', 'pascalprecht.translate',
	'angular-input-stars',
	'ui.select'
]);

angular.module('NodeForm', [
    'ui.select', 'cgBusy', 'ngSanitize', 'vButton', 'ngResource',
    'ui.router', 'ui.bootstrap', 'ui.utils', 'ngRaven', 'forms',
	'ui.select'
]);

angular.module('forms').factory('Auth', [
  function() {
    var service = {
      _currentUser: null,
      get currentUser(){
        return this._currentUser;
      },
      ensureHasCurrentUser: function() {
        return null;
      },
      isAuthenticated: function() {
        return false;
      },
      getUserState: function() {
        return '';
      },
      login: function() {
      },
      logout: function() {
      },
    };
    return service;
  }
]);
angular.module('forms').factory('$state', [function() {
    return {
        go: function() {}
    };
}]);
angular.module('forms').factory('myForm', ['Forms', function(Forms) {
    var form = window.form;
    form.visible_form_fields = _.filter(form.form_fields, function(field){
    	return (field.deletePreserved === false);
    });
    return form;
}]);
angular.module('forms').constant('FORM_URL', '/form/:formId');

angular.element(document).ready(function() {
	//Then init the app
	angular.bootstrap(document, ['forms']);
});
<commit_msg>fake  SendVisitorDataProvider<commit_after>
angular.module('forms', [
	'duScroll', 'ngResource', 'NodeForm.templates', 'pascalprecht.translate',
	'angular-input-stars',
	'ui.select'
]);

angular.module('NodeForm', [
    'ui.select', 'cgBusy', 'ngSanitize', 'vButton', 'ngResource',
    'ui.router', 'ui.bootstrap', 'ui.utils', 'ngRaven', 'forms',
	'ui.select'
]);

angular.module('forms').factory('Auth', [
  function() {
    var service = {
      _currentUser: null,
      get currentUser(){
        return this._currentUser;
      },
      ensureHasCurrentUser: function() {
        return null;
      },
      isAuthenticated: function() {
        return false;
      },
      getUserState: function() {
        return '';
      },
      login: function() {
      },
      logout: function() {
      },
    };
    return service;
  }
]);
angular.module('forms').factory('$state', [function() {
    return {
        go: function() {}
    };
}]);
angular.module('forms').factory('myForm', ['Forms', function(Forms) {
    var form = window.form;
    form.visible_form_fields = _.filter(form.form_fields, function(field){
    	return (field.deletePreserved === false);
    });
    return form;
}]);
angular.module('forms').constant('FORM_URL', '/form/:formId');

angular.module('forms').value('SendVisitorData', {
	send: function(){}
});

angular.element(document).ready(function() {
	//Then init the app
	angular.bootstrap(document, ['forms']);
});
<|endoftext|>


<commit_before>import React from 'react';

import SPELLS from 'common/SPELLS';

import Wrapper from 'common/Wrapper';

import CoreChecklist, { Rule, Requirement, GenericCastEfficiencyRequirement } from 'Parser/Core/Modules/Features/Checklist';
import CastEfficiency from 'Parser/Core/Modules/CastEfficiency';
import Combatants from 'Parser/Core/Modules/Combatants';

import CancelledCasts from '../../../Shared/Modules/Features/CancelledCasts';
import AlwaysBeCasting from './AlwaysBeCasting';
import WintersChill from './WintersChill';
import BrainFreeze from './BrainFreeze';
import IceLance from './IceLance';

class Checklist extends CoreChecklist {
  static dependencies = {
    castEfficiency: CastEfficiency,
    combatants: Combatants,
    alwaysBeCasting: AlwaysBeCasting,
    cancelledCasts: CancelledCasts,
    wintersChill: WintersChill,
    brainFreeze: BrainFreeze,
    iceLance: IceLance,
  };

  rules = [
    new Rule({
      name: 'Always Be Casting',
      description: <Wrapper>Continuously chaining casts throughout an encounter is the single most important thing for achieving good DPS as a caster. There shoule be no delay at all between your spell casts, it's better to start casting the wrong spell than to think for a few seconds and then cast the right spell. You should be able to handle a fight's mechanics with the minimum possible interruption to your casting.</Wrapper>,
      requirements: () => {
        return [
          new Requirement({
            name: 'Downtime',
            check: () => this.alwaysBeCasting.downtimeSuggestionThresholds,
          }),
          new Requirement({
            name: 'Cancelled Casts',
            check: () => this.cancelledCasts.cancelledCastSuggestionThresholds,
          }),
        ];
      },
    }),
    new Rule({
      name: 'Use Your Procs',
      description: <Wrapper>Frost Mage is a heavily proc dependent spec, so using your procs correctly is very important.</Wrapper>,
      requirements: () => {
        return [
          new Requirement({
            name: "Use Brain Freeze procs",
            check: () => this.brainFreeze.brainFreezeUtilSuggestionThresholds,
          }),
          new Requirement({
            name: "Use Fingers of Frost procs",
            check: () => this.iceLance.fingersUtilSuggestionThresholds,
          }),
          new Requirement({
            name: "Ice Lance into Winter's Chill",
            check: () => this.wintersChill.iceLanceUtilSuggestionThresholds,
          }),
          new Requirement({
            name: "Hardcast into Winter's Chill",
            check: () => this.wintersChill.hardcastUtilSuggestionThresholds,
          }),
        ];
      },
    }),
    new Rule({
      name: 'Use Your Cooldowns',
      description: <Wrapper>Your cooldowns are a major contributor to your DPS, and should be used as frequently as possible throughout a fight. A cooldown should be held on to only if a priority DPS phase is coming soon. Holding cooldowns too long will hurt your DPS.</Wrapper>,
      requirements: () => {
        const combatant = this.combatants.selected;
        return [
          new GenericCastEfficiencyRequirement({
            spell: SPELLS.FROZEN_ORB,
          }),
          new GenericCastEfficiencyRequirement({
            spell: SPELLS.EBONBOLT,
          }),
          new GenericCastEfficiencyRequirement({
            spell: SPELLS.ICY_VEINS,
          }),
          new GenericCastEfficiencyRequirement({
            spell: SPELLS.RAY_OF_FROST_TALENT,
            when: combatant.hasTalent(SPELLS.RAY_OF_FROST_TALENT.id),
          }),
          new GenericCastEfficiencyRequirement({
            spell: SPELLS.MIRROR_IMAGE_TALENT,
            when: combatant.hasTalent(SPELLS.MIRROR_IMAGE_TALENT.id),
          }),
          new GenericCastEfficiencyRequirement({
            spell: SPELLS.RUNE_OF_POWER_TALENT,
            when: combatant.hasTalent(SPELLS.RUNE_OF_POWER_TALENT.id),
          }),
          new GenericCastEfficiencyRequirement({
            spell: SPELLS.ICE_NOVA_TALENT,
            when: combatant.hasTalent(SPELLS.ICE_NOVA_TALENT.id),
          }),
          new GenericCastEfficiencyRequirement({
            spell: SPELLS.COMET_STORM_TALENT,
            when: combatant.hasTalent(SPELLS.COMET_STORM_TALENT.id),
          }),
        ];
      },
    }),
  ];
}

export default Checklist;
<commit_msg>[frost mage] Added checklist TODOs<commit_after>import React from 'react';

import SPELLS from 'common/SPELLS';

import Wrapper from 'common/Wrapper';

import CoreChecklist, { Rule, Requirement, GenericCastEfficiencyRequirement } from 'Parser/Core/Modules/Features/Checklist';
import CastEfficiency from 'Parser/Core/Modules/CastEfficiency';
import Combatants from 'Parser/Core/Modules/Combatants';

import CancelledCasts from '../../../Shared/Modules/Features/CancelledCasts';
import AlwaysBeCasting from './AlwaysBeCasting';
import WintersChill from './WintersChill';
import BrainFreeze from './BrainFreeze';
import IceLance from './IceLance';

class Checklist extends CoreChecklist {
  static dependencies = {
    castEfficiency: CastEfficiency,
    combatants: Combatants,
    alwaysBeCasting: AlwaysBeCasting,
    cancelledCasts: CancelledCasts,
    wintersChill: WintersChill,
    brainFreeze: BrainFreeze,
    iceLance: IceLance,
  };

  rules = [
    new Rule({
      name: 'Always Be Casting',
      description: <Wrapper>Continuously chaining casts throughout an encounter is the single most important thing for achieving good DPS as a caster. There shoule be no delay at all between your spell casts, it's better to start casting the wrong spell than to think for a few seconds and then cast the right spell. You should be able to handle a fight's mechanics with the minimum possible interruption to your casting.</Wrapper>,
      requirements: () => {
        return [
          new Requirement({
            name: 'Downtime',
            check: () => this.alwaysBeCasting.downtimeSuggestionThresholds,
          }),
          new Requirement({
            name: 'Cancelled Casts',
            check: () => this.cancelledCasts.cancelledCastSuggestionThresholds,
          }),
        ];
      },
    }),
    new Rule({
      name: 'Use Your Procs',
      description: <Wrapper>Frost Mage is a heavily proc dependent spec, so using your procs correctly is very important.</Wrapper>,
      requirements: () => {
        return [
          new Requirement({
            name: "Use Brain Freeze procs",
            check: () => this.brainFreeze.brainFreezeUtilSuggestionThresholds,
          }),
          new Requirement({
            name: "Use Fingers of Frost procs",
            check: () => this.iceLance.fingersUtilSuggestionThresholds,
          }),
          new Requirement({
            name: "Ice Lance into Winter's Chill",
            check: () => this.wintersChill.iceLanceUtilSuggestionThresholds,
          }),
          new Requirement({
            name: "Hardcast into Winter's Chill",
            check: () => this.wintersChill.hardcastUtilSuggestionThresholds,
          }),
        ];
      },
    }),
    new Rule({
      name: 'Use Your Cooldowns',
      description: <Wrapper>Your cooldowns are a major contributor to your DPS, and should be used as frequently as possible throughout a fight. A cooldown should be held on to only if a priority DPS phase is coming soon. Holding cooldowns too long will hurt your DPS.</Wrapper>,
      requirements: () => {
        const combatant = this.combatants.selected;
        return [
          new GenericCastEfficiencyRequirement({
            spell: SPELLS.FROZEN_ORB,
          }),
          new GenericCastEfficiencyRequirement({
            spell: SPELLS.EBONBOLT,
          }),
          new GenericCastEfficiencyRequirement({
            spell: SPELLS.ICY_VEINS,
          }),
          new GenericCastEfficiencyRequirement({
            spell: SPELLS.RAY_OF_FROST_TALENT,
            when: combatant.hasTalent(SPELLS.RAY_OF_FROST_TALENT.id),
          }),
          new GenericCastEfficiencyRequirement({
            spell: SPELLS.MIRROR_IMAGE_TALENT,
            when: combatant.hasTalent(SPELLS.MIRROR_IMAGE_TALENT.id),
          }),
          new GenericCastEfficiencyRequirement({
            spell: SPELLS.RUNE_OF_POWER_TALENT,
            when: combatant.hasTalent(SPELLS.RUNE_OF_POWER_TALENT.id),
          }),
          new GenericCastEfficiencyRequirement({
            spell: SPELLS.ICE_NOVA_TALENT,
            when: combatant.hasTalent(SPELLS.ICE_NOVA_TALENT.id),
          }),
          new GenericCastEfficiencyRequirement({
            spell: SPELLS.COMET_STORM_TALENT,
            when: combatant.hasTalent(SPELLS.COMET_STORM_TALENT.id),
          }),
        ];
      },
    }),

    // TODO add Talent Usage rule

    // TODO add Be Prepared rule

  ];
}

export default Checklist;
<|endoftext|>


<commit_before>var getArticleInfo = new XMLHttpRequest();

getArticleInfo.onreadystatechange = loadText;
getArticleInfo.open("GET", "articleName.txt");
getArticleInfo.send();

function loadText() {
  var text = document.getElementById("textTarget");
    if (getArticleInfo.readyState === 4) {
      if (getArticleInfo.status === 200) {
        text.innerHTML = getArticleInfo.responseText;
      } else {
        console.log('There was a problem with the request.');
      }
    }
};
<commit_msg>fix code indentation in sample01/scripts.js<commit_after>var getArticleInfo = new XMLHttpRequest();

getArticleInfo.onreadystatechange = loadText;
getArticleInfo.open("GET", "articleName.txt");
getArticleInfo.send();

function loadText() {
  var text = document.getElementById("textTarget");
  if (getArticleInfo.readyState === 4) {
    if (getArticleInfo.status === 200) {
      text.innerHTML = getArticleInfo.responseText;
    } else {
      console.log('There was a problem with the request.');
    }
  }
};
<|endoftext|>


<commit_before>/**
 * @desc Navigate with Keyboard from an article to another on an article's page
 * @param string leftURL - URL of the article on the left
 * @param string rightURL - URL of the article on the right
 */

function navigateKeyboard(leftURL, rightURL) {
  window.addEventListener("keydown", function (event) {
    var key = event.which || event.keyCode; // event.keyCode is used for IE8 and earlier versions
    switch (key) {
      case 37:
       goLeft(leftURL); // left arrow
      break;
      case 72:
        goLeft(leftURL); // h letter (vim style)
      break;

      case 39:
        goRight(rightURL); // right arrow
      break;
      case 76:
        goRight(rightURL); // l letter (vim style)
      break;
      case 8:
        window.history.back();

    }

  }, false);
}

function goLeft(leftURL) {
   if (leftURL != "?view=view&id=") {
          window.location = window.location.origin + window.location.pathname + leftURL;
  }
}

function goRight(rightURL) {
  if (rightURL != "?view=view&id=") {
        window.location = window.location.origin + window.location.pathname + rightURL;
  }
}

/**
 * @desc Do actions with Keyboard on an article's page
 * @param number id - ID of the current article
 */

function actionArticle(id) {
  window.addEventListener("keydown", function (event) {
    var key = event.which || event.keyCode; // event.keyCode is used for IE8 and earlier versions
    switch (key) {
      case 46:
       deleteArticle(id); // delete key
      break;
      case 68:
        deleteArticle(id); // d key letter
      break;
      case 70:
        favoriteArticle(id); // f key letter
      break;
      case 77:
        markReadArticle(id); // m key letter
      break;
    }

  }, false);
}

function deleteArticle(id) {
   if (id) {
          window.location = window.location.origin + window.location.pathname + '?action=delete&id=' + id;
  }
}

function favoriteArticle(id) {
   if (id) {
          window.location = window.location.origin + window.location.pathname + '?action=toggle_fav&id=' + id;
  }
}

function markReadArticle(id) {
   if (id) {
          window.location = window.location.origin + window.location.pathname + '?action=toggle_archive&id=' + id;
  }
}

function homeNavigation() {
  selectedArticle = $('.entrie:first');
  window.addEventListener("keydown", function (event) {
    var key = event.which || event.keyCode; // event.keyCode is used for IE8 and earlier versions
    switch (key) {
      case 37: // left arrow
       selectedArticle = goSelectPrev(selectedArticle,1);
      break;
      case 72: // h letter (vim style)
        selectedArticle = goSelectPrev(selectedArticle,1);
      break;

      case 39: // right arrow
        selectedArticle = goSelectNext(selectedArticle,1);
      break;
      case 76: // l letter (vim style)
        selectedArticle = goSelectNext(selectedArticle,1);
      break;
      case 13: // enter into article
        enterArticle(selectedArticle);
      break;
      case 74: // j letter key
        selectedArticle = goSelectNext(selectedArticle,3);
      break;
      case 40: // down arrow
        selectedArticle = goSelectNext(selectedArticle,3);
      break;
      case 75: // k letter key
        selectedArticle = goSelectNext(selectedArticle,3);
      break;
      case 38: // up arrow
        selectedArticle = goSelectNext(selectedArticle,3);
      break;
    }

  }, false);
}

function goSelectNext(selectedArticle,number) {
  if (selectedArticle.next().length) {
    selectedArticle.removeClass("eselected");
    selectedArticle = selectedArticle.next();
    selectedArticle.addClass("eselected");
  }
  return selectedArticle;
}

function goSelectPrev(selectedArticle,number) {
  if (selectedArticle.prev().length) {
    selectedArticle.removeClass("eselected");
    selectedArticle = selectedArticle.prev();
    selectedArticle.addClass("eselected");
  }
  return selectedArticle;
}

function enterArticle(selectedArticle) {
  window.location = selectedArticle.find('a:first').attr('href');
}<commit_msg>fix saving URL with enter key<commit_after>/**
 * @desc Navigate with Keyboard from an article to another on an article's page
 * @param string leftURL - URL of the article on the left
 * @param string rightURL - URL of the article on the right
 */

function navigateKeyboard(leftURL, rightURL) {
  window.addEventListener("keydown", function (event) {
    var key = event.which || event.keyCode; // event.keyCode is used for IE8 and earlier versions
    switch (key) {
      case 37:
       goLeft(leftURL); // left arrow
      break;
      case 72:
        goLeft(leftURL); // h letter (vim style)
      break;

      case 39:
        goRight(rightURL); // right arrow
      break;
      case 76:
        goRight(rightURL); // l letter (vim style)
      break;
      case 8:
        window.history.back();

    }

  }, false);
}

function goLeft(leftURL) {
   if (leftURL != "?view=view&id=") {
          window.location = window.location.origin + window.location.pathname + leftURL;
  }
}

function goRight(rightURL) {
  if (rightURL != "?view=view&id=") {
        window.location = window.location.origin + window.location.pathname + rightURL;
  }
}

/**
 * @desc Do actions with Keyboard on an article's page
 * @param number id - ID of the current article
 */

function actionArticle(id) {
  window.addEventListener("keydown", function (event) {
    var key = event.which || event.keyCode; // event.keyCode is used for IE8 and earlier versions
    switch (key) {
      case 46:
       deleteArticle(id); // delete key
      break;
      case 68:
        deleteArticle(id); // d key letter
      break;
      case 70:
        favoriteArticle(id); // f key letter
      break;
      case 77:
        markReadArticle(id); // m key letter
      break;
    }

  }, false);
}

function deleteArticle(id) {
   if (id) {
          window.location = window.location.origin + window.location.pathname + '?action=delete&id=' + id;
  }
}

function favoriteArticle(id) {
   if (id) {
          window.location = window.location.origin + window.location.pathname + '?action=toggle_fav&id=' + id;
  }
}

function markReadArticle(id) {
   if (id) {
          window.location = window.location.origin + window.location.pathname + '?action=toggle_archive&id=' + id;
  }
}

function homeNavigation() {
  selectedArticle = $('.entrie:first');
  window.addEventListener("keydown", function (event) {
    var key = event.which || event.keyCode; // event.keyCode is used for IE8 and earlier versions
    switch (key) {
      case 37: // left arrow
       selectedArticle = goSelectPrev(selectedArticle,1);
      break;
      case 72: // h letter (vim style)
        selectedArticle = goSelectPrev(selectedArticle,1);
      break;

      case 39: // right arrow
        selectedArticle = goSelectNext(selectedArticle,1);
      break;
      case 76: // l letter (vim style)
        selectedArticle = goSelectNext(selectedArticle,1);
      break;
      case 13: // enter into article
        enterArticle(selectedArticle);
      break;
      case 74: // j letter key
        selectedArticle = goSelectNext(selectedArticle,3);
      break;
      case 40: // down arrow
        selectedArticle = goSelectNext(selectedArticle,3);
      break;
      case 75: // k letter key
        selectedArticle = goSelectNext(selectedArticle,3);
      break;
      case 38: // up arrow
        selectedArticle = goSelectNext(selectedArticle,3);
      break;
    }

  }, false);
}

function goSelectNext(selectedArticle,number) {
  if (selectedArticle.next().length) {
    selectedArticle.removeClass("eselected");
    selectedArticle = selectedArticle.next();
    selectedArticle.addClass("eselected");
  }
  return selectedArticle;
}

function goSelectPrev(selectedArticle,number) {
  if (selectedArticle.prev().length) {
    selectedArticle.removeClass("eselected");
    selectedArticle = selectedArticle.prev();
    selectedArticle.addClass("eselected");
  }
  return selectedArticle;
}

function enterArticle(selectedArticle) {
  if (!$("#bagit").hasClass("current")) {
    window.location = selectedArticle.find('a:first').attr('href');
  }
}<|endoftext|>


<commit_before>define(
    [
        'libraries/angularMocks',
        'classes/guests/guestsService',
        'app'
    ],
    function (angularMocks,
              GuestsService,
              app) {

        'use strict';
        describe('GuestServiceTest', function () {

            var httpBackend, guestService;

            beforeEach(function () {
                console.log("inject mocked httpbackend");
                angularMocks.module('eventManager');
                angularMocks.inject(function ($httpBackend, _guestService_) {
                    httpBackend = $httpBackend;
                    guestService = _guestService_;
                });
            });
            /*
             beforeEach(angularMocks.inject(function ($injector, $guestService) {
             console.log("Mock backend");

             $httpBackend = $injector.get('$httpBackend');

             // var $resource = $injector.get('$resource');
             // guestsService = new GuestsService($injector.get('$resource'));

             // console.log("Print guestService: ");
             // console.log(guestsService);
             // expect(guestsService).toBeDefined();
             }));
             /*
             */
            afterEach(function () {
                console.log("Check if any pending requests");

                //These two calls will make sure that at the end of the test, all expected http calls were made
                httpBackend.verifyNoOutstandingExpectation();
                httpBackend.verifyNoOutstandingRequest();
            });

            it('should find guest by id', function () {
                expect(guestService).toBeDefined();

                var eventId = 1;
                var guestId = 2;

                var returnedGuest = {
                    id: guestId,
                    name: 'James Bond',
                    contribution: 'Entertainment',
                    comment: 'Bond, James Bond'
                };

                console.log("mock REST server");
                httpBackend.expectGET('http://127.0.0.1:8080/api/events/1/guests/2').respond(200, JSON.stringify(returnedGuest));

                console.log("do actual request");
                guestService.findGuestById(eventId, guestId).then(function (foundGuests) {
                    console.log("found guest is: " + foundGuests.name);
                    expect(foundGuests.name).toBe('James Bond');
                });

                // Because we're mocking an async action, ngMock provides a method for us to explicitly flush the request
                httpBackend.flush();
            });

        });
    });
<commit_msg>added another test<commit_after>define(
    [
        'libraries/angularMocks',
        'app'
    ],
    function (angularMocks, app) {

        'use strict';
        describe('GuestServiceTest', function () {

            var httpBackend, guestService;

            beforeEach(function () {
                console.log("inject mocked httpbackend");
                angularMocks.module('eventManager');
                angularMocks.inject(function ($httpBackend, _guestService_) {
                    httpBackend = $httpBackend;
                    guestService = _guestService_;
                });

                expect(guestService).toBeDefined();
            });

            afterEach(function () {
                console.log("Check if any pending requests");

                //These two calls will make sure that at the end of the test, all expected http calls were made
                httpBackend.verifyNoOutstandingExpectation();
                httpBackend.verifyNoOutstandingRequest();
            });

            it('should find guests for event', function () {
                var eventId = 1;

                console.log("mock REST server");
                httpBackend.expectGET('http://127.0.0.1:8080/api/events/1/guests').respond(200, JSON.stringify(
                    {
                        guests: [
                            createNewBondAsGuest(1),
                            createEinsteinAsGuest(2),
                            createSupermanAsGuest(3)
                        ]
                    }
                ));

                console.log("do actual request");
                guestService.findGuestsForEvent(eventId).then(function (foundGuests) {
                    expect(foundGuests.length).toBe(3);
                    var onlyNames = extractsNamesOnly(foundGuests);

                    expect(onlyNames).toContain('James Bond');
                    expect(onlyNames).toContain('Albert Einstein');
                    expect(onlyNames).toContain('Superman');
                });

                // Because we're mocking an async action, ngMock provides a method for us to explicitly flush the request
                httpBackend.flush();
            });

            it('should find guest by id', function () {
                var eventId = 1;
                var guestId = 2;

                var returnedGuest = createNewBondAsGuest(guestId);

                console.log("mock REST server");
                httpBackend.expectGET('http://127.0.0.1:8080/api/events/1/guests/2').respond(200, JSON.stringify(returnedGuest));

                console.log("do actual request");
                guestService.findGuestById(eventId, guestId).then(function (foundGuests) {
                    console.log("found guest is: " + foundGuests.name);
                    expect(foundGuests.name).toBe('James Bond');
                });

                // Because we're mocking an async action, ngMock provides a method for us to explicitly flush the request
                httpBackend.flush();
            });

            function createNewBondAsGuest(guestId) {
                return {
                    id: guestId,
                    name: 'James Bond',
                    contribution: 'Entertainment',
                    comment: 'Bond, James Bond'
                };
            }

            function createEinsteinAsGuest(guestId) {
                return {
                    id: guestId,
                    name: 'Albert Einstein',
                    contribution: 'Theory of relativity',
                    comment: 'Only two things are infinite, the universe and human stupidity, and I am not sure about the former.'
                };
            }

            function createSupermanAsGuest(guestId) {
                return {
                    id: guestId,
                    name: 'Superman',
                    contribution: 'Strength',
                    comment: 'Yeah!'
                };
            }

            function extractsNamesOnly(foundGuests) {
                return foundGuests.map(function (a) {
                    return a.name
                });
            }
        });
    });
<|endoftext|>


<commit_before>planet_app.controller('QuestCtrl', ['$scope', '$resource', '$stateParams', 'GetterFactory', function ($scope, $resource, $stateParams, GetterFactory) {
    $scope.quest = GetterFactory.getItem('quests', $stateParams.id).query();
}]);
<commit_msg>remove unused $resource<commit_after>planet_app.controller('QuestCtrl', ['$scope', '$stateParams', 'GetterFactory', function ($scope, $stateParams, GetterFactory) {
    $scope.quest = GetterFactory.getItem('quests', $stateParams.id).query();
}]);
<|endoftext|>


<commit_before>import settings from '../../globals/js/settings';
import mixin from '../../globals/js/misc/mixin';
import createComponent from '../../globals/js/mixins/create-component';
import initComponentBySearch from '../../globals/js/mixins/init-component-by-search';
import eventMatches from '../../globals/js/misc/event-matches';

class Tile extends mixin(createComponent, initComponentBySearch) {
  /**
   * Tile.
   * @extends CreateComponent
   * @extends InitComponentBySearch
   * @param {HTMLElement} element The element working as an Tile.
   */
  constructor(element, options) {
    super(element, options);
    this.tileType = this.element.dataset.tile;
    this.tileHeight = 0; // Tracks expandable tile height
    this.atfHeight = 0; // Tracks above the fold height
    this._hookActions(this._getClass(this.tileType));
  }

  _getClass = type => {
    const typeObj = {
      expandable: this.options.classExpandedTile,
      clickable: this.options.classClickableTile,
      selectable: this.options.classSelectableTile,
    };
    return typeObj[type];
  };

  _hookActions = tileClass => {
    const isExpandable = this.tileType === 'expandable';
    if (isExpandable) {
      const aboveTheFold = this.element.querySelector(this.options.selectorAboveTheFold);
      if (aboveTheFold) {
        this.tileHeight = this.element.getBoundingClientRect().height;
        this.atfHeight = aboveTheFold.getBoundingClientRect().height;
        this.element.style.maxHeight = `${this.atfHeight}px`;
      }
    }
    this.element.addEventListener('click', evt => {
      const input = eventMatches(evt, this.options.selectorTileInput);
      if (!input) {
        this.element.classList.toggle(tileClass);
      }
      if (isExpandable) {
        this._setTileHeight();
      }
    });
    this.element.addEventListener('keydown', evt => {
      const input = this.element.querySelector(this.options.selectorTileInput);
      if (evt.which === 13 || evt.which === 32) {
        if (!isExpandable) {
          this.element.classList.toggle(tileClass);
          input.checked = !input.checked;
        }
      }
    });
  };

  _setTileHeight = () => {
    const isExpanded = this.element.classList.contains(this.options.classExpandedTile);
    this.element.style.maxHeight = isExpanded ? `${this.tileHeight}px` : `${this.atfHeight}px`;
  };

  release() {
    super.release();
  }

  /**
   * The map associating DOM element and Tile UI instance.
   * @type {WeakMap}
   */
  static components = new WeakMap();

  /**
   * The component options.
   * If `options` is specified in the constructor,
   * properties in this object are overriden for the instance being created.
   * @property {string} selectorInit The CSS selector to find Tile instances.
   */
  static get options() {
    const { prefix } = settings;
    return {
      selectorInit: '[data-tile]',
      selectorAboveTheFold: '[data-tile-atf]',
      selectorTileInput: '[data-tile-input]',
      classExpandedTile: `${prefix}--tile--is-expanded`,
      classClickableTile: `${prefix}--tile--is-clicked`,
      classSelectableTile: `${prefix}--tile--is-selected`,
    };
  }
}

export default Tile;
<commit_msg>fix(tile): Add padding value to height calculation for above the fold on expandable tile (#635)<commit_after>import settings from '../../globals/js/settings';
import mixin from '../../globals/js/misc/mixin';
import createComponent from '../../globals/js/mixins/create-component';
import initComponentBySearch from '../../globals/js/mixins/init-component-by-search';
import eventMatches from '../../globals/js/misc/event-matches';

class Tile extends mixin(createComponent, initComponentBySearch) {
  /**
   * Tile.
   * @extends CreateComponent
   * @extends InitComponentBySearch
   * @param {HTMLElement} element The element working as an Tile.
   */
  constructor(element, options) {
    super(element, options);
    this.tileType = this.element.dataset.tile;
    this.tileHeight = 0; // Tracks expandable tile height
    this.atfHeight = 0; // Tracks above the fold height
    this._hookActions(this._getClass(this.tileType));
  }

  _getClass = type => {
    const typeObj = {
      expandable: this.options.classExpandedTile,
      clickable: this.options.classClickableTile,
      selectable: this.options.classSelectableTile,
    };
    return typeObj[type];
  };

  _hookActions = tileClass => {
    const isExpandable = this.tileType === 'expandable';
    if (isExpandable) {
      const aboveTheFold = this.element.querySelector(this.options.selectorAboveTheFold);
      const getStyle = this.element.ownerDocument.defaultView.getComputedStyle(this.element, null);
      const tilePaddingTop = parseInt(getStyle.getPropertyValue('padding-top'), 10);
      const tilePaddingBottom = parseInt(getStyle.getPropertyValue('padding-bottom'), 10);
      const tilePadding = tilePaddingTop + tilePaddingBottom;
      if (aboveTheFold) {
        this.tileHeight = this.element.getBoundingClientRect().height;
        this.atfHeight = aboveTheFold.getBoundingClientRect().height + tilePadding;
        this.element.style.maxHeight = `${this.atfHeight}px`;
      }
    }
    this.element.addEventListener('click', evt => {
      const input = eventMatches(evt, this.options.selectorTileInput);
      if (!input) {
        this.element.classList.toggle(tileClass);
      }
      if (isExpandable) {
        this._setTileHeight();
      }
    });
    this.element.addEventListener('keydown', evt => {
      const input = this.element.querySelector(this.options.selectorTileInput);
      if (evt.which === 13 || evt.which === 32) {
        if (!isExpandable) {
          this.element.classList.toggle(tileClass);
          input.checked = !input.checked;
        }
      }
    });
  };

  _setTileHeight = () => {
    const isExpanded = this.element.classList.contains(this.options.classExpandedTile);
    this.element.style.maxHeight = isExpanded ? `${this.tileHeight}px` : `${this.atfHeight}px`;
  };

  release() {
    super.release();
  }

  /**
   * The map associating DOM element and Tile UI instance.
   * @type {WeakMap}
   */
  static components = new WeakMap();

  /**
   * The component options.
   * If `options` is specified in the constructor,
   * properties in this object are overriden for the instance being created.
   * @property {string} selectorInit The CSS selector to find Tile instances.
   */
  static get options() {
    const { prefix } = settings;
    return {
      selectorInit: '[data-tile]',
      selectorAboveTheFold: '[data-tile-atf]',
      selectorTileInput: '[data-tile-input]',
      classExpandedTile: `${prefix}--tile--is-expanded`,
      classClickableTile: `${prefix}--tile--is-clicked`,
      classSelectableTile: `${prefix}--tile--is-selected`,
    };
  }
}

export default Tile;
<|endoftext|>


<commit_before>$(document).ready(
    function() {
        var _s = [{
                      action: "Click on the service you'd like to add first:",
                      desc: "You must install one service in order to use your locker."
                  },
                  {
                      action: "Your data is syncing in the background:",
                      desc: "Click on another service to make your Locker more awesome!"
                  },
                  {
                      action: "Wow! You're a social-web powerhouse!",
                      desc: "Click 'Next' to continue."
                  }
                 ];

        var CountPoll = (
            function () {
                var CountPoll = function (name) {
//                    console.log("Count poll made ("+name+")");
                    var t = this;
                    t.name = name;
                    t.lastCount = 0;
                    t.count = 0;

                    t.handleResponse = function(data, err, resp) {
                        t.lastCount = t.count;
                        t.count = data.count;
                        if (t.count != t.lastCount) {
//                            console.log("Updated count of "+t.name+": " + data.count);

                            $("#"+t.name+"Count").odoTicker(
                                {
	                            number: data.count ? data.count : 0, //Number to load
	                            speed: 1500, //speed in ms
	                            height: 28 	 //height of a single number in the CSS sprite
                                }
                            );
                        }
                        if (t.lastCount == 0 && t.count != 0) {
//                            console.log("Not 0 anymore");
                            $("#wizard-collections").slideDown();
                            $("#wizard-actions").fadeIn();
                            $("#popup h2").html(_s[1].action).next().html(_s[1].desc);
                        }

                        t.timeout = setTimeout(t.query, 1000);
                    };

                    t.query = function() {
                        var url = "/Me/"+t.name+"/state";
                        $.ajax({
                                   url: url,
                                   dataType: 'json',
                                   success: t.handleResponse,
                                   error: function(e) {
                                       // assume it will become available later
                                       t.timeout = setTimeout(t.query, 3000);
                                   }
                               });
                    };

                    t.halt = function() {
                        clearTimeout(t.timeout);
                    };

                    // init
//                    console.log("init");
                    t.query();
                    $("#"+t.name+"Count").odoTicker(
                        {
	                    number: 0,   //Number to load
	                    speed: 1500, //speed in ms
	                    height: 28   //height of a single number in the CSS sprite
                        });

                };

                return function (name) {
                    return new CountPoll(name);
                };

            })();

        /*
         * SyncletPoll
         */
        var SyncletPoll = (
            function () {
                var SyncletPoll = function () {
//                    console.log("Synclet poll made");
                    var t = this;
                    t.uri = "/synclets";
                    t.buttonsConnected = false;
                    t.installed = {};

                    var app = {};

                    t.pending = function(provider) {
                        console.log(provider + " pending");
                        if (typeof(t.installed[provider]) == "undefined") {
                            var b =  {
                                "state": "pending",
                                "$el": $("#"+provider+"Connect a:first")
                            };

                            b.$el.addClass("pending disabled");

                            b.spinner = spinner(b.$el.parent().parent().children(".spinner").get(0), 15, 20, 20, 4, "#aaa");

                            t.installed[provider] = b;
                        }
                    };

                    t.handleResponse = function(data, err, resp) {
                        console.log(data);
                        var wizardApps = ["facebook", "twitter", "gcontacts", "github", "foursquare"];
                        if (!t.buttonsConnected) {
                            for (app in data.available) {
                                app = data.available[app];

                                if (wizardApps.indexOf(app.provider) != -1 && typeof(app.authurl) != "undefined") {
                                    // update app button with the correct link
                                    var $el = $("#"+ app.provider + "Connect a:first");
                                    // change link
                                    //console.log("Change link for " + app.provider + " to " + app.authurl);
                                    $el.attr("href", app.authurl);
                                    $el.attr("target", "_blank");
                                    console.log(app.authurl);
                                }
                            }
                            t.buttonsConnected = true;
                        }

                        for (app in data.installed) {
                            app = data.installed[app];
                            console.log(app);

                            if (wizardApps.indexOf(app.provider) != -1) {
                                // update app button with "pending" gfx
                                console.log(app.provider);
                                t.pending(app.provider);
                                console.log(app.provider);
                            }
                        }

                        t.timeout = setTimeout(t.query, 1000);
                    };

                    t.query = function() {
                        var url = t.uri;
                        $.ajax({
                                   url: url,
                                   dataType: 'json',
                                   success: t.handleResponse,
                                   error: function(e) {
                                       // assume it will become available later
                                       t.timeout = setTimeout(t.query, 3000);
                                   }
                               });
                    };

                    t.halt = function() {
                        clearTimeout(t.timeout);
                    };

                    // init
                    t.query();
                };

                return function () {
                    return new SyncletPoll();
                };

            })();

        function spinner(container, R1, R2, count, stroke_width, colour) {
            var sectorsCount = count || 12,
            color = colour || "#fff",
            width = stroke_width || 15,
            r1 = Math.min(R1, R2) || 35,
            r2 = Math.max(R1, R2) || 60,
            cx = r2 + width,
            cy = r2 + width,
            r = Raphael(container, r2 * 2 + width * 2, r2 * 2 + width * 2),

            sectors = [],
            opacity = [],
            beta = 2 * Math.PI / sectorsCount,

            pathParams = {stroke: color, "stroke-width": width, "stroke-linecap": "round"};
            Raphael.getColor.reset();
            for (var i = 0; i < sectorsCount; i++) {
                var alpha = beta * i - Math.PI / 2,
                cos = Math.cos(alpha),
                sin = Math.sin(alpha);
                opacity[i] = 1 / sectorsCount * i;
                sectors[i] = r.path([["M", cx + r1 * cos, cy + r1 * sin], ["L", cx + r2 * cos, cy + r2 * sin]]).attr(pathParams);
                if (color == "rainbow") {
                    sectors[i].attr("stroke", Raphael.getColor());
                }
            }
            var tick;
            (function ticker() {
                 opacity.unshift(opacity.pop());
                 for (var i = 0; i < sectorsCount; i++) {
                     sectors[i].attr("opacity", opacity[i]);
                 }
                 r.safari();
                 tick = setTimeout(ticker, 1000 / sectorsCount);
             })();
            return function () {
                clearTimeout(tick);
                r.remove();
            };
        }

        $('#popup').live('pagecreate',function(event){
                             // collections
                             window.photoCountPoll = new CountPoll("photos");
                             window.linkCountPoll = new CountPoll("links");
                             window.contactCountPoll = new CountPoll("contacts");

                             // synclets
                             window.syncletPoll = new SyncletPoll();
                         });
    }
);

function accountPopup (url) {
    //    console.log("URL " + url);
    var popup = window.open(url, "account",
                            "width=620,height=400,status=no,scrollbars=no,resizable=no");
    popup.focus();
}
<commit_msg>Removed debug.<commit_after>function log(m) { if (console && console.log) console.log(m); }

$(document).ready(
    function() {
        var _s = [{
                      action: "Click on the service you'd like to add first:",
                      desc: "You must install one service in order to use your locker."
                  },
                  {
                      action: "Your data is syncing in the background:",
                      desc: "Click on another service to make your Locker more awesome!"
                  },
                  {
                      action: "Wow! You're a social-web powerhouse!",
                      desc: "Click 'Next' to continue."
                  }
                 ];

        var CountPoll = (
            function () {
                var CountPoll = function (name) {
                    var t = this;
                    t.name = name;
                    t.lastCount = 0;
                    t.count = 0;

                    t.handleResponse = function(data, err, resp) {
                        t.lastCount = t.count;
                        t.count = data.count;
                        if (t.count != t.lastCount) {
                            $("#"+t.name+"Count").odoTicker(
                                {
	                            number: data.count ? data.count : 0, //Number to load
	                            speed: 1500, //speed in ms
	                            height: 28 	 //height of a single number in the CSS sprite
                                }
                            );
                        }
                        if (t.lastCount == 0 && t.count != 0) {
                            $("#wizard-collections").slideDown();
                            $("#wizard-actions").fadeIn();
                            $("#popup h2").html(_s[1].action).next().html(_s[1].desc);
                        }

                        t.timeout = setTimeout(t.query, 1000);
                    };

                    t.query = function() {
                        var url = "/Me/"+t.name+"/state";
                        $.ajax({
                                   url: url,
                                   dataType: 'json',
                                   success: t.handleResponse,
                                   error: function(e) {
                                       // assume it will become available later
                                       t.timeout = setTimeout(t.query, 3000);
                                   }
                               });
                    };

                    t.halt = function() {
                        clearTimeout(t.timeout);
                    };

                    // init
                    t.query();
                    $("#"+t.name+"Count").odoTicker(
                        {
	                    number: 0,   //Number to load
	                    speed: 1500, //speed in ms
	                    height: 28   //height of a single number in the CSS sprite
                        });
                };

                return function (name) {
                    return new CountPoll(name);
                };

            })();

        /*
         * SyncletPoll
         */
        var SyncletPoll = (
            function () {
                var SyncletPoll = function () {
                    var t = this;
                    t.uri = "/synclets";
                    t.buttonsConnected = false;
                    t.installed = {};

                    var app = {};

                    t.pending = function(provider) {
                        if (typeof(t.installed[provider]) == "undefined") {
                            var b =  {
                                "state": "pending",
                                "$el": $("#"+provider+"Connect a:first")
                            };

                            b.$el.addClass("pending disabled");

                            b.spinner = spinner(b.$el.parent().parent().children(".spinner").get(0), 15, 20, 20, 4, "#aaa");

                            t.installed[provider] = b;
                        }
                    };

                    t.handleResponse = function(data, err, resp) {
                        var wizardApps = ["facebook", "twitter", "gcontacts", "github", "foursquare"];
                        if (!t.buttonsConnected) {
                            for (app in data.available) {
                                app = data.available[app];

                                if (wizardApps.indexOf(app.provider) != -1 && typeof(app.authurl) != "undefined") {
                                    // update app button with the correct link
                                    var $el = $("#"+ app.provider + "Connect a:first");
                                    // change link
                                    $el.attr("href", app.authurl);
                                    $el.attr("target", "_blank");
                                }
                            }
                            t.buttonsConnected = true;
                        }

                        for (app in data.installed) {
                            app = data.installed[app];

                            if (wizardApps.indexOf(app.provider) != -1) {
                                // update app button with "pending" gfx
                                t.pending(app.provider);
                            }
                        }

                        t.timeout = setTimeout(t.query, 1000);
                    };

                    t.query = function() {
                        var url = t.uri;
                        $.ajax({
                                   url: url,
                                   dataType: 'json',
                                   success: t.handleResponse,
                                   error: function(e) {
                                       // assume it will become available later
                                       t.timeout = setTimeout(t.query, 3000);
                                   }
                               });
                    };

                    t.halt = function() {
                        clearTimeout(t.timeout);
                    };

                    // init
                    t.query();
                };

                return function () {
                    return new SyncletPoll();
                };

            })();

        function spinner(container, R1, R2, count, stroke_width, colour) {
            var sectorsCount = count || 12,
            color = colour || "#fff",
            width = stroke_width || 15,
            r1 = Math.min(R1, R2) || 35,
            r2 = Math.max(R1, R2) || 60,
            cx = r2 + width,
            cy = r2 + width,
            r = Raphael(container, r2 * 2 + width * 2, r2 * 2 + width * 2),

            sectors = [],
            opacity = [],
            beta = 2 * Math.PI / sectorsCount,

            pathParams = {stroke: color, "stroke-width": width, "stroke-linecap": "round"};
            Raphael.getColor.reset();
            for (var i = 0; i < sectorsCount; i++) {
                var alpha = beta * i - Math.PI / 2,
                cos = Math.cos(alpha),
                sin = Math.sin(alpha);
                opacity[i] = 1 / sectorsCount * i;
                sectors[i] = r.path([["M", cx + r1 * cos, cy + r1 * sin], ["L", cx + r2 * cos, cy + r2 * sin]]).attr(pathParams);
                if (color == "rainbow") {
                    sectors[i].attr("stroke", Raphael.getColor());
                }
            }
            var tick;
            (function ticker() {
                 opacity.unshift(opacity.pop());
                 for (var i = 0; i < sectorsCount; i++) {
                     sectors[i].attr("opacity", opacity[i]);
                 }
                 r.safari();
                 tick = setTimeout(ticker, 1000 / sectorsCount);
             })();
            return function () {
                clearTimeout(tick);
                r.remove();
            };
        }

        $('#popup').live('pagecreate',function(event){
                             // collections
                             window.photoCountPoll = new CountPoll("photos");
                             window.linkCountPoll = new CountPoll("links");
                             window.contactCountPoll = new CountPoll("contacts");

                             // synclets
                             window.syncletPoll = new SyncletPoll();
                         });
    }
);

/*
 * Account Popup
 */
function accountPopup (url) {
    var popup = window.open(url, "account", "width=620,height=400,status=no,scrollbars=no,resizable=no");
    popup.focus();
}
<|endoftext|>