<commit_before>/**
*
* UserHeaderBar
*
*/

import React, { PropTypes } from 'react';
import styled from 'styled-components';
import pallete from 'styles/colors';

import FlexColumn from 'components/FlexColumn';
import FlexCenter from 'components/FlexCenter';
import ExpProgress from 'components/ExpProgress';
import { Icon, Button } from 'antd-mobile';

const MaskWrapper = styled.div`
  position: fixed;
  top: 1.8rem;
  right: 0;
  left: 0;
  bottom: 0;
  height: 100%;
  z-index: 102;
  background-color: rgba(0, 0, 0, 0.4);
`;

const ContentWrapper = styled.div`
  display: flex;
  flex-wrap: wrap;
  padding: 0.12rem 0.2rem;
  background-color: ${pallete.white};
  z-index: 22;
`;

const buttonStyle = {
  padding: 0,
  margin: '0.04rem 0.025rem',
  width: '1.72rem',
  height: '0.62rem',
  lineHeight: '0.62rem',
  backgroundColor: pallete.background.grey,
  color: pallete.text.content,
  fontSize: '0.22rem',
}

const buttonActiveStyle = {
  backgroundColor: pallete.background.lightBule,
  color: pallete.theme,
};

const rootStyle = {
  height: '0.9rem',
  padding: '0.12rem 0',
  width: '100%',
  lineHeight: '0.9rem',
  color: pallete.text.tag,
  fontSize: '0.26rem',
  borderBottom: `0.01rem ${pallete.border.normal} solid`,
  backgroundColor: pallete.white,
};

class FilterPanel extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
  state = {
    expanded: false,
  }

  static defaultProps = {
    value: 1,
    onSelect: () => {},
    selectTotalName: '全部',
  }

  handleExpand = (e) => {
    e.preventDefault();
    e.stopPropagation();
    this.setState({
      expanded: !this.state.expanded,
    });

    this.props.onExpand && this.props.onExpand();
  }

  render() {
    const { expanded } = this.state;
    const { defaultTitle, field, value, items, style, contentStyle, onSelect, selectTotalName, from } = this.props;
    let currentItemTitle = defaultTitle;

    if (from && from === 'supplier') {
      buttonActiveStyle.backgroundColor = '#ffedd0';
      buttonActiveStyle.color = pallete.yellow;
    }

    const itemsView = items ? items.map((item, i) => {
      if (item.id === value) {
        currentItemTitle = item[field] + (item.unit ? item.unit : '');
      }
      return (
        item[field] !== '' &&
        <Button
          key={i}
          className="btn"
          inline
          style={item.id === value ? {...buttonStyle, ...buttonActiveStyle} : buttonStyle}
          activeStyle={buttonActiveStyle}
          onClick={() => onSelect(item)}>
          {item[field]}{item.unit ? item.unit : ''}
        </Button>
      )
    }) : null

    return (

          <FlexCenter style={contentStyle} onClick={this.handleExpand}>

{currentItemTitle}

              {
                expanded ?
                <Icon
                  type={require('icons/icon-core/list-up.svg')}
                  size="xxs"
                  color={pallete.text.words}
                /> :
                <Icon
                  type={require('icons/icon-core/list-down.svg')}
                  size="xxs"
                  color={pallete.text.words}
                />
              }

          </FlexCenter>
          {expanded &&
            <MaskWrapper onClick={this.handleExpand}>
              <ContentWrapper>
                <Button
                  key={0}
                  className="btn"
                  inline
                  style={value === 0 ? {...buttonStyle, ...buttonActiveStyle} : buttonStyle} activeStyle={buttonActiveStyle}
                  onClick={() => onSelect({ id: 0, [field]: '' })}>
                  {selectTotalName}
                </Button>
                {itemsView}
              </ContentWrapper>
            </MaskWrapper>
          }

    );
  }
}

FilterPanel.propTypes = {
  defaultTitle: PropTypes.string,
  field: PropTypes.string,
  selectTotalName: PropTypes.string,
  value: PropTypes.oneOfType([
    PropTypes.number,
    PropTypes.string,
  ]),
  items: PropTypes.oneOfType([
    PropTypes.array,
    PropTypes.bool,
  ]),
  style: PropTypes.object,
  contentStyle: PropTypes.object,
  onSelect: PropTypes.func,
  onExpand: PropTypes.func,
  from: PropTypes.string,
};

export default FilterPanel;
<commit_msg>. fix color show wrong for business filter panel comp<commit_after>/**
*
* UserHeaderBar
*
*/

import React, { PropTypes } from 'react';
import styled from 'styled-components';
import pallete from 'styles/colors';

import FlexColumn from 'components/FlexColumn';
import FlexCenter from 'components/FlexCenter';
import ExpProgress from 'components/ExpProgress';
import { Icon, Button } from 'antd-mobile';

const MaskWrapper = styled.div`
  position: fixed;
  top: 1.8rem;
  right: 0;
  left: 0;
  bottom: 0;
  height: 100%;
  z-index: 102;
  background-color: rgba(0, 0, 0, 0.4);
`;

const ContentWrapper = styled.div`
  display: flex;
  flex-wrap: wrap;
  padding: 0.12rem 0.2rem;
  background-color: ${pallete.white};
  z-index: 22;
`;

const buttonStyle = {
  padding: 0,
  margin: '0.04rem 0.025rem',
  width: '1.72rem',
  height: '0.62rem',
  lineHeight: '0.62rem',
  backgroundColor: pallete.background.grey,
  color: pallete.text.content,
  fontSize: '0.22rem',
}

const rootStyle = {
  height: '0.9rem',
  padding: '0.12rem 0',
  width: '100%',
  lineHeight: '0.9rem',
  color: pallete.text.tag,
  fontSize: '0.26rem',
  borderBottom: `0.01rem ${pallete.border.normal} solid`,
  backgroundColor: pallete.white,
};

class FilterPanel extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
  state = {
    expanded: false,
  }

  static defaultProps = {
    value: 1,
    onSelect: () => {},
    selectTotalName: '全部',
  }

  handleExpand = (e) => {
    e.preventDefault();
    e.stopPropagation();
    this.setState({
      expanded: !this.state.expanded,
    });

    this.props.onExpand && this.props.onExpand();
  }

  render() {
    const { expanded } = this.state;
    const { defaultTitle, field, value, items, style, contentStyle, onSelect, selectTotalName, from } = this.props;
    let currentItemTitle = defaultTitle;

    const buttonActiveStyle = {
      backgroundColor: from === 'supplier' ? '#ffedd0' : pallete.background.lightBule,
      color: from === 'supplier' ? pallete.yellow : pallete.theme,
    };

    const itemsView = items ? items.map((item, i) => {
      if (item.id === value) {
        currentItemTitle = item[field] + (item.unit ? item.unit : '');
      }
      return (
        item[field] !== '' &&
        <Button
          key={i}
          className="btn"
          inline
          style={item.id === value ? {...buttonStyle, ...buttonActiveStyle} : buttonStyle}
          activeStyle={buttonActiveStyle}
          onClick={() => onSelect(item)}>
          {item[field]}{item.unit ? item.unit : ''}
        </Button>
      )
    }) : null

    return (

          <FlexCenter style={contentStyle} onClick={this.handleExpand}>

{currentItemTitle}

              {
                expanded ?
                <Icon
                  type={require('icons/icon-core/list-up.svg')}
                  size="xxs"
                  color={pallete.text.words}
                /> :
                <Icon
                  type={require('icons/icon-core/list-down.svg')}
                  size="xxs"
                  color={pallete.text.words}
                />
              }

          </FlexCenter>
          {expanded &&
            <MaskWrapper onClick={this.handleExpand}>
              <ContentWrapper>
                <Button
                  key={0}
                  className="btn"
                  inline
                  style={value === 0 ? {...buttonStyle, ...buttonActiveStyle} : buttonStyle} activeStyle={buttonActiveStyle}
                  onClick={() => onSelect({ id: 0, [field]: '' })}>
                  {selectTotalName}
                </Button>
                {itemsView}
              </ContentWrapper>
            </MaskWrapper>
          }

    );
  }
}

FilterPanel.propTypes = {
  defaultTitle: PropTypes.string,
  field: PropTypes.string,
  selectTotalName: PropTypes.string,
  value: PropTypes.oneOfType([
    PropTypes.number,
    PropTypes.string,
  ]),
  items: PropTypes.oneOfType([
    PropTypes.array,
    PropTypes.bool,
  ]),
  style: PropTypes.object,
  contentStyle: PropTypes.object,
  onSelect: PropTypes.func,
  onExpand: PropTypes.func,
  from: PropTypes.string,
};

export default FilterPanel;
<|endoftext|>


<commit_before>var args = arguments[0] || {};
var title = args.title;
var image = args.image;
var author = args.author;
var isbn = args.isbn;
var price = args.price;

var mainCategory = {};
var subCategory = {};
var os = Ti.Platform.getOsname();

$.itemImage.setImage(image);
$.itemTitle.setText(title);
$.itemAuthor.setText(author);
if (price == "") {
    $.itemPrice.setText(price);
} else {
    $.itemPrice.setText(price + "円");
}

$.categoriesView.addEventListener("itemclick", function (e) {
    var win;
    var detailWindow;
    if (e.itemIndex == 0) {
        openCategoryWindow("mainCategories", {
                selectedCategory: mainCategory
            },
            function (e) {
                updateMainCategory(e.mainCategory);
                updateSubCategory(e.subCategory);
            });
    } else if (e.itemIndex == 1) {
        // return if main category is not selected
        if (mainCategory.categoryId < 0 || mainCategory.categoryId == null) {
            Ti.UI.createAlertDialog({
                title: "大学を選択してください",
            }).show();
            return;
        }
        openCategoryWindow("subCategories", {
                mainCategory: mainCategory,
                selectedCategory: subCategory
            },
            function (e) {
                updateSubCategory(e.subCategory);
            });
    }
});

/* exhibition process */
function exhibit() {
	$.exhibit.removeEventListener('click', exhibit);
    // error check
    // return if subcategory is not selected
    if (subCategory.categoryId < 0 || subCategory.categoryId == null) {
        Ti.UI.createAlertDialog({
            title: "学部を選択してください",
            message: "大学と学部を両方選択する必要があります。"
        }).show();
        $.exhibit.addEventListener('click', exhibit);
        return;
    }

    var url = Alloy.Globals.config.baseurl + '/wp-admin/admin-ajax.php';
    var exhibitClient = Ti.Network.createHTTPClient({
        onload: function (e) {
            var dialog = Ti.UI.createAlertDialog({
                message: this.responseText
            });
            dialog.addEventListener('click', function (e) {
                cancel();
            });
            dialog.show();
        },
        onerror: function (e) {
            Ti.API.debug(e.error);
            var errorDialog = Alloy.Globals.getConnectionErrorDialog();
            errorDialog.show();
           	$.exhibit.addEventListener('click', exhibit);
        },
        timeout: 5000
    });

    // Set system cookie value into http cookie store for android
    // This is necessary for social login case
    // addHTTPcookie method does not work at here
    if (Ti.Platform.getOsname() == 'android') {
        var systemCookies = Ti.Network.getSystemCookies(Alloy.Globals.config.domain, Alloy.Globals.config.cookiepath, null);
        var cookiestrings = "";
        if (systemCookies) {
            systemCookies.forEach(function (cookie) {
                cookiestrings += '; ' + cookie.name + '=' + cookie.value;
                Ti.API.info('name:' + cookie.name + ' value:' + cookie.value);
            });
            exhibitClient.setRequestHeader('Cookie:', cookiestrings);
        }
    }

    exhibitClient.open('POST', url);
    exhibitClient.send({
        'action': 'exhibit_from_app',
        'item_name': title,
        'author': author,
        'ISBN': isbn,
        'price': price,
        'image_url': image,
        'category': subCategory.categoryId
    });
}

function openCategoryWindow(name, args, callback) {
    var win = Alloy.createController('exhibition/categories/' + name, args);
    var detailWindow = win.getView();
    if (os == "iphone") {
        $.confirmationRootWindow.openWindow(detailWindow);
    } else {
        detailWindow.open();
    }
    win.on('select', callback);
}

function updateMainCategory(main) {
    mainCategory = main; // update global variable
    var item = $.categoriesSection.getItemAt(0);
    if (os == "iphone") {
        item.properties.subtitle = main.title;
    } else {
        item.properties.title = main.title;
    }
    $.categoriesSection.updateItemAt(0, item);
}

function updateSubCategory(sub) {
    subCategory = sub; // update global variable
    var item = $.categoriesSection.getItemAt(1);
    if (os == "iphone") {
        item.properties.subtitle = sub.title;
    } else {
        item.properties.title = sub.title;
    }
    $.categoriesSection.updateItemAt(1, item);
}

function cancel() {
    if (os == "iphone") {
        $.confirmationRootWindow.close();
    } else {
        $.confirmationWindow.close();
    }
}
<commit_msg>Close department window when any element is selected Add an event listener on select event<commit_after>var args = arguments[0] || {};
var title = args.title;
var image = args.image;
var author = args.author;
var isbn = args.isbn;
var price = args.price;

var mainCategory = {};
var subCategory = {};
var os = Ti.Platform.getOsname();

$.itemImage.setImage(image);
$.itemTitle.setText(title);
$.itemAuthor.setText(author);
if (price == "") {
    $.itemPrice.setText(price);
} else {
    $.itemPrice.setText(price + "円");
}

$.categoriesView.addEventListener("itemclick", function (e) {
    var win;
    var detailWindow;
    if (e.itemIndex == 0) {
        openCategoryWindow("mainCategories", {
                selectedCategory: mainCategory
            },
            function (e) {
                updateMainCategory(e.mainCategory);
                updateSubCategory(e.subCategory);
            });
    } else if (e.itemIndex == 1) {
        // return if main category is not selected
        if (mainCategory.categoryId < 0 || mainCategory.categoryId == null) {
            Ti.UI.createAlertDialog({
                title: "大学を選択してください",
            }).show();
            return;
        }
        openCategoryWindow("subCategories", {
                mainCategory: mainCategory,
                selectedCategory: subCategory
            },
            function (e) {
                updateSubCategory(e.subCategory);
            });
    }
});

/* exhibition process */
function exhibit() {
	$.exhibit.removeEventListener('click', exhibit);
    // error check
    // return if subcategory is not selected
    if (subCategory.categoryId < 0 || subCategory.categoryId == null) {
        Ti.UI.createAlertDialog({
            title: "学部を選択してください",
            message: "大学と学部を両方選択する必要があります。"
        }).show();
        $.exhibit.addEventListener('click', exhibit);
        return;
    }

    var url = Alloy.Globals.config.baseurl + '/wp-admin/admin-ajax.php';
    var exhibitClient = Ti.Network.createHTTPClient({
        onload: function (e) {
            var dialog = Ti.UI.createAlertDialog({
                message: this.responseText
            });
            dialog.addEventListener('click', function (e) {
                cancel();
            });
            dialog.show();
        },
        onerror: function (e) {
            Ti.API.debug(e.error);
            var errorDialog = Alloy.Globals.getConnectionErrorDialog();
            errorDialog.show();
           	$.exhibit.addEventListener('click', exhibit);
        },
        timeout: 5000
    });

    // Set system cookie value into http cookie store for android
    // This is necessary for social login case
    // addHTTPcookie method does not work at here
    if (Ti.Platform.getOsname() == 'android') {
        var systemCookies = Ti.Network.getSystemCookies(Alloy.Globals.config.domain, Alloy.Globals.config.cookiepath, null);
        var cookiestrings = "";
        if (systemCookies) {
            systemCookies.forEach(function (cookie) {
                cookiestrings += '; ' + cookie.name + '=' + cookie.value;
                Ti.API.info('name:' + cookie.name + ' value:' + cookie.value);
            });
            exhibitClient.setRequestHeader('Cookie:', cookiestrings);
        }
    }

    exhibitClient.open('POST', url);
    exhibitClient.send({
        'action': 'exhibit_from_app',
        'item_name': title,
        'author': author,
        'ISBN': isbn,
        'price': price,
        'image_url': image,
        'category': subCategory.categoryId
    });
}

function openCategoryWindow(name, args, callback) {
    var win = Alloy.createController('exhibition/categories/' + name, args);
    var detailWindow = win.getView();
    if (os == "iphone") {
        $.confirmationRootWindow.openWindow(detailWindow);
		win.on('select', function(){$.confirmationRootWindow.closeWindow(detailWindow);});
    } else {
        detailWindow.open();
		win.on('select', function(){detailWindow.close();});
    }
    win.on('select', callback);
}

function updateMainCategory(main) {
    mainCategory = main; // update global variable
    var item = $.categoriesSection.getItemAt(0);
    if (os == "iphone") {
        item.properties.subtitle = main.title;
    } else {
        item.properties.title = main.title;
    }
    $.categoriesSection.updateItemAt(0, item);
}

function updateSubCategory(sub) {
    subCategory = sub; // update global variable
    var item = $.categoriesSection.getItemAt(1);
    if (os == "iphone") {
        item.properties.subtitle = sub.title;
    } else {
        item.properties.title = sub.title;
    }
    $.categoriesSection.updateItemAt(1, item);
}

function cancel() {
    if (os == "iphone") {
        $.confirmationRootWindow.close();
    } else {
        $.confirmationWindow.close();
    }
}
<|endoftext|>


<commit_before>/* Component for rendering the map outlines as means of selecting regions */
import _ from 'lodash';
import Leaflet from 'leaflet';
import cloneLayer from 'leaflet-clonelayer';

import { findLocationNamed, findLocationById } from '../lib/locations';
import gbFeaturesData from '../data/ONS-Geographies.json';
import niFeaturesData from '../data/OSNI-Geographies.json';

const ENGLAND = 'http://landregistry.data.gov.uk/id/region/england';

const LOCAL_AUTHORITY_TYPES = [
  'http://data.ordnancesurvey.co.uk/ontology/admingeo/District',
  'http://data.ordnancesurvey.co.uk/ontology/admingeo/LondonBorough',
  'http://data.ordnancesurvey.co.uk/ontology/admingeo/MetropolitanDistrict',
  'http://data.ordnancesurvey.co.uk/ontology/admingeo/UnitaryAuthority',
];

const COUNTY_TYPES = [
  'http://data.ordnancesurvey.co.uk/ontology/admingeo/County',
  'http://data.ordnancesurvey.co.uk/ontology/admingeo/GreaterLondonAuthority',
];

const REGION_TYPES = [
  'http://data.ordnancesurvey.co.uk/ontology/admingeo/EuropeanRegion',
];

  /** Cases where selecting one thing highlights several things */
const LOCATION_EXPANSIONS = {
  'http://landregistry.data.gov.uk/id/region/great-britain':
      ['http://landregistry.data.gov.uk/id/region/england',
        'http://landregistry.data.gov.uk/id/region/scotland',
        'http://landregistry.data.gov.uk/id/region/wales',
      ],
  'http://landregistry.data.gov.uk/id/region/united-kingdom':
      ['http://landregistry.data.gov.uk/id/region/england',
        'http://landregistry.data.gov.uk/id/region/scotland',
        'http://landregistry.data.gov.uk/id/region/wales',
        'http://landregistry.data.gov.uk/id/region/northern-ireland',
      ],
  'http://landregistry.data.gov.uk/id/region/england-and-wales':
      ['http://landregistry.data.gov.uk/id/region/england',
        'http://landregistry.data.gov.uk/id/region/wales',
      ],
};

  /** A list of reqions that are typed as metropolitan districts but which should not appear
   *  on the LA map due to problems with the data.
   */
const LA_MAP_ERRATA = [
  'http://landregistry.data.gov.uk/id/region/greater-manchester',
  'http://landregistry.data.gov.uk/id/region/west-midlands',
  'http://landregistry.data.gov.uk/id/region/west-yorkshire',
  'http://landregistry.data.gov.uk/id/region/south-yorkshire',
  'http://landregistry.data.gov.uk/id/region/merseyside',
  'http://landregistry.data.gov.uk/id/region/tyne-and-wear',
];

/* eslint-disable max-len, class-methods-use-this */
export default class LocationsMap {
  constructor(elementId) {
    this.elementId = elementId;

    this.featuresIndex = {};
    this.backgroundLayer = Leaflet.layerGroup([]);

    /** Guard flag so that we only initialise the features index once */
    this.featuresIndexInitialised = false;

    /** The currently selected location URI, or null */
    this.currentSelection = null;

    /** The root leaflet map object */
    this.leafletMap = null;

    /** The currently displayed layerGroup (countries, counties, etc) */
    this.currentLayer = null;

    /** Callback to notify Vue that user has selected a location via the map */
    this.onSelectionCallback = null;
  }

  /** @return The location object denoted by the layer, looked up by name */
  findLayerLocation(layer) {
    const { name, code } = layer.feature.properties;
    return findLocationById(code) || findLocationNamed(name);
  }

  /** @return the full list of currently selected location URIs. Non-null, but may be empty */
  currentSelections() {
    return this.currentSelection ? (LOCATION_EXPANSIONS[this.currentSelection] || [this.currentSelection]) : [];
  }

  /** @return true if the layer is currently selected */
  isLayerSelected(layer) {
    return _.includes(this.currentSelections(), layer.options.ukhpiURI);
  }

  /* Layer styling */
  standardLocationStyle() {
    return {
      fillColor: '#5A8006',
      weight: 1,
      opacity: 1,
      color: 'white',
      dashArray: '3',
      fillOpacity: 0.7,
    };
  }

  backgroundLocationStyle() {
    return {
      fillColor: '#5A8006',
      color: '#999999',
      weight: 1,
      dashArray: '3',
      fillOpacity: 0.7,
    };
  }

  highlightLocationStyle() {
    return {
      color: '#222',
      fillColor: '#ded',
      weight: 2,
    };
  }

  selectedLocationStyle(layer) {
    return _.extend(this.standardLocationStyle(layer), {
      fillColor: '#C0C006',
      color: '#686',
      fillOpacity: 0.7,
      dashArray: '',
    });
  }

  /** Apply the given style to the given layer */
  styleLayer(layer, style) {
    layer.setStyle(style(layer));
  }

  /** Work out which style to use for a layer */
  determineStyle(layer) {
    return _.bind(
      this.isLayerSelected(layer) ? this.selectedLocationStyle : this.standardLocationStyle,
      this,
    );
  }

  /** Update all current layer styles */
  updateCurrentLayersStyle() {
    const determineStyle = _.bind(this.determineStyle, this);
    const styleLayer = _.bind(this.styleLayer, this);

    if (this.currentLayer) {
      this.currentLayer.eachLayer((layer) => {
        styleLayer(layer, determineStyle(layer));
      });
    }
  }

  /* Event handling and region selection */

  /** Show a popup with the location label */
  showPopup(label, point) {
    if (label) {
      const popup = Leaflet.popup({
        offset: new Leaflet.Point(0, -10),
        autoPan: false,
      })
        .setLatLng(point)
        .setContent(label);

      popup.openOn(this.leafletMap);
      const hidePopup = (function onHidePopup(m, p) {
        return function onClosePopup() { m.closePopup(p); };
      }(this.leafletMap, popup));

      _.delay(hidePopup, 2000);
    } else {
      this.leafletMap.closePopup();
    }
  }

  /** Highlight a feature of the map */
  onHighlightFeature(e) {
    const layer = e.target;
    const locationAndType = this.findLayerLocation(layer);
    const label = locationAndType.location.labels.en;

    this.styleLayer(layer, this.highlightLocationStyle);
    this.showPopup(label, e.latlng);
  }

  /** Unhighlight a feature of the map */
  onUnhighlightFeature(e) {
    const layer = e.target;
    const determineStyle = _.bind(this.determineStyle, this);
    this.styleLayer(layer, determineStyle(layer));
  }

  /** Select a feature */
  onSelectFeature(e) {
    const layer = e.target;
    this.onSelectionCallback(layer.options.ukhpiURI);
  }

  /** Bind event handlers when each feature is first loaded */
  onEachFeature(feature, layer) {
    const onHighlightFeature = _.bind(this.onHighlightFeature, this);
    const onUnhighlightFeature = _.bind(this.onUnhighlightFeature, this);
    const onSelectFeature = _.bind(this.onSelectFeature, this);

    layer.on({
      mouseover: onHighlightFeature,
      mouseout: onUnhighlightFeature,
      click: onSelectFeature,
    });
  }

  /* Index of features */

  /** @return An array of the index keys under which we should index this layer */
  indexKeysByLayerType(layer) {
    const partitionKeys = [];
    const locationAndType = this.findLayerLocation(layer);
    const props = layer.feature.properties;
    let isCountry = false;

    if (props.type && props.type.match(/countries|country/)) {
      partitionKeys.push('country');
      isCountry = true;
    }

    if (props.ukhpiType === 'country') {
      partitionKeys.push('country');
      isCountry = true;
    }

    if (locationAndType) {
      const { location } = locationAndType;
      Object.assign(layer.options, { ukhpiURI: location.uri });

      // add a partition key based on hierarchy position
      if (location.container2 === ENGLAND) {
        partitionKeys.push('county');
      }

      if (_.includes(COUNTY_TYPES, location.type)) {
        partitionKeys.push('county');
      }

      if (_.includes(REGION_TYPES, location.type) && !isCountry) {
        partitionKeys.push('region');
      }

      if (location.container3 === ENGLAND) {
        partitionKeys.push('la');
      }

      if (_.includes(LOCAL_AUTHORITY_TYPES, location.type) &&
      !_.includes(LA_MAP_ERRATA, location.uri)) {
        partitionKeys.push('la');
      }
    }

    return _.uniq(partitionKeys);
  }

  /** Update the given partition table by assigning the `layer` to the category for `key` */
  addToPartition(partitionTable, key, layer) {
    if (!_.has(partitionTable, key)) {
      const layerGroup = Leaflet.layerGroup([], { pane: 'overlayPane' });
      Object.assign(partitionTable, { [key]: layerGroup });
    }

    partitionTable[key].addLayer(layer);
  }

  /** @return the feature set from loading the given GeoJSON structure */
  loadGeoJson(json) {
    const onEachFeature = _.bind(this.onEachFeature, this);
    return Leaflet.geoJson(json, {
      style: this.standardLocationStyle,
      onEachFeature,
    });
  }

  /** Update the index of GB and NI GeoJSON features */
  indexFeatures() {
    const gbFeatures = this.loadGeoJson(gbFeaturesData);
    const niFeatures = this.loadGeoJson(niFeaturesData);
    const { featuresIndex, backgroundLayer, addToPartition } = this;

    _.each([gbFeatures, niFeatures], (features) => {
      features.eachLayer((layer) => {
        _.each(this.indexKeysByLayerType(layer), (indexKey) => {
          addToPartition(featuresIndex, indexKey, layer);

          // if this is a country, we also use it to build the background layer
          if (indexKey === 'country') {
            const bgLayer = cloneLayer(layer);
            bgLayer.options.pane = 'tilePane';
            backgroundLayer.addLayer(bgLayer);
          }
        });
      });
    });
  }

  /** @return The indexed collection of Leaflet layers, ensuring it is only initialised once */
  indexedFeatures() {
    if (!this.featuresIndexInitialised) {
      this.indexFeatures();
      this.featuresIndexInitialised = true;
    }

    return this.featuresIndex;
  }

  /** Reset any selections back to empty */
  resetSelection() {
    this.currentSelection = null;
  }

  /** @return The Leaflet map object, creating a new one if necessary */
  createMap() {
    if (!this.leafletMap) {
      this.indexedFeatures();

      this.leafletMap = Leaflet.map(this.elementId)
        .setView([54.85, -2], 5);
      this.leafletMap
        .attributionControl
        .setPrefix(`Open Government License © Crown copyright ${new Date().getFullYear()}`);
      this.leafletMap
        .addLayer(this.backgroundLayer, { pane: 'tilePane' });

      const { styleLayer, backgroundLocationStyle } = this;
      this.backgroundLayer.eachLayer((layer) => { styleLayer(layer, backgroundLocationStyle); });
    }

    return this.leafletMap;
  }

  /** @return The Leaflet map object, ensuring that it is reset */
  getMap() {
    const map = this.createMap(this.elementId);
    this.resetSelection();
    return map;
  }

  /** Remove the given feature group from the map */
  removeLayer(layer, map) {
    if (layer) {
      map.removeLayer(layer);
      map.closePopup();
    }
  }

  /** Show the given feature group on the map */
  showFeatureGroup(groupId, map) {
    this.currentLayer = this.indexedFeatures()[groupId];
    map.addLayer(this.currentLayer);
  }

  /** Display the map and optionally a feature group */
  showMap(featureGroupId, selectionCallback) {
    const map = this.getMap();
    this.onSelectionCallback = selectionCallback;

    if (featureGroupId) {
      this.removeLayer(this.currentLayer, map);
      this.showFeatureGroup(featureGroupId, map);
    }
  }

  /** Nominate a new location to be the currently selected location */
  setSelectedLocationMap(location) {
    this.currentSelection = location.uri;
    this.updateCurrentLayersStyle();
  }
}
<commit_msg>Change Leaflet to use fractional zoom, and set the initial scale on the map to ensure that the Shetland Islands are visible. This then highlighted a problem that the popup labels are not visible in the far north of the map, so added Rrose to change the orientation of the popups depending on the relative location of the popup to edges of the map. #151<commit_after>/* Component for rendering the map outlines as means of selecting regions */
import _ from 'lodash';
import Leaflet from 'leaflet';
import cloneLayer from 'leaflet-clonelayer';
import '../lib/leaflet-rrose';

import { findLocationNamed, findLocationById } from '../lib/locations';
import gbFeaturesData from '../data/ONS-Geographies.json';
import niFeaturesData from '../data/OSNI-Geographies.json';

const ENGLAND = 'http://landregistry.data.gov.uk/id/region/england';

const LOCAL_AUTHORITY_TYPES = [
  'http://data.ordnancesurvey.co.uk/ontology/admingeo/District',
  'http://data.ordnancesurvey.co.uk/ontology/admingeo/LondonBorough',
  'http://data.ordnancesurvey.co.uk/ontology/admingeo/MetropolitanDistrict',
  'http://data.ordnancesurvey.co.uk/ontology/admingeo/UnitaryAuthority',
];

const COUNTY_TYPES = [
  'http://data.ordnancesurvey.co.uk/ontology/admingeo/County',
  'http://data.ordnancesurvey.co.uk/ontology/admingeo/GreaterLondonAuthority',
];

const REGION_TYPES = [
  'http://data.ordnancesurvey.co.uk/ontology/admingeo/EuropeanRegion',
];

  /** Cases where selecting one thing highlights several things */
const LOCATION_EXPANSIONS = {
  'http://landregistry.data.gov.uk/id/region/great-britain':
      ['http://landregistry.data.gov.uk/id/region/england',
        'http://landregistry.data.gov.uk/id/region/scotland',
        'http://landregistry.data.gov.uk/id/region/wales',
      ],
  'http://landregistry.data.gov.uk/id/region/united-kingdom':
      ['http://landregistry.data.gov.uk/id/region/england',
        'http://landregistry.data.gov.uk/id/region/scotland',
        'http://landregistry.data.gov.uk/id/region/wales',
        'http://landregistry.data.gov.uk/id/region/northern-ireland',
      ],
  'http://landregistry.data.gov.uk/id/region/england-and-wales':
      ['http://landregistry.data.gov.uk/id/region/england',
        'http://landregistry.data.gov.uk/id/region/wales',
      ],
};

  /** A list of reqions that are typed as metropolitan districts but which should not appear
   *  on the LA map due to problems with the data.
   */
const LA_MAP_ERRATA = [
  'http://landregistry.data.gov.uk/id/region/greater-manchester',
  'http://landregistry.data.gov.uk/id/region/west-midlands',
  'http://landregistry.data.gov.uk/id/region/west-yorkshire',
  'http://landregistry.data.gov.uk/id/region/south-yorkshire',
  'http://landregistry.data.gov.uk/id/region/merseyside',
  'http://landregistry.data.gov.uk/id/region/tyne-and-wear',
];

/* eslint-disable max-len, class-methods-use-this */
export default class LocationsMap {
  constructor(elementId) {
    this.elementId = elementId;

    this.featuresIndex = {};
    this.backgroundLayer = Leaflet.layerGroup([]);

    /** Guard flag so that we only initialise the features index once */
    this.featuresIndexInitialised = false;

    /** The currently selected location URI, or null */
    this.currentSelection = null;

    /** The root leaflet map object */
    this.leafletMap = null;

    /** The currently displayed layerGroup (countries, counties, etc) */
    this.currentLayer = null;

    /** Callback to notify Vue that user has selected a location via the map */
    this.onSelectionCallback = null;
  }

  /** @return The location object denoted by the layer, looked up by name */
  findLayerLocation(layer) {
    const { name, code } = layer.feature.properties;
    return findLocationById(code) || findLocationNamed(name);
  }

  /** @return the full list of currently selected location URIs. Non-null, but may be empty */
  currentSelections() {
    return this.currentSelection ? (LOCATION_EXPANSIONS[this.currentSelection] || [this.currentSelection]) : [];
  }

  /** @return true if the layer is currently selected */
  isLayerSelected(layer) {
    return _.includes(this.currentSelections(), layer.options.ukhpiURI);
  }

  /* Layer styling */
  standardLocationStyle() {
    return {
      fillColor: '#5A8006',
      weight: 1,
      opacity: 1,
      color: 'white',
      dashArray: '3',
      fillOpacity: 0.7,
    };
  }

  backgroundLocationStyle() {
    return {
      fillColor: '#5A8006',
      color: '#999999',
      weight: 1,
      dashArray: '3',
      fillOpacity: 0.7,
    };
  }

  highlightLocationStyle() {
    return {
      color: '#222',
      fillColor: '#ded',
      weight: 2,
    };
  }

  selectedLocationStyle(layer) {
    return _.extend(this.standardLocationStyle(layer), {
      fillColor: '#C0C006',
      color: '#686',
      fillOpacity: 0.7,
      dashArray: '',
    });
  }

  /** Apply the given style to the given layer */
  styleLayer(layer, style) {
    layer.setStyle(style(layer));
  }

  /** Work out which style to use for a layer */
  determineStyle(layer) {
    return _.bind(
      this.isLayerSelected(layer) ? this.selectedLocationStyle : this.standardLocationStyle,
      this,
    );
  }

  /** Update all current layer styles */
  updateCurrentLayersStyle() {
    const determineStyle = _.bind(this.determineStyle, this);
    const styleLayer = _.bind(this.styleLayer, this);

    if (this.currentLayer) {
      this.currentLayer.eachLayer((layer) => {
        styleLayer(layer, determineStyle(layer));
      });
    }
  }

  /* Event handling and region selection */

  /** Show a popup with the location label */
  showPopup(label, point) {
    if (label) {
      const popup = new Leaflet.Rrose({
        offset: new Leaflet.Point(0, 0),
        autoPan: false,
      })
        .setLatLng(point)
        .setContent(label);

      popup.openOn(this.leafletMap);
      const hidePopup = (function onHidePopup(m, p) {
        return function onClosePopup() { m.closePopup(p); };
      }(this.leafletMap, popup));

      _.delay(hidePopup, 2000);
    } else {
      this.leafletMap.closePopup();
    }
  }

  /** Highlight a feature of the map */
  onHighlightFeature(e) {
    const layer = e.target;
    const locationAndType = this.findLayerLocation(layer);
    const label = locationAndType.location.labels.en;

    this.styleLayer(layer, this.highlightLocationStyle);
    this.showPopup(label, e.latlng);
  }

  /** Unhighlight a feature of the map */
  onUnhighlightFeature(e) {
    const layer = e.target;
    const determineStyle = _.bind(this.determineStyle, this);
    this.styleLayer(layer, determineStyle(layer));
  }

  /** Select a feature */
  onSelectFeature(e) {
    const layer = e.target;
    this.onSelectionCallback(layer.options.ukhpiURI);
  }

  /** Bind event handlers when each feature is first loaded */
  onEachFeature(feature, layer) {
    const onHighlightFeature = _.bind(this.onHighlightFeature, this);
    const onUnhighlightFeature = _.bind(this.onUnhighlightFeature, this);
    const onSelectFeature = _.bind(this.onSelectFeature, this);

    layer.on({
      mouseover: onHighlightFeature,
      mouseout: onUnhighlightFeature,
      click: onSelectFeature,
    });
  }

  /* Index of features */

  /** @return An array of the index keys under which we should index this layer */
  indexKeysByLayerType(layer) {
    const partitionKeys = [];
    const locationAndType = this.findLayerLocation(layer);
    const props = layer.feature.properties;
    let isCountry = false;

    if (props.type && props.type.match(/countries|country/)) {
      partitionKeys.push('country');
      isCountry = true;
    }

    if (props.ukhpiType === 'country') {
      partitionKeys.push('country');
      isCountry = true;
    }

    if (locationAndType) {
      const { location } = locationAndType;
      Object.assign(layer.options, { ukhpiURI: location.uri });

      // add a partition key based on hierarchy position
      if (location.container2 === ENGLAND) {
        partitionKeys.push('county');
      }

      if (_.includes(COUNTY_TYPES, location.type)) {
        partitionKeys.push('county');
      }

      if (_.includes(REGION_TYPES, location.type) && !isCountry) {
        partitionKeys.push('region');
      }

      if (location.container3 === ENGLAND) {
        partitionKeys.push('la');
      }

      if (_.includes(LOCAL_AUTHORITY_TYPES, location.type) &&
      !_.includes(LA_MAP_ERRATA, location.uri)) {
        partitionKeys.push('la');
      }
    }

    return _.uniq(partitionKeys);
  }

  /** Update the given partition table by assigning the `layer` to the category for `key` */
  addToPartition(partitionTable, key, layer) {
    if (!_.has(partitionTable, key)) {
      const layerGroup = Leaflet.layerGroup([], { pane: 'overlayPane' });
      Object.assign(partitionTable, { [key]: layerGroup });
    }

    partitionTable[key].addLayer(layer);
  }

  /** @return the feature set from loading the given GeoJSON structure */
  loadGeoJson(json) {
    const onEachFeature = _.bind(this.onEachFeature, this);
    return Leaflet.geoJson(json, {
      style: this.standardLocationStyle,
      onEachFeature,
    });
  }

  /** Update the index of GB and NI GeoJSON features */
  indexFeatures() {
    const gbFeatures = this.loadGeoJson(gbFeaturesData);
    const niFeatures = this.loadGeoJson(niFeaturesData);
    const { featuresIndex, backgroundLayer, addToPartition } = this;

    _.each([gbFeatures, niFeatures], (features) => {
      features.eachLayer((layer) => {
        _.each(this.indexKeysByLayerType(layer), (indexKey) => {
          addToPartition(featuresIndex, indexKey, layer);

          // if this is a country, we also use it to build the background layer
          if (indexKey === 'country') {
            const bgLayer = cloneLayer(layer);
            bgLayer.options.pane = 'tilePane';
            backgroundLayer.addLayer(bgLayer);
          }
        });
      });
    });
  }

  /** @return The indexed collection of Leaflet layers, ensuring it is only initialised once */
  indexedFeatures() {
    if (!this.featuresIndexInitialised) {
      this.indexFeatures();
      this.featuresIndexInitialised = true;
    }

    return this.featuresIndex;
  }

  /** Reset any selections back to empty */
  resetSelection() {
    this.currentSelection = null;
  }

  /** @return The Leaflet map object, creating a new one if necessary */
  createMap() {
    if (!this.leafletMap) {
      this.indexedFeatures();

      this.leafletMap = Leaflet.map(this.elementId, {
        zoomDelta: 0.5,
        zoomSnap: 0,
      })
        .setView([55.7, -2], 4.7);
      this.leafletMap
        .attributionControl
        .setPrefix(`Open Government License © Crown copyright ${new Date().getFullYear()}`);
      this.leafletMap
        .addLayer(this.backgroundLayer, { pane: 'tilePane' });

      const { styleLayer, backgroundLocationStyle } = this;
      this.backgroundLayer.eachLayer((layer) => { styleLayer(layer, backgroundLocationStyle); });
    }

    return this.leafletMap;
  }

  /** @return The Leaflet map object, ensuring that it is reset */
  getMap() {
    const map = this.createMap(this.elementId);
    this.resetSelection();
    return map;
  }

  /** Remove the given feature group from the map */
  removeLayer(layer, map) {
    if (layer) {
      map.removeLayer(layer);
      map.closePopup();
    }
  }

  /** Show the given feature group on the map */
  showFeatureGroup(groupId, map) {
    this.currentLayer = this.indexedFeatures()[groupId];
    map.addLayer(this.currentLayer);
  }

  /** Display the map and optionally a feature group */
  showMap(featureGroupId, selectionCallback) {
    const map = this.getMap();
    this.onSelectionCallback = selectionCallback;

    if (featureGroupId) {
      this.removeLayer(this.currentLayer, map);
      this.showFeatureGroup(featureGroupId, map);
    }
  }

  /** Nominate a new location to be the currently selected location */
  setSelectedLocationMap(location) {
    this.currentSelection = location.uri;
    this.updateCurrentLayersStyle();
  }
}
<|endoftext|>


<commit_before>var MapproxyBaseService = function(_section, _dependencies) {
    var _this = this;
    this._items = {};
    this._item;
    this._last;
    this._section = _section;
    this._dependencies = _dependencies;
    this._dependenciesLoadComplete = {};
    this._dependenciesLoadComplete[_section] = false;
    this._rootScope;
    this._resource;
    this.error;
    this._waitForLoadComplete = function(event) {
        var name = event.name.split('.')[0];
        _this._dependenciesLoadComplete[name] = true;
        var loadComplete = true;
        angular.forEach(_this._dependenciesLoadComplete, function(loaded) {
            if(!loaded) {
                loadComplete = false;
            }
        });
        if(loadComplete) {
            angular.forEach(_this._items, function(item, id) {
                angular.forEach(_this._dependencies, function(dependency) {
                    item.dependencies[dependency._section] = []
                    angular.forEach(dependency._items, function(dependencyItem) {
                        var useSection = _this._section;
                        //layers only have sources for cache- and source-items
                        if(item._section == 'caches' && dependencyItem._section == 'layers') {
                            useSection = 'sources';
                        }
                        if($.inArray(item._id, dependencyItem[useSection]) != -1) {
                            item.dependencies[dependency._section].push(dependencyItem);
                        }
                    });
                });
            });
            _this._rootScope.$broadcast(_this._section + '.load_complete');
        }
    }
    this.load = function() {
        _this._items = {};
        _this._resource.query({action: _this._section}, function(result) {
            if(result) {
                angular.forEach(result, function(item) {
                    item.dependencies = {};
                    item._section = _this._section;
                    _this._items[item._id] = item;
                })
                if(angular.isDefined(_this._rootScope))
                    _this._rootScope.$broadcast(_this._section + '.load_finished');
            }
        });
    };
    this.add = function(_item) {
        var item = new _this._resource(_item);
        if(angular.isUndefined(item._id)) {
            item.$save({action: _this._section},
                function(result) {
                    _this._items[result._id] = result;
                    if(angular.isDefined(_this._rootScope)) {
                        _this._last = result;
                        _this._rootScope.$broadcast(_this._section + '.added');
                    }
                }, function(error) {
                    _this._error_msg = error.data.error;
                    _this._rootScope.$broadcast(_this._section + '.error')
            });
        } else {
            item.$update({action: _this._section, id: item._id}, function(result) {
                _this._items[result._id] = result;
                if(angular.isDefined(_this._rootScope))
                    _this._rootScope.$broadcast(_this._section + '.updated');
            });
        }
    };
    this.remove = function(_item) {
        var item = new _this._resource(_item)
        item.$delete({action: _this._section, id: item._id}, function(result) {
            delete(_this._items[result._id]);
            if(angular.isDefined(_this._rootScope))
                _this._rootScope.$broadcast(_this._section + '.deleted');
        });
    };
    this.list = function() {
        var result = [];
        for(var key in _this._items) {
            result.push(_this._items[key]);
        }
        return result;
    };
    this.byId = function(_id) {
        return angular.isDefined(_this._items[_id]) ? _this._items[_id] : false;
    };
    this.current = function(copy, _item) {
        if(_item) {
            _this._item = _item;
            if(angular.isDefined(_this._rootScope))
                _this._rootScope.$broadcast(_this._section + '.current');
        } else {
            return copy ? angular.copy(_this._item) : _this._item;
        }
    };
    this.last = function() {
        return _this._last;
    };
    this.error = function() {
        return _this._error_msg;
    }
    this.return_func = function($rootScope, MapproxyResource) {
        _this._inited = true;
        _this._rootScope = $rootScope;
        _this._resource = MapproxyResource;
        _this._rootScope.$on(_this._section + '.load_finished', _this._waitForLoadComplete);
        angular.forEach(_this._dependencies, function(dependency) {
            _this._dependenciesLoadComplete[dependency._section] = false;
            _this._rootScope.$on(dependency._section + '.load_finished', _this._waitForLoadComplete)
            if(!dependency._inited) {
              dependency.return_func(_this._rootScope, _this._resource);
            }

        });
        _this.load();
        return _this.return_dict;
    };

    this.return_dict = {
        refresh: _this.load,
        add: _this.add,
        remove: _this.remove,
        list: _this.list,
        byId: _this.byId,
        current: _this.current,
        last: _this.last,
        error: _this.error
    }
};

var MapproxyLayerService = function(_section) {
    MapproxyBaseService.call(this, _section);
    var _this = this;

    this.prepareLayer = function(store, layer, idx, parent_id) {
        if(angular.isDefined(layer._layers)) {
            angular.forEach(layer._layers, function(child_layer, _idx) {
                _this.prepareLayer(store, child_layer, _idx, layer._id);
            });
        }
        store.push({_id: layer._id, _rank: idx, _parent: parent_id})
    };

    this.tree = function(parent_id) {
        var treeStructure = [];
        var items = angular.copy(_this._items);
        angular.forEach(items, function(item) {
            if(item._parent == null) {
                if($.inArray(item, treeStructure) == -1) {
                    treeStructure.push(item);
                }
            } else {
                if(angular.isArray(items[item._parent]._layers)) {
                    if($.inArray(item, items[item._parent]) == -1) {
                        items[item._parent]._layers.push(item)
                    }
                } else {
                    items[item._parent]._layers = [item]
                }
            }
        });
        return treeStructure;
    };

    this.updateStructure = function(tree) {
        var to_update = [];
        angular.forEach(tree, function(layer, idx) {
            _this.prepareLayer(to_update, layer, idx);
        });
        to_update = new _this._resource({'tree': to_update});
        to_update.$update({action: _this._section}, function(result) {
            _this._rootScope.$broadcast(_this._section + '.updatedStructure');
        });
    };

    this.return_dict['tree'] = _this.tree;
    this.return_dict['updateStructure'] = _this.updateStructure;
};

WMSSourceService = function(_section) {
    MapproxyBaseService.call(this, _section);
    var _this = this;

    this.layerTitle = function(url, layer_name) {
        var title = false;
        angular.forEach(_this._items, function(wms) {
            if(wms.url == url) {
                angular.forEach(wms.layer.layers, function(layer) {
                    if(layer.name == layer_name) {
                        title = layer.title;
                    }
                });
            }
        });
        return title;
    };

    this.refresh = function(_item) {
        var item = new _this._resource(_item);
        item.$update({action: _this._section, id: item._id}, function(result) {
            _this._items[result._id] = result;
            _this._last = result;
            if(angular.isDefined(_this._rootScope))
                _this._rootScope.$broadcast(_this._section + '.updated');
        });
    }

    this.return_dict['layerTitle'] = _this.layerTitle;
    this.return_dict['refresh'] = _this.refresh;
};

var layerService = new MapproxyLayerService('layers');
var globalsService = new MapproxyBaseService('globals');
var servicesService = new MapproxyBaseService('services');
var cacheService = new MapproxyBaseService('caches', [layerService]);
var gridService = new MapproxyBaseService('grids', [cacheService]);
var sourceService = new MapproxyBaseService('sources', [cacheService, layerService]);
var wmsService = new WMSSourceService('wms_capabilities');

angular.module('mapproxy_gui.services', ['mapproxy_gui.resources']).

service('WMSSources', wmsService.return_func).
service('MapproxySources', sourceService.return_func).
service('MapproxyCaches', cacheService.return_func).
service('MapproxyGrids', gridService.return_func).
service('MapproxyLayers', layerService.return_func).
service('MapproxyGlobals', globalsService.return_func).
service('MapproxyServices', servicesService.return_func).

service('DataShareService', function($rootScope) {
    var _this = this;
    this._data = {};

    return {
        data: function(key, value) {
            if(angular.isDefined(value)) {
                _this._data[key] = value;
                $rootScope.$broadcast('dss.' + key);
            } else {
                if(angular.isDefined(_this._data[key])) {
                    return _this._data[key];
                } else {
                    return undefined;
                }
            }
        }
    }
});
<commit_msg>Refactored<commit_after>var MapproxyBaseService = function(_section, _dependencies) {
    var _this = this;
    this._items = {};
    this._item;
    this._last;
    this._section = _section;
    this._dependencies = _dependencies;
    this._rootScope;
    this._resource;
    this.error;
    this._waitForLoadComplete = function(event) {
        var name = event.name.split('.')[0];
        var loadComplete = true;
        angular.forEach(_this.dependencies, function(dependency) {
            if(!dependency._loaded) {
                loadComplete = false;
            }
        });
        if(loadComplete) {
            angular.forEach(_this._items, function(item, id) {
                angular.forEach(_this._dependencies, function(dependency) {
                    item.dependencies[dependency._section] = []
                    angular.forEach(dependency._items, function(dependencyItem) {
                        var useSection = _this._section;
                        //layers only have sources for cache- and source-items
                        if(item._section == 'caches' && dependencyItem._section == 'layers') {
                            useSection = 'sources';
                        }
                        if($.inArray(item._id, dependencyItem[useSection]) != -1) {
                            item.dependencies[dependency._section].push(dependencyItem);
                        }
                    });
                });
            });
            _this._rootScope.$broadcast(_this._section + '.load_complete');
        }
    }
    this.load = function() {
        _this._items = {};
        _this._loaded = false;
        _this._resource.query({action: _this._section}, function(result) {
            if(result) {
                angular.forEach(result, function(item) {
                    item.dependencies = {};
                    item._section = _this._section;
                    _this._items[item._id] = item;
                });
                _this._loaded = false;
                if(angular.isDefined(_this._rootScope))
                    _this._rootScope.$broadcast(_this._section + '.load_finished');
            }
        });
    };
    this.add = function(_item) {
        var item = new _this._resource(_item);
        if(angular.isUndefined(item._id)) {
            item.$save({action: _this._section},
                function(result) {
                    _this._items[result._id] = result;
                    if(angular.isDefined(_this._rootScope)) {
                        _this._last = result;
                        _this._rootScope.$broadcast(_this._section + '.added');
                    }
                }, function(error) {
                    _this._error_msg = error.data.error;
                    _this._rootScope.$broadcast(_this._section + '.error')
            });
        } else {
            item.$update({action: _this._section, id: item._id}, function(result) {
                _this._items[result._id] = result;
                if(angular.isDefined(_this._rootScope))
                    _this._rootScope.$broadcast(_this._section + '.updated');
            });
        }
    };
    this.remove = function(_item) {
        var item = new _this._resource(_item)
        item.$delete({action: _this._section, id: item._id}, function(result) {
            delete(_this._items[result._id]);
            if(angular.isDefined(_this._rootScope))
                _this._rootScope.$broadcast(_this._section + '.deleted');
        });
    };
    this.list = function() {
        var result = [];
        for(var key in _this._items) {
            result.push(_this._items[key]);
        }
        return result;
    };
    this.byId = function(_id) {
        return angular.isDefined(_this._items[_id]) ? _this._items[_id] : false;
    };
    this.current = function(copy, _item) {
        if(_item) {
            _this._item = _item;
            if(angular.isDefined(_this._rootScope))
                _this._rootScope.$broadcast(_this._section + '.current');
        } else {
            return copy ? angular.copy(_this._item) : _this._item;
        }
    };
    this.last = function() {
        return _this._last;
    };
    this.error = function() {
        return _this._error_msg;
    }
    this.return_func = function($rootScope, MapproxyResource) {
        _this._inited = true;
        _this._rootScope = $rootScope;
        _this._resource = MapproxyResource;
        _this._rootScope.$on(_this._section + '.load_finished', _this._waitForLoadComplete);
        angular.forEach(_this._dependencies, function(dependency) {
            _this._rootScope.$on(dependency._section + '.load_finished', _this._waitForLoadComplete)
            if(!dependency._inited) {
              dependency.return_func(_this._rootScope, _this._resource);
            }

        });
        _this.load();
        return _this.return_dict;
    };

    this.return_dict = {
        refresh: _this.load,
        add: _this.add,
        remove: _this.remove,
        list: _this.list,
        byId: _this.byId,
        current: _this.current,
        last: _this.last,
        error: _this.error
    }
};

var MapproxyLayerService = function(_section) {
    MapproxyBaseService.call(this, _section);
    var _this = this;

    this.prepareLayer = function(store, layer, idx, parent_id) {
        if(angular.isDefined(layer._layers)) {
            angular.forEach(layer._layers, function(child_layer, _idx) {
                _this.prepareLayer(store, child_layer, _idx, layer._id);
            });
        }
        store.push({_id: layer._id, _rank: idx, _parent: parent_id})
    };

    this.tree = function(parent_id) {
        var treeStructure = [];
        var items = angular.copy(_this._items);
        angular.forEach(items, function(item) {
            if(item._parent == null) {
                if($.inArray(item, treeStructure) == -1) {
                    treeStructure.push(item);
                }
            } else {
                if(angular.isArray(items[item._parent]._layers)) {
                    if($.inArray(item, items[item._parent]) == -1) {
                        items[item._parent]._layers.push(item)
                    }
                } else {
                    items[item._parent]._layers = [item]
                }
            }
        });
        return treeStructure;
    };

    this.updateStructure = function(tree) {
        var to_update = [];
        angular.forEach(tree, function(layer, idx) {
            _this.prepareLayer(to_update, layer, idx);
        });
        to_update = new _this._resource({'tree': to_update});
        to_update.$update({action: _this._section}, function(result) {
            _this._rootScope.$broadcast(_this._section + '.updatedStructure');
        });
    };

    this.return_dict['tree'] = _this.tree;
    this.return_dict['updateStructure'] = _this.updateStructure;
};

WMSSourceService = function(_section) {
    MapproxyBaseService.call(this, _section);
    var _this = this;

    this.layerTitle = function(url, layer_name) {
        var title = false;
        angular.forEach(_this._items, function(wms) {
            if(wms.url == url) {
                angular.forEach(wms.layer.layers, function(layer) {
                    if(layer.name == layer_name) {
                        title = layer.title;
                    }
                });
            }
        });
        return title;
    };

    this.refresh = function(_item) {
        var item = new _this._resource(_item);
        item.$update({action: _this._section, id: item._id}, function(result) {
            _this._items[result._id] = result;
            _this._last = result;
            if(angular.isDefined(_this._rootScope))
                _this._rootScope.$broadcast(_this._section + '.updated');
        });
    }

    this.return_dict['layerTitle'] = _this.layerTitle;
    this.return_dict['refresh'] = _this.refresh;
};

var layerService = new MapproxyLayerService('layers');
var globalsService = new MapproxyBaseService('globals');
var servicesService = new MapproxyBaseService('services');
var cacheService = new MapproxyBaseService('caches', [layerService]);
var gridService = new MapproxyBaseService('grids', [cacheService]);
var sourceService = new MapproxyBaseService('sources', [cacheService, layerService]);
var wmsService = new WMSSourceService('wms_capabilities');

angular.module('mapproxy_gui.services', ['mapproxy_gui.resources']).

service('WMSSources', wmsService.return_func).
service('MapproxySources', sourceService.return_func).
service('MapproxyCaches', cacheService.return_func).
service('MapproxyGrids', gridService.return_func).
service('MapproxyLayers', layerService.return_func).
service('MapproxyGlobals', globalsService.return_func).
service('MapproxyServices', servicesService.return_func).

service('DataShareService', function($rootScope) {
    var _this = this;
    this._data = {};

    return {
        data: function(key, value) {
            if(angular.isDefined(value)) {
                _this._data[key] = value;
                $rootScope.$broadcast('dss.' + key);
            } else {
                if(angular.isDefined(_this._data[key])) {
                    return _this._data[key];
                } else {
                    return undefined;
                }
            }
        }
    }
});
<|endoftext|>


<commit_before>angular.module('mapproxy_gui.services', ['mapproxy_gui.resources']).

service('WMSSources', function($rootScope, GetCapabilitiesResource) {
    var wms_list = {};

    var load = function() {
        GetCapabilitiesResource.query(function(result) {
            if(result) {
                angular.forEach(result, function(item) {
                    wms_list[item._id] = item;
                })
                $rootScope.$broadcast('wms_list_refreshed');
            }
        })
    }

    var addCapabilities = function(url) {
        var cap = new GetCapabilitiesResource({url: url});
        cap.$save(function(result) {
            console.log(result)
            wms_list[result._id] = result;
            $rootScope.$broadcast('wms_list_refreshed');
        });
    };

    var layerTitle = function(url, layer_name) {
        var title = false
        angular.forEach(wms_list, function(wms) {
            if(wms.url == url) {
                angular.forEach(wms.layer.layers, function(layer) {
                    if(layer.name == layer_name) {
                        title = layer.title;
                    }
                });
            }
        });
        return title;
    };
    var wmsList = function() {
        return wms_list;
    }

    load();

    return {
        refresh: load,
        addCapabilities: addCapabilities,
        layerTitle: layerTitle,
        wmsList: wmsList
    };
}).

service('MapproxySources', function($rootScope, MapproxySourceResource) {
    var _sources = {};
    var current;

    var load = function() {
        MapproxySourceResource.query(function(result) {
            angular.forEach(result, function(item) {
                _sources[item._id] = item;
            })
            $rootScope.$broadcast('mapproxy_sources.load_complete');
        });
    };
    var add = function(source) {
        if(angular.isUndefined(source._id)) {
            var source = new MapproxySourceResource(source);
            source.$save(function(result) {
                _sources[result._id] = result;
                $rootScope.$broadcast('mapproxy_sources.source_added');
            });
        } else {
            source.$update({id: source._id}, function(result) {
                _sources[result._id] = result;
                $rootScope.$broadcast('mapproxy_sources.source_updated');
            });
        }
    };
    var remove = function(source) {
        source.$delete({id: source._id}, function(result) {
            delete(_sources[result._id]);
        });
    };
    var list = function() {
        return dict2list(_sources);
    };
    var setCurrent = function(source, copy) {
        if(copy) {
            current = angular.copy(source);
        } else {
            current = source;
        }
        $rootScope.$broadcast('mapproxy_sources.current');
    };
    var getCurrent= function() {
        if(current) {
            return current;
        }
    };

    //initial load data from server
    load();

    return {
        refresh: load,
        add: add,
        remove: remove,
        list: list,
        setCurrent: setCurrent,
        getCurrent: getCurrent
    };
}).

service('MapproxyCaches', function($rootScope) {
    var caches = {};
    var current;
    return {
        add: function(name, value) {
            caches[name] = value;
            //trigger event in rootScope, so all scope notive about
            $rootScope.$broadcast('mapproxy_caches.list');
        },
        byName: function(name) {
            return caches[name];
        },
        list: function() {
            var result = [];
            for(var key in caches) {
                result.push(caches[key]);
            }
            return result;
        },
        setCurrent: function(cache, copy) {
            if(copy) {
                current = angular.copy(cache);
            } else {
                current = cache;
            }
            $rootScope.$broadcast('mapproxy_caches.current');
        },
        getCurrent: function(cache) {
            if(current) {
                return current;
            }
        }
    };
}).

service('MapproxyLayers', function($rootScope, MapproxyLayerResource) {
    var layers = {};
    var current;

    var load = function() {
        //can't use query. resource returns no array.
        MapproxyLayerResource.get(function(result) {
            angular.forEach(result['tree'], function(item) {
                layers[item._id] = item;
            });
            $rootScope.$broadcast('mapproxy_layers.load_complete')
        });
    };
    var add = function(layer) {
        if(angular.isUndefined(layer._id)) {
            var layer = new MapproxyLayerResource(layer);
            layer.$save(function(result) {
                layers[result._id] = result;
                $rootScope.$broadcast('mapproxy_layers.added');
            });
        } else {
            layer.$update({id: layer._id}, function(result) {
                layers[result._id] = result;
                $rootScope.$broadcast('mapproxy_layers.updated');
            });
        }
    };
    var remove = function(layer) {
        layer.$delete({id: layer._id}, function(result) {
            delete(layers[result._id]);
        });
    };

    var list = function() {
        return dict2list(_layers)
    };

    var setCurrent = function(layer, copy) {
        if(copy) {
            current = angular.copy(layer);
        } else {
            current = layer;
        }
        $rootScope.$broadcast('mapproxy_layers.current');
    };

    var getCurrent = function(layer) {
        if(current) {
            return current;
        }
    };

    load();

    return {
        refresh: load,
        add: add,
        list: list,
        setCurrent: setCurrent,
        getCurrent: getCurrent
    };
});
<commit_msg>Refactored<commit_after>angular.module('mapproxy_gui.services', ['mapproxy_gui.resources']).

service('WMSSources', function($rootScope, GetCapabilitiesResource) {
    var wms_list = {};

    var load = function() {
        GetCapabilitiesResource.query(function(result) {
            if(result) {
                angular.forEach(result, function(item) {
                    wms_list[item._id] = item;
                })
                $rootScope.$broadcast('wms_list_refreshed');
            }
        })
    }

    var addCapabilities = function(url) {
        var cap = new GetCapabilitiesResource({url: url});
        cap.$save(function(result) {
            console.log(result)
            wms_list[result._id] = result;
            $rootScope.$broadcast('wms_list_refreshed');
        });
    };

    var layerTitle = function(url, layer_name) {
        var title = false
        angular.forEach(wms_list, function(wms) {
            if(wms.url == url) {
                angular.forEach(wms.layer.layers, function(layer) {
                    if(layer.name == layer_name) {
                        title = layer.title;
                    }
                });
            }
        });
        return title;
    };
    var wmsList = function() {
        return wms_list;
    }

    load();

    return {
        refresh: load,
        addCapabilities: addCapabilities,
        layerTitle: layerTitle,
        wmsList: wmsList
    };
}).

service('MapproxySources', function($rootScope, MapproxySourceResource) {
    var _sources = {};
    var current;

    var load = function() {
        MapproxySourceResource.query(function(result) {
            angular.forEach(result, function(item) {
                _sources[item._id] = item;
            })
            $rootScope.$broadcast('mapproxy_sources.load_complete');
        });
    };
    var add = function(source) {
        if(angular.isUndefined(source._id)) {
            var source = new MapproxySourceResource(source);
            source.$save(function(result) {
                _sources[result._id] = result;
                $rootScope.$broadcast('mapproxy_sources.source_added');
            });
        } else {
            source.$update({id: source._id}, function(result) {
                _sources[result._id] = result;
                $rootScope.$broadcast('mapproxy_sources.source_updated');
            });
        }
    };
    var remove = function(source) {
        source.$delete({id: source._id}, function(result) {
            delete(_sources[result._id]);
        });
    };
    var list = function() {
        return dict2list(_sources);
    };
    var setCurrent = function(source, copy) {
        if(copy) {
            current = angular.copy(source);
        } else {
            current = source;
        }
        $rootScope.$broadcast('mapproxy_sources.current');
    };
    var getCurrent= function() {
        if(current) {
            return current;
        }
    };

    //initial load data from server
    load();

    return {
        refresh: load,
        add: add,
        remove: remove,
        list: list,
        setCurrent: setCurrent,
        getCurrent: getCurrent
    };
}).

service('MapproxyCaches', function($rootScope, MapproxyCacheResource) {
    var _caches = {};
    var current;

    var load = function() {
        MapproxyCacheResource.query(function(result) {
            angular.forEach(result, function(item) {
                _caches[item._id] = item;
            });
            $rootScope.$broadcast('mapproxy_caches.load_complete');
        });
    };
    var add = function(cache) {
        if(angular.isUndefined(cache._id)) {
            var cache = new MapproxyCacheResource(cache);
            cache.$save(function(result) {
                _caches[result._id] = result;
                $rootScope.$broadcast('mapproxy_caches.added');
            });
        } else {
            cache.$update({id: cache._id}, function(result) {
                _caches[result._id] = result;
                $rootScope.$broadcast('mapproxy_caches.updated');
            });
        }
    };
    var remove = function(cache) {
        cache.$delete({id: cache._id}, function(result) {
            delete(_caches[result._id]);
            $rootScope.$broadcast('mapproxy_caches.deleted');
        })
    };
    var list = function() {
        return dict2list(_caches);
    };
    var setCurrent = function(cache, copy) {
        if(copy) {
            current = angular.copy(cache);
        } else {
            current = cache;
        }
        $rootScope.$broadcast('mapproxy_caches.current');
    };
    var getCurrent = function(cache) {
        if(current) {
            return current;
        }
    };

    load()

    return {
        refresh: load,
        add: add,
        remove: remove,
        list: list,
        setCurrent: setCurrent,
        getCurrent: getCurrent
    };
}).

service('MapproxyLayers', function($rootScope, MapproxyLayerResource) {
    var _layers = {};
    var current;

    var load = function() {
        //can't use query. resource returns no array.
        MapproxyLayerResource.get(function(result) {
            angular.forEach(result['tree'], function(item) {
                _layers[item._id] = item;
            });
            $rootScope.$broadcast('mapproxy_layers.load_complete')
        });
    };
    var add = function(layer) {
        if(angular.isUndefined(layer._id)) {
            var layer = new MapproxyLayerResource(layer);
            layer.$save(function(result) {
                _layers[result._id] = result;
                $rootScope.$broadcast('mapproxy_layers.added');
            });
        } else {
            layer.$update({id: layer._id}, function(result) {
                _layers[result._id] = result;
                $rootScope.$broadcast('mapproxy_layers.updated');
            });
        }
    };
    var remove = function(layer) {
        layer.$delete({id: layer._id}, function(result) {
            delete(_layers[result._id]);
        });
    };

    var list = function() {
        return dict2list(_layers)
    };

    var setCurrent = function(layer, copy) {
        if(copy) {
            current = angular.copy(layer);
        } else {
            current = layer;
        }
        $rootScope.$broadcast('mapproxy_layers.current');
    };

    var getCurrent = function(layer) {
        if(current) {
            return current;
        }
    };

    load();

    return {
        refresh: load,
        add: add,
        list: list,
        setCurrent: setCurrent,
        getCurrent: getCurrent
    };
});
<|endoftext|>


<commit_before>'use strict';

var Weather = require('../models/weather');
var WeatherMapView = require('../views/weather_map_view');
//var MapsConf = require('../conf/maps_coordinates');
var Config =  require('../conf/config');

module.exports = (function(){

  var selectors = {
    searchForm:'form[name=searchForm]',
    searchInput:'input[name=search]',
    body:'body',
    leftToggleButton:'#toggle_sidemenu_l',
    leftMenu:'.sidebar-menu li a.accordion-toggle'
  };

  var options = {
    sbl: 'sb-r-o',
    sbr: 'sb-r-c',
    collapse: 'sb-l-m'
  };

  var searchWeatherByName = function(event){
    event.preventDefault();
    Weather.get({url:Config.hardAntUrl.concat('/weather'),
                 data:$(this).serialize()}).then(success,failure);
  };

  var success = function(data){
    //var placeInformation = getInformationFromPlace(data);
    //WeatherMapView.render(placeInformation);
    //drawHeatMap(data);
    //getTemperatureChart(data);
  };

  var failure = function(data){
    console.error("Error");
    console.error(data);
  };

  var sidebarLeftToggle = function(){
    if($('body.sb-top').length) { return; }

    if($(selectors.body).hasClass('sb-r-c') && options.collapse === "sb-l-m"){
      $(selectors.body).removeClass('sb-r-c');
    }

    $(selectors.body).toggleClass(options.collapse).removeClass('sb-r-o').addClass('sb-r-c');
    triggerResize();
  };

  var triggerResize = function() {
    setTimeout(function() {
      $(window).trigger('resize');

      if($(selectors.body).hasClass('sb-l-m')) {
        $(selectors.body).addClass('sb-l-disable-animation');
      }
      else {
        $(selectors.body).removeClass('sb-l-disable-animation');
      }
    }, 300);
  };

  var leftMenuToggle = function(event){
    event.preventDefault();
    if ($(selectors.body).hasClass('sb-l-m') && !$(this).parents('ul.sub-nav').length) { return; }

    if (!$(this).parents('ul.sub-nav').length) {

      if ($(window).width() > 900) {
        if ($('body.sb-top').length) { return; }
      }

      $('a.accordion-toggle.menu-open').next('ul').slideUp('fast', 'swing', function() {
        $(this).attr('style', '').prev().removeClass('menu-open');
      });
    }
    else {
      var activeMenu = $(this).next('ul.sub-nav');
      var siblingMenu = $(this).parent().siblings('li').children('a.accordion-toggle.menu-open').next('ul.sub-nav')

      activeMenu.slideUp('fast', 'swing', function() {
        $(this).attr('style', '').prev().removeClass('menu-open');
      });

      siblingMenu.slideUp('fast', 'swing', function() {
        $(this).attr('style', '').prev().removeClass('menu-open');
      });
    }

    if (!$(this).hasClass('menu-open')) {
      $(this).next('ul').slideToggle('fast', 'swing', function() {
        $(this).attr('style', '').prev().toggleClass('menu-open');
      });
    }

  };

  var bindEvents = function(){
    //$(selectors.searchForm).on('submit',searchWeatherByName);
    $(selectors.leftToggleButton).on('click',sidebarLeftToggle);
    $(selectors.leftMenu).on('click',leftMenuToggle);
  };

  //var drawHeatMap = function (data) {
  //  var strictBounds = new google.maps.LatLngBounds(
  //        new google.maps.LatLng(19.600237, -99.403214),
  //        new google.maps.LatLng(19.222031, -98.941788)),
  //      distritoFederal = new google.maps.LatLng(19.381836, -99.1372371),
  //      map = new google.maps.Map(document.getElementById('map'),{
  //        zoom: 10,
  //        center: {lat: 19.45, lng: -99},
  //        maxZoom: 13,
  //        minZoom: 8,
  //        streetViewControl: false,
  //        mapTypeId: google.maps.MapTypeId.HYBRID
  //      }),
  //      heatmapData = [],
  //      coordinates;
  //  for(var i=0; i < data.weathers.length; i++) {
  //    coordinates = data.weathers[i].location.coordinates;
  //    var googleMapsPoint = new google.maps.LatLng(coordinates[1], coordinates[0]);
  //    heatmapData.push(googleMapsPoint);
  //  }

  //  var heatmap = new google.maps.visualization.HeatmapLayer({
  //    data: heatmapData
  //  });

  //  heatmap.setMap(map);

  //  var flightPlanCoordinates_DF = MapsConf.DF_Coordinates;

  //  var flightPath2 = new google.maps.Polyline({
  //    path: flightPlanCoordinates_DF,
  //    geodesic: true,
  //    strokeColor: '#E0FFFF',
  //    strokeOpacity: 1.0,
  //    strokeWeight: 2
  //  });

  //  flightPath2.setMap(map);
  //  heatmap.set('radius', 40);

  //  google.maps.event.addListener(map, 'zoom_changed', function() {
  //   if (map.getZoom() < minZoomLevel) map.setZoom(minZoomLevel);
  //  });
  //};

  var getInformationFromPlace = function (data) {
    var basicInformation = {},
        maxTemperature = "",
        minTemperature = "",
        averageTemperature = "";

    maxTemperature = "" + Math.max.apply(Math,data.weathers.map(function(element){return element.temperature;}));
    minTemperature = "" + Math.min.apply(Math,data.weathers.map(function(element){return element.temperature;}));
    averageTemperature = "" + data.weathers.map(function(obj) {return obj.temperature})
                  .reduce(function(a, b) { return a + b }) / data.weathers.length;

    basicInformation.place = data.weathers[0].fullName;
    basicInformation.maxTemperature = maxTemperature.substring(maxTemperature.indexOf(".") - 3,  maxTemperature.indexOf(".") + 3);
    basicInformation.minTemperature = minTemperature.substring(minTemperature.indexOf(".") - 3,  minTemperature.indexOf(".") + 3);
    basicInformation.averageTemperature = averageTemperature.substring(minTemperature.indexOf(".") - 3,  minTemperature.indexOf(".") + 3);

    return basicInformation;
  };

  var getTemperatureChart = function(data) {
    var ctx = document.getElementById("weatherChart").getContext("2d");
    var chartOptions = {
      scaleBeginAtZero : true,
      scaleShowGridLines : false,
      scaleGridLineColor : "rgba(0,0,0,.05)",
      scaleGridLineWidth : 1,
      scaleShowHorizontalLines: false,
      scaleShowVerticalLines: false,
      barShowStroke : true,
      animation: false,
    }
    var temperatureData = {
        labels: [],
        datasets: []
    };
    var dataSetContent = {
        fillColor: "rgba(220,220,220,0.5)",
        strokeColor: "rgba(220,220,220,0.8)",
        highlightFill: "rgba(220,220,220,0.75)",
        highlightStroke: "rgba(220,220,220,1)",
        data: []
    };
    for(var i=0; i < data.weathers.length; i++) {
      temperatureData.labels.push("");
      dataSetContent.data.push(data.weathers[i].temperature);
    }

    temperatureData.datasets.push(dataSetContent);

    var myBarChart = new Chart(ctx).Bar(temperatureData, chartOptions);
  }

  var start = function(){
    bindEvents();
  };

  return{
    start:start
  };

}());
<commit_msg>coding #10 fixing home controller<commit_after>'use strict';

var Weather = require('../models/weather');
var WeatherMapView = require('../views/weather_map_view');
//var MapsConf = require('../conf/maps_coordinates');
var Config =  require('../conf/config');

module.exports = (function(){

  var selectors = {
    searchForm:'form[name=searchForm]',
    body:'body',
    leftToggleButton:'#toggle_sidemenu_l',
    leftMenu:'.sidebar-menu li a.accordion-toggle'
  };

  var options = {
    sbl: 'sb-r-o',
    sbr: 'sb-r-c',
    collapse: 'sb-l-m'
  };

  var searchWeatherByName = function(event){
    event.preventDefault();
    Weather.get({url:Config.hardAntUrl.concat('/weather'),
                 data:$(this).serialize()}).then(success,failure);
  };

  var success = function(data){
    //var placeInformation = getInformationFromPlace(data);
    //WeatherMapView.render(placeInformation);
    //drawHeatMap(data);
    //getTemperatureChart(data);
  };

  var failure = function(data){
    console.error("Error");
    console.error(data);
  };

  var sidebarLeftToggle = function(){
    if($('body.sb-top').length) { return; }

    if($(selectors.body).hasClass('sb-r-c') && options.collapse === "sb-l-m"){
      $(selectors.body).removeClass('sb-r-c');
    }

    $(selectors.body).toggleClass(options.collapse).removeClass('sb-r-o').addClass('sb-r-c');
    triggerResize();
  };

  var triggerResize = function() {
    setTimeout(function() {
      $(window).trigger('resize');

      if($(selectors.body).hasClass('sb-l-m')) {
        $(selectors.body).addClass('sb-l-disable-animation');
      }
      else {
        $(selectors.body).removeClass('sb-l-disable-animation');
      }
    }, 300);
  };

  var leftMenuToggle = function(event){
    event.preventDefault();
    if ($(selectors.body).hasClass('sb-l-m') && !$(this).parents('ul.sub-nav').length) { return; }

    if (!$(this).parents('ul.sub-nav').length) {

      if ($(window).width() > 900) {
        if ($('body.sb-top').length) { return; }
      }

      $('a.accordion-toggle.menu-open').next('ul').slideUp('fast', 'swing', function() {
        $(this).attr('style', '').prev().removeClass('menu-open');
      });
    }
    else {
      var activeMenu = $(this).next('ul.sub-nav');
      var siblingMenu = $(this).parent().siblings('li').children('a.accordion-toggle.menu-open').next('ul.sub-nav')

      activeMenu.slideUp('fast', 'swing', function() {
        $(this).attr('style', '').prev().removeClass('menu-open');
      });

      siblingMenu.slideUp('fast', 'swing', function() {
        $(this).attr('style', '').prev().removeClass('menu-open');
      });
    }

    if (!$(this).hasClass('menu-open')) {
      $(this).next('ul').slideToggle('fast', 'swing', function() {
        $(this).attr('style', '').prev().toggleClass('menu-open');
      });
    }

  };

  var bindEvents = function(){
    $(selectors.searchForm).on('submit',searchWeatherByName);
    $(selectors.leftToggleButton).on('click',sidebarLeftToggle);
    $(selectors.leftMenu).on('click',leftMenuToggle);
  };

  //var drawHeatMap = function (data) {
  //  var strictBounds = new google.maps.LatLngBounds(
  //        new google.maps.LatLng(19.600237, -99.403214),
  //        new google.maps.LatLng(19.222031, -98.941788)),
  //      distritoFederal = new google.maps.LatLng(19.381836, -99.1372371),
  //      map = new google.maps.Map(document.getElementById('map'),{
  //        zoom: 10,
  //        center: {lat: 19.45, lng: -99},
  //        maxZoom: 13,
  //        minZoom: 8,
  //        streetViewControl: false,
  //        mapTypeId: google.maps.MapTypeId.HYBRID
  //      }),
  //      heatmapData = [],
  //      coordinates;
  //  for(var i=0; i < data.weathers.length; i++) {
  //    coordinates = data.weathers[i].location.coordinates;
  //    var googleMapsPoint = new google.maps.LatLng(coordinates[1], coordinates[0]);
  //    heatmapData.push(googleMapsPoint);
  //  }

  //  var heatmap = new google.maps.visualization.HeatmapLayer({
  //    data: heatmapData
  //  });

  //  heatmap.setMap(map);

  //  var flightPlanCoordinates_DF = MapsConf.DF_Coordinates;

  //  var flightPath2 = new google.maps.Polyline({
  //    path: flightPlanCoordinates_DF,
  //    geodesic: true,
  //    strokeColor: '#E0FFFF',
  //    strokeOpacity: 1.0,
  //    strokeWeight: 2
  //  });

  //  flightPath2.setMap(map);
  //  heatmap.set('radius', 40);

  //  google.maps.event.addListener(map, 'zoom_changed', function() {
  //   if (map.getZoom() < minZoomLevel) map.setZoom(minZoomLevel);
  //  });
  //};

  var getInformationFromPlace = function (data) {
    var basicInformation = {},
        maxTemperature = "",
        minTemperature = "",
        averageTemperature = "";

    maxTemperature = "" + Math.max.apply(Math,data.weathers.map(function(element){return element.temperature;}));
    minTemperature = "" + Math.min.apply(Math,data.weathers.map(function(element){return element.temperature;}));
    averageTemperature = "" + data.weathers.map(function(obj) {return obj.temperature})
                  .reduce(function(a, b) { return a + b }) / data.weathers.length;

    basicInformation.place = data.weathers[0].fullName;
    basicInformation.maxTemperature = maxTemperature.substring(maxTemperature.indexOf(".") - 3,  maxTemperature.indexOf(".") + 3);
    basicInformation.minTemperature = minTemperature.substring(minTemperature.indexOf(".") - 3,  minTemperature.indexOf(".") + 3);
    basicInformation.averageTemperature = averageTemperature.substring(minTemperature.indexOf(".") - 3,  minTemperature.indexOf(".") + 3);

    return basicInformation;
  };

  var getTemperatureChart = function(data) {
    var ctx = document.getElementById("weatherChart").getContext("2d");
    var chartOptions = {
      scaleBeginAtZero : true,
      scaleShowGridLines : false,
      scaleGridLineColor : "rgba(0,0,0,.05)",
      scaleGridLineWidth : 1,
      scaleShowHorizontalLines: false,
      scaleShowVerticalLines: false,
      barShowStroke : true,
      animation: false,
    }
    var temperatureData = {
        labels: [],
        datasets: []
    };
    var dataSetContent = {
        fillColor: "rgba(220,220,220,0.5)",
        strokeColor: "rgba(220,220,220,0.8)",
        highlightFill: "rgba(220,220,220,0.75)",
        highlightStroke: "rgba(220,220,220,1)",
        data: []
    };
    for(var i=0; i < data.weathers.length; i++) {
      temperatureData.labels.push("");
      dataSetContent.data.push(data.weathers[i].temperature);
    }

    temperatureData.datasets.push(dataSetContent);

    var myBarChart = new Chart(ctx).Bar(temperatureData, chartOptions);
  }

  var start = function(){
    bindEvents();
  };

  return{
    start:start
  };

}());
<|endoftext|>


<commit_before>app.controller('MainController', MainController);

function MainController($scope, Error, CurrentUser, Game, Mobile){
    $scope.user = CurrentUser;
    $scope.game = Game;
    $scope.validationError = Error;
    $scope.userState = 'start';
    $scope.onMobile = Mobile;

    if(!$scope.onMobile) {
      Game.createNew();
    }

    $scope.connectToGame = function (id){
        if(!id) {Error.message = "You need to enter an ID."; return;}
        if(id.length !== 6) {Error.message = "The ID should be 6 characters long."; return;}

        id = id.toUpperCase();
        Game.connectTo(id);
    }

    $scope.setUser = function(name){
        if(!name) {Error.message = "You need to enter a name."; return;}
        Error.message = "";

        CurrentUser.auth().then(function(authData) {
            var user = CurrentUser.setDetails(name);

            console.log("Logged in as:", authData.uid);
            CurrentUser.ref = Game.ref.child('players').child(authData.uid);
            CurrentUser.ref.set(user);
            CurrentUser.ref.onDisconnect().remove();

            CurrentUser.state = 'registered';
            Game.playerOrder.push(authData.uid);
            Game.ref.update({playerOrder: Game.playerOrder});
        }, {remember: "sessionOnly"})
         .catch(function(error) {
          console.error("Authentication failed:", error);
        });
    }

    $scope.toggleReady = function(){
      $scope.user.ready = !$scope.user.ready;
      CurrentUser.toggleReady($scope.user.ready);
    }

}
<commit_msg>Bug-fix for undefined playerOrder<commit_after>app.controller('MainController', MainController);

function MainController($scope, Error, CurrentUser, Game, Mobile){
    $scope.user = CurrentUser;
    $scope.game = Game;
    $scope.validationError = Error;
    $scope.userState = 'start';
    $scope.onMobile = Mobile;

    if(!$scope.onMobile) {
      Game.createNew();
    }

    $scope.connectToGame = function (id){
        if(!id) {Error.message = "You need to enter an ID."; return;}
        if(id.length !== 6) {Error.message = "The ID should be 6 characters long."; return;}

        id = id.toUpperCase();
        Game.connectTo(id);
    }

    $scope.setUser = function(name){
        if(!name) {Error.message = "You need to enter a name."; return;}
        Error.message = "";

        CurrentUser.auth().then(function(authData) {
            var user = CurrentUser.setDetails(name);

            console.log("Logged in as:", authData.uid);
            CurrentUser.ref = Game.ref.child('players').child(authData.uid);
            CurrentUser.ref.set(user);
            CurrentUser.ref.onDisconnect().remove();

            CurrentUser.state = 'registered';

            Game.playerOrder = Game.playerOrder || [];
            Game.playerOrder.push(authData.uid);
            Game.ref.update({playerOrder: Game.playerOrder});
        }, {remember: "sessionOnly"})
         .catch(function(error) {
          console.error("Authentication failed:", error);
        });
    }

    $scope.toggleReady = function(){
      $scope.user.ready = !$scope.user.ready;
      CurrentUser.toggleReady($scope.user.ready);
    }

}
<|endoftext|>