<commit_before>'use strict'
var ObjectId = require("mongodb").ObjectId;
require('mongodb-toolkit');
var DLModels = require('dl-models');
var assert = require('assert');
var map = DLModels.map;
var i18n = require('dl-i18n');
var UnitPaymentPriceCorrectionNote = DLModels.purchasing.UnitPaymentPriceCorrectionNote;
var UnitPaymentOrderManager = require('./unit-payment-order-manager');
var BaseManager = require('../base-manager');

module.exports = class UnitPaymentPriceCorrectionNoteManager extends BaseManager {
    constructor(db, user) {
        super(db, user);
        this.collection = this.db.use(map.purchasing.collection.UnitPaymentPriceCorrectionNote);
        this.unitPaymentOrderManager = new UnitPaymentOrderManager(db, user);
    }

    _validate(unitPaymentPriceCorrectionNote) {
        var errors = {};
        return new Promise((resolve, reject) => {
            var valid = unitPaymentPriceCorrectionNote;

            var getUnitPaymentPriceCorrectionNote = this.collection.singleOrDefault({
                "$and": [{
                    _id: {
                        '$ne': new ObjectId(valid._id)
                    }
                }, {
                        "no": valid.no
                    }, {
                        _deleted: false
                    }]
            });

            var getUnitPaymentOrder = this.unitPaymentOrderManager.getSingleByIdOrDefault(valid.unitPaymentOrder._id);

            Promise.all([getUnitPaymentPriceCorrectionNote,getUnitPaymentOrder])
                .then(results => {
                    var _unitPaymentPriceCorrectionNote = results[0];
                    var _unitPaymentOrder = results[1];
                    var now = new Date();

                    if (!valid.no || valid.no == '')
                        errors["no"] = i18n.__("UnitPaymentPriceCorrectionNote.no.isRequired:%s is required", i18n.__("UnitPaymentPriceCorrectionNote.no._:No"));
                    else if (_unitPaymentPriceCorrectionNote)
                        errors["no"] = i18n.__("UnitPaymentPriceCorrectionNote.no.isExists:%s is already exists", i18n.__("UnitPaymentPriceCorrectionNote.no._:No"));

                    if (!_unitPaymentOrder)
                        errors["unitPaymentOrder"] = i18n.__("UnitPaymentPriceCorrectionNote.unitPaymentOrder.isRequired:%s is required", i18n.__("UnitPaymentPriceCorrectionNote.unitPaymentOrder._:Unit Payment Order"));
                    else if (!valid.unitPaymentOrderId)
                        errors["unitPaymentOrder"] = i18n.__("UnitPaymentPriceCorrectionNote.unitPaymentOrder.isRequired:%s is required", i18n.__("UnitPaymentPriceCorrectionNote.unitPaymentOrder._:Unit Payment Order"));
                    else if (valid.unitPaymentOrder) {
                        if (!valid.unitPaymentOrder._id)
                            errors["unitPaymentOrder"] = i18n.__("UnitPaymentPriceCorrectionNote.unitPaymentOrder.isRequired:%s is required", i18n.__("UnitPaymentPriceCorrectionNote.unitPaymentOrder._:Unit Payment Order"));
                    }
                    else if (!valid.unitPaymentOrder)
                        errors["unitPaymentOrder"] = i18n.__("UnitPaymentPriceCorrectionNote.unitPaymentOrder.isRequired:%s is required", i18n.__("UnitPaymentPriceCorrectionNote.unitPaymentOrder._:Unit Payment Order"));

                    if (!valid.invoiceCorrectionNo || valid.invoiceCorrectionNo == '')
                        errors["invoiceCorrectionNo"] = i18n.__("UnitPaymentPriceCorrectionNote.invoiceCorrectionNo.isRequired:%s is required", i18n.__("UnitPaymentPriceCorrectionNote.invoiceCorrectionNo._:Invoice Correction No"));

                    if (!valid.invoiceCorrectionDate || valid.invoiceCorrectionDate == '')
                        errors["invoiceCorrectionDate"] = i18n.__("UnitPaymentPriceCorrectionNote.invoiceCorrectionDate.isRequired:%s is required", i18n.__("UnitPaymentPriceCorrectionNote.invoiceCorrectionDate._:Invoice Correction Date"));

                    if (valid.items) {
                        if (valid.items.length <= 0) {
                        }
                        else {
                            var itemErrors = [];
                            for (var item of valid.items) {
                                var itemError = {};
                                if (item.pricePerUnit <= 0)
                                    itemError["pricePerUnit"] = i18n.__("UnitPaymentPriceCorrectionNote.items.pricePerUnit.isRequired:%s is required", i18n.__("UnitPaymentPriceCorrectionNote.items.pricePerUnit._:Price Per Unit"));

                                if (item.priceTotal <= 0)
                                    itemError["priceTotal"] = i18n.__("UnitPaymentPriceCorrectionNote.items.priceTotal.isRequired:%s is required", i18n.__("UnitPaymentPriceCorrectionNote.items.priceTotal._:Total Price"));

                                itemErrors.push(itemError);
                            }
                            for (var itemError of itemErrors) {
                                for (var prop in itemError) {
                                    errors.items = itemErrors;
                                    break;
                                }
                                if (errors.items)
                                    break;
                            }
                        }
                    }
                    else {
                        errors["items"] = i18n.__("UnitPaymentPriceCorrectionNote.items.isRequired:%s is required", i18n.__("UnitPaymentPriceCorrectionNote.items._:Item"));
                    }

                    if (Object.getOwnPropertyNames(errors).length > 0) {
                        var ValidationError = require('../../validation-error');
                        reject(new ValidationError('data does not pass validation', errors));
                    }

                    valid.unitPaymentOrderId = _unitPaymentOrder._id;
                    valid.unitPaymentOrder = _unitPaymentOrder;

                    for (var item of valid.items) {
                        for (var _unitPaymentOrderItem of _unitPaymentOrder.items){
                            for(var unitReceiptNoteItem of _unitPaymentOrderItem.unitReceiptNote.items) {
                                    var _purchaseOrderExternalId = new ObjectId(item.purchaseOrderExternalId);
                                    var _productId = new ObjectId(item.productId);

                                    if (_purchaseOrderExternalId.equals(unitReceiptNoteItem.purchaseOrder.purchaseOrderExternalId) && _productId.equals(unitReceiptNoteItem.product._id)) {
                                        item.purchaseOrderExternalId = unitReceiptNoteItem.purchaseOrder.purchaseOrderExternalId;
                                        item.purchaseOrderExternal = unitReceiptNoteItem.purchaseOrder.purchaseOrderExternal;
                                        item.purchaseRequestId = unitReceiptNoteItem.purchaseOrder.purchaseRequestId;
                                        item.purchaseRequest = unitReceiptNoteItem.purchaseOrder.purchaseRequest;
                                        item.productId = unitReceiptNoteItem.product._id;
                                        item.product = unitReceiptNoteItem.product;
                                        item.quantity = unitReceiptNoteItem.deliveredQuantity;
                                        item.uom = unitReceiptNoteItem.deliveredUom;
                                        item.currency = unitReceiptNoteItem.currency;
                                        item.currencyRate = unitReceiptNoteItem.currencyRate;
                                        break;
                                    }
                        }
                    }
                    }

                    if (!valid.stamp)
                        valid = new UnitPaymentPriceCorrectionNote(valid);

                    valid.stamp(this.user.username, 'manager');
                    resolve(valid);
                })
                .catch(e => {
                    reject(e);
                })

        });
    }

    _getQuery(paging) {
        var deletedFilter = {
            _deleted: false
        }, keywordFilter = {};

        var query = {};

        if (paging.keyword) {
            var regex = new RegExp(paging.keyword, "i");

            var filterNo = {
                'no': {
                    '$regex': regex
                }
            };

            var filterSupplierName = {
                'unitPaymentOrder.supplier.name': {
                    '$regex': regex
                }
            };

            var filterUnitCoverLetterNo = {
                "unitCoverLetterNo": {
                    '$regex': regex
                }
            };

            keywordFilter = {
                '$or': [filterNo, filterSupplierName, filterUnitCoverLetterNo]
            };
        }
        query = { '$and': [deletedFilter, paging.filter, keywordFilter] }
        return query;
    }

    _createIndexes() {
        var createdDateIndex = {
            name: `ix_${map.master.collection.PurchaseOrder}__createdDate`,
            key: {
                _createdDate: -1
            }
        }
        var poNoIndex = {
            name: `ix_${map.master.collection.PurchaseOrder}_no`,
            key: {
                no: -1
            },
            unique: true
        }

        return this.collection.createIndexes([createdDateIndex, poNoIndex]);
    }

    pdf(id) {
        return new Promise((resolve, reject) => {

            this.getSingleById(id)
                .then(unitReceiptNote => {
                    var getDefinition = require('../../pdf/definitions/unit-receipt-note');
                    var definition = getDefinition(unitReceiptNote);

                    var generatePdf = require('../../pdf/pdf-generator');
                    generatePdf(definition)
                        .then(binary => {
                            resolve(binary);
                        })
                        .catch(e => {
                            reject(e);
                        });
                })
                .catch(e => {
                    reject(e);
                });

        });
    }

}<commit_msg>fix unit-payment-price-correction-note-manager<commit_after>'use strict'
var ObjectId = require("mongodb").ObjectId;
require('mongodb-toolkit');
var DLModels = require('dl-models');
var assert = require('assert');
var map = DLModels.map;
var i18n = require('dl-i18n');
var UnitPaymentPriceCorrectionNote = DLModels.purchasing.UnitPaymentPriceCorrectionNote;
var UnitPaymentOrderManager = require('./unit-payment-order-manager');
var BaseManager = require('../base-manager');

module.exports = class UnitPaymentPriceCorrectionNoteManager extends BaseManager {
    constructor(db, user) {
        super(db, user);
        this.collection = this.db.use(map.purchasing.collection.UnitPaymentPriceCorrectionNote);
        this.unitPaymentOrderManager = new UnitPaymentOrderManager(db, user);
    }

    _validate(unitPaymentPriceCorrectionNote) {
        var errors = {};
        return new Promise((resolve, reject) => {
            var valid = unitPaymentPriceCorrectionNote;

            var getUnitPaymentPriceCorrectionNote = this.collection.singleOrDefault({
                "$and": [{
                    _id: {
                        '$ne': new ObjectId(valid._id)
                    }
                }, {
                    "no": valid.no
                }, {
                    _deleted: false
                }]
            });

            var getUnitPaymentOrder = this.unitPaymentOrderManager.getSingleByIdOrDefault(valid.unitPaymentOrder._id);

            Promise.all([getUnitPaymentPriceCorrectionNote, getUnitPaymentOrder])
                .then(results => {
                    var _unitPaymentPriceCorrectionNote = results[0];
                    var _unitPaymentOrder = results[1];
                    var now = new Date();

                    // if (!valid.no || valid.no == '')
                    //     errors["no"] = i18n.__("UnitPaymentPriceCorrectionNote.no.isRequired:%s is required", i18n.__("UnitPaymentPriceCorrectionNote.no._:No"));
                    if (_unitPaymentPriceCorrectionNote)
                        errors["no"] = i18n.__("UnitPaymentPriceCorrectionNote.no.isExists:%s is already exists", i18n.__("UnitPaymentPriceCorrectionNote.no._:No"));

                    if (!_unitPaymentOrder)
                        errors["unitPaymentOrder"] = i18n.__("UnitPaymentPriceCorrectionNote.unitPaymentOrder.isRequired:%s is required", i18n.__("UnitPaymentPriceCorrectionNote.unitPaymentOrder._:Unit Payment Order"));
                    else if (!valid.unitPaymentOrderId)
                        errors["unitPaymentOrder"] = i18n.__("UnitPaymentPriceCorrectionNote.unitPaymentOrder.isRequired:%s is required", i18n.__("UnitPaymentPriceCorrectionNote.unitPaymentOrder._:Unit Payment Order"));
                    else if (valid.unitPaymentOrder) {
                        if (!valid.unitPaymentOrder._id)
                            errors["unitPaymentOrder"] = i18n.__("UnitPaymentPriceCorrectionNote.unitPaymentOrder.isRequired:%s is required", i18n.__("UnitPaymentPriceCorrectionNote.unitPaymentOrder._:Unit Payment Order"));
                    }
                    else if (!valid.unitPaymentOrder)
                        errors["unitPaymentOrder"] = i18n.__("UnitPaymentPriceCorrectionNote.unitPaymentOrder.isRequired:%s is required", i18n.__("UnitPaymentPriceCorrectionNote.unitPaymentOrder._:Unit Payment Order"));

                    if (!valid.invoiceCorrectionNo || valid.invoiceCorrectionNo == '')
                        errors["invoiceCorrectionNo"] = i18n.__("UnitPaymentPriceCorrectionNote.invoiceCorrectionNo.isRequired:%s is required", i18n.__("UnitPaymentPriceCorrectionNote.invoiceCorrectionNo._:Invoice Correction No"));

                    if (!valid.invoiceCorrectionDate || valid.invoiceCorrectionDate == '')
                        errors["invoiceCorrectionDate"] = i18n.__("UnitPaymentPriceCorrectionNote.invoiceCorrectionDate.isRequired:%s is required", i18n.__("UnitPaymentPriceCorrectionNote.invoiceCorrectionDate._:Invoice Correction Date"));

                    if (valid.items) {
                        if (valid.items.length > 0) {
                            var itemErrors = [];
                            for (var item of valid.items) {
                                var itemError = {};
                                if (item.pricePerUnit <= 0)
                                    itemError["pricePerUnit"] = i18n.__("UnitPaymentPriceCorrectionNote.items.pricePerUnit.isRequired:%s is required", i18n.__("UnitPaymentPriceCorrectionNote.items.pricePerUnit._:Price Per Unit"));

                                if (item.priceTotal <= 0)
                                    itemError["priceTotal"] = i18n.__("UnitPaymentPriceCorrectionNote.items.priceTotal.isRequired:%s is required", i18n.__("UnitPaymentPriceCorrectionNote.items.priceTotal._:Total Price"));

                                itemErrors.push(itemError);
                            }
                            for (var itemError of itemErrors) {
                                for (var prop in itemError) {
                                    errors.items = itemErrors;
                                    break;
                                }
                                if (errors.items)
                                    break;
                            }
                        }

                        // if (valid.items.length == 0)
                        //     errors["items"] = i18n.__("UnitPaymentPriceCorrectionNote.items.isRequired:%s is required", i18n.__("UnitPaymentPriceCorrectionNote.items._:Item"));
                    }
                    else {
                        errors["items"] = i18n.__("UnitPaymentPriceCorrectionNote.items.isRequired:%s is required", i18n.__("UnitPaymentPriceCorrectionNote.items._:Item"));
                    }

                    if (Object.getOwnPropertyNames(errors).length > 0) {
                        var ValidationError = require('../../validation-error');
                        reject(new ValidationError('data does not pass validation', errors));
                    }

                    valid.unitPaymentOrderId = _unitPaymentOrder._id;
                    valid.unitPaymentOrder = _unitPaymentOrder;

                    for (var item of valid.items) {
                        for (var _unitPaymentOrderItem of _unitPaymentOrder.items) {
                            for (var unitReceiptNoteItem of _unitPaymentOrderItem.unitReceiptNote.items) {
                                var _purchaseOrderExternalId = new ObjectId(item.purchaseOrderExternalId);
                                var _productId = new ObjectId(item.productId);

                                if (_purchaseOrderExternalId.equals(unitReceiptNoteItem.purchaseOrder.purchaseOrderExternalId) && _productId.equals(unitReceiptNoteItem.product._id)) {
                                    item.purchaseOrderExternalId = unitReceiptNoteItem.purchaseOrder.purchaseOrderExternalId;
                                    item.purchaseOrderExternal = unitReceiptNoteItem.purchaseOrder.purchaseOrderExternal;
                                    item.purchaseRequestId = unitReceiptNoteItem.purchaseOrder.purchaseRequestId;
                                    item.purchaseRequest = unitReceiptNoteItem.purchaseOrder.purchaseRequest;
                                    item.productId = unitReceiptNoteItem.product._id;
                                    item.product = unitReceiptNoteItem.product;
                                    item.quantity = unitReceiptNoteItem.deliveredQuantity;
                                    item.uom = unitReceiptNoteItem.deliveredUom;
                                    item.currency = unitReceiptNoteItem.currency;
                                    item.currencyRate = unitReceiptNoteItem.currencyRate;
                                    break;
                                }
                            }
                        }
                    }

                    if (!valid.stamp)
                        valid = new UnitPaymentPriceCorrectionNote(valid);

                    valid.stamp(this.user.username, 'manager');
                    resolve(valid);
                })
                .catch(e => {
                    reject(e);
                })

        });
    }

    _getQuery(paging) {
        var deletedFilter = {
                _deleted: false
            },
            keywordFilter = {};

        var query = {};

        if (paging.keyword) {
            var regex = new RegExp(paging.keyword, "i");

            var filterNo = {
                'no': {
                    '$regex': regex
                }
            };

            var filterSupplierName = {
                'unitPaymentOrder.supplier.name': {
                    '$regex': regex
                }
            };

            var filterUnitCoverLetterNo = {
                "unitCoverLetterNo": {
                    '$regex': regex
                }
            };

            keywordFilter = {
                '$or': [filterNo, filterSupplierName, filterUnitCoverLetterNo]
            };
        }
        query = {
            '$and': [deletedFilter, paging.filter, keywordFilter]
        }
        return query;
    }

    _createIndexes() {
        var createdDateIndex = {
            name: `ix_${map.master.collection.PurchaseOrder}__createdDate`,
            key: {
                _createdDate: -1
            }
        }
        var poNoIndex = {
            name: `ix_${map.master.collection.PurchaseOrder}_no`,
            key: {
                no: -1
            },
            unique: true
        }

        return this.collection.createIndexes([createdDateIndex, poNoIndex]);
    }

    pdf(id) {
        return new Promise((resolve, reject) => {

            this.getSingleById(id)
                .then(unitReceiptNote => {
                    var getDefinition = require('../../pdf/definitions/unit-payment-correction-note');
                    var definition = getDefinition(unitReceiptNote);

                    var generatePdf = require('../../pdf/pdf-generator');
                    generatePdf(definition)
                        .then(binary => {
                            resolve(binary);
                        })
                        .catch(e => {
                            reject(e);
                        });
                })
                .catch(e => {
                    reject(e);
                });

        });
    }

    generateNo(unit) {
        var now = new Date();
        var stamp = now / 1000 | 0;
        var code = stamp.toString();
        var locale = 'id-ID';
        var moment = require('moment');
        moment.locale(locale);
        var no = `NDO${unit.code.toUpperCase()}${moment(new Date()).format("YYMM")}${code}`;
        return no;
    }

    generateNo(unit, category) {
        var now = new Date();
        var stamp = now / 1000 | 0;
        var code = stamp.toString();
        var locale = 'id-ID';
        var moment = require('moment');
        moment.locale(locale);
        var no = `NDO${unit.toUpperCase()}${category.toUpperCase()}${moment(new Date()).format("YYMM")}${code}`;
        return no;
    }

    create(unitPaymentPriceCorrectionNote) {
        return new Promise((resolve, reject) => {
            this._createIndexes()
                .then((createIndexResults) => {
                    this._validate(unitPaymentPriceCorrectionNote)
                        .then(validData => {
                            validData.no = this.generateNo(validData.unitPaymentOrder.unit.code, validData.unitPaymentOrder.category.code);
                            this.collection.insert(validData)
                                .then(id => {
                                    resolve(id);
                                })
                                .catch(e => {
                                    reject(e);
                                });
                        })
                        .catch(e => {
                            reject(e);
                        });
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

}
<|endoftext|>


<commit_before>import 'dom-shims/shim/CustomEvent';
import 'dom-shims/shim/Element.mutation';
import 'es6-shim';
import es7 from 'es7-shim';

import { EventEmitter } from 'events';
import { FastClick } from 'fastclick';
import { request } from 'https';
import get from 'lodash-es/get';

import {
  HttpConnection,
  PubSub,
  WsConnection,
  load as loadApi
} from '@scola/api';

import {
  Auth,
  setUser,
  logIn,
  logOut,
  load as loadAuth
} from '@scola/auth-client';

import {
  cache as cacheFactory,
  i18n as i18nFactory,
  router as routerFactory,
  main as mainFactory,
  menu as menuFactory,
  model as modelFactory
} from '@scola/d3';

import { ScolaError } from '@scola/error';
import { load as loadValidator } from '@scola/validator';
import Route from './route';

export default class Client extends EventEmitter {
  constructor() {
    super();

    this._auth = null;
    this._config = null;
    this._http = null;
    this._i18n = null;
    this._pubsub = null;
    this._router = null;
    this._storage = null;
    this._user = null;
    this._ws = null;

    this._mainModifier = null;
    this._menuModifiers = new Map();

    this._state = {
      auth: false,
      open: false
    };

    this._fastClick = FastClick.attach(document.body);

    this._handleClose = () => this._close();
    this._handleError = (e) => this._error(e);
    this._handleMain = (t) => this._main(t);
    this._handleMenu = (t) => this._menu(t);
    this._handleOnline = () => this._online();
    this._handleOpen = (e) => this._open(e);
    this._handleSetAuth = (e) => this._setAuth(e);
  }

  destroy() {
    this._fastClick.destroy();

    this._unbindAuth();
    this._unbindRouter();
    this._unbindWs();
  }

  state(name, value = null) {
    if (value === null) {
      return typeof this._state[name] === 'undefined' ?
        null : this._state[name];
    }

    this._state[name] = value;
    this.emit(name, value);

    return this;
  }

  auth(options = null) {
    if (options === null) {
      return this._auth;
    }

    const model = modelFactory(options.name, true)
      .connection(this._ws || this._http)
      .serialize((d) => this._serializeAuth(d));

    const cache = cacheFactory()
      .model(model);

    this._auth = new Auth()
      .cache(cache);

    this._bindAuth();
    return this;
  }

  config(value = null) {
    if (value === null) {
      return this._config;
    }

    if (typeof value === 'string') {
      return get(this._config, value);
    }

    this._config = value;
    return this;
  }

  error(message) {
    return new ScolaError(message);
  }

  http(options = null) {
    if (options === null) {
      return this._http;
    }

    this._http = new HttpConnection()
      .http({ request })
      .codec(options.codec)
      .host(options.host)
      .port(options.port);

    return this;
  }

  i18n(options = null) {
    if (options === null) {
      return this._i18n;
    }

    this._i18n = i18nFactory()
      .locale(options.locale)
      .timezone(options.timezone);

    return this;
  }

  main(modifier = (e) => e.size()) {
    this._mainModifier = modifier;
    this._router.target('main').render(this._handleMain);

    return this;
  }

  menu(name, modifier = (e) => e.size()) {
    this._menuModifiers.set(name, modifier);
    this._router.target(name).render(this._handleMenu);

    return this;
  }

  pubsub(options = null) {
    if (this._pubsub === null) {
      this._pubsub = new PubSub();
    }

    if (options === null) {
      return this._pubsub;
    }

    if (options === true) {
      this._pubsub.connection(this._ws);
      return this;
    }

    options.factory = (u, p) => {
      return new WebSocket(u, p);
    };

    const connection = new WsConnection()
      .codec(options.codec)
      .reconnector(options);

    this._pubsub.connection(connection);
    return this;
  }

  route() {
    return new Route()
      .client(this);
  }

  router(options = null) {
    if (options === null) {
      return this._router;
    }

    const model = modelFactory(options.name, true);
    this._router = routerFactory().model(model);

    this._bindRouter();
    return this;
  }

  storage(value = null) {
    if (value === null) {
      return this._storage;
    }

    this._storage = value;
    return this;
  }

  user(value = null) {
    if (value === null) {
      return this._user;
    }

    this._user = value === false ?
      null : value;

    if (this._ws) {
      this._ws.user(value);
    }

    if (this._http) {
      this._http.user(value);
    }

    if (this._router) {
      this._router.user(value);
    }

    return this;
  }

  ws(options = null) {
    if (options === null) {
      return this._ws;
    }

    options.factory = (u, p) => {
      return new WebSocket(u, p);
    };

    this._ws = new WsConnection()
      .codec(options.codec)
      .reconnector(options);

    this._bindWs();
    return this;
  }

  start() {
    es7.shim();

    loadApi(this);
    loadValidator(this);

    if (this._pubsub) {
      this._pubsub.open();
    }

    if (this._auth === null) {
      this._popState();
      return this;
    }

    loadAuth(this);
    setUser(this, () => this._popState());

    return this;
  }

  _bindAuth() {
    if (this._auth) {
      this.setMaxListeners(this.getMaxListeners() + 1);
      this.on('auth', this._handleSetAuth);
    }
  }

  _unbindAuth() {
    if (this._auth) {
      this.setMaxListeners(this.getMaxListeners() - 1);
      this.removeListener('auth', this._handleSetAuth);
    }
  }

  _bindRouter() {
    if (this._router) {
      this._router.setMaxListeners(this._router.getMaxListeners() + 1);
      this._router.on('error', this._handleError);
    }
  }

  _unbindRouter() {
    if (this._router) {
      this._router.setMaxListeners(this._router.getMaxListeners() - 1);
      this._router.removeListener('error', this._handleError);
    }
  }

  _bindWs() {
    if (this._ws) {
      window.addEventListener('online', this._handleOnline);
      this._ws.setMaxListeners(this._ws.getMaxListeners() + 1);
      this._ws.on('close', this._handleClose);
      this._ws.on('error', this._handleError);
      this._ws.on('open', this._handleOpen);
    }
  }

  _unbindWs() {
    if (this._ws) {
      window.removeEventListener('online', this._handleOnline);
      this._ws.setMaxListeners(this._ws.getMaxListeners() - 1);
      this._ws.removeListener('close', this._handleClose);
      this._ws.removeListener('error', this._handleError);
      this._ws.removeListener('open', this._handleOpen);
    }
  }

  _popState() {
    const filter = this._user === null ? ['scola.auth'] : null;

    this._router.popState(filter);

    if (this._ws) {
      if (window.navigator.onLine === true) {
        this._ws.open();
      }
    }
  }

  _setAuth(value) {
    if (value !== 'valid' && this._mainModifier) {
      this._router.target('main').destroy();
    }
  }

  _serializeAuth(data) {
    return {
      token: data.user.token
    };
  }

  _error(error) {
    if (error.status === 500) {
      return;
    }

    if (error.status === 401 || error.status === 403) {
      logOut(this);
      return;
    }

    this.emit('error', error);
  }

  _main(target) {
    let element = mainFactory()
      .mode('over');

    element = this._mainModifier(element);
    const menus = Array.from(this._menuModifiers.keys());

    menus.forEach((name) => {
      const menu = target
        .router()
        .target(name)
        .element();

      if (menu !== null) {
        element.append(menu);
      }
    });

    document.body.appendChild(element.root().node());
    element.show(true);

    target
      .element(element)
      .once('destroy', () => {
        element.show(false).on('end', () => {
          element.destroy();
          target.routes(false);

          menus.forEach((name) => {
            target
              .router()
              .target(name)
              .destroy();
          });
        });
      });
  }

  _menu(target) {
    const modifier = this._menuModifiers.get(target.name());

    let element = menuFactory()
      .position('left');

    element = modifier(element);

    const main = target
      .router()
      .target('main')
      .element();

    if (main !== null) {
      main.append(element);
    }

    target
      .element(element)
      .once('destroy', () => {
        element.destroy();
        target.routes(false);
      });
  }

  _close() {
    this.state('open', false);
  }

  _online() {
    if (this._ws) {
      this._ws.open();
    }
  }

  _open() {
    this.state('open', true);

    if (this._auth) {
      logIn(this);
    }
  }
}
<commit_msg>Add api dictionary<commit_after>import 'dom-shims/shim/CustomEvent';
import 'dom-shims/shim/Element.mutation';
import 'es6-shim';
import es7 from 'es7-shim';

import { EventEmitter } from 'events';
import { FastClick } from 'fastclick';
import { request } from 'https';
import get from 'lodash-es/get';

import {
  HttpConnection,
  PubSub,
  WsConnection,
  dictionary,
  load as loadApi
} from '@scola/api';

import {
  Auth,
  setUser,
  logIn,
  logOut,
  load as loadAuth
} from '@scola/auth-client';

import {
  cache as cacheFactory,
  i18n as i18nFactory,
  router as routerFactory,
  main as mainFactory,
  menu as menuFactory,
  model as modelFactory
} from '@scola/d3';

import { ScolaError } from '@scola/error';
import { load as loadValidator } from '@scola/validator';
import Route from './route';

export default class Client extends EventEmitter {
  constructor() {
    super();

    this._auth = null;
    this._config = null;
    this._http = null;
    this._i18n = null;
    this._pubsub = null;
    this._router = null;
    this._storage = null;
    this._user = null;
    this._ws = null;

    this._mainModifier = null;
    this._menuModifiers = new Map();

    this._state = {
      auth: false,
      open: false
    };

    this._fastClick = FastClick.attach(document.body);

    this._handleClose = () => this._close();
    this._handleError = (e) => this._error(e);
    this._handleMain = (t) => this._main(t);
    this._handleMenu = (t) => this._menu(t);
    this._handleOnline = () => this._online();
    this._handleOpen = (e) => this._open(e);
    this._handleSetAuth = (e) => this._setAuth(e);
  }

  destroy() {
    this._fastClick.destroy();

    this._unbindAuth();
    this._unbindRouter();
    this._unbindWs();
  }

  state(name, value = null) {
    if (value === null) {
      return typeof this._state[name] === 'undefined' ?
        null : this._state[name];
    }

    this._state[name] = value;
    this.emit(name, value);

    return this;
  }

  auth(options = null) {
    if (options === null) {
      return this._auth;
    }

    const model = modelFactory(options.name, true)
      .connection(this._ws || this._http)
      .serialize((d) => this._serializeAuth(d));

    const cache = cacheFactory()
      .model(model);

    this._auth = new Auth()
      .cache(cache);

    this._bindAuth();
    return this;
  }

  config(value = null) {
    if (value === null) {
      return this._config;
    }

    if (typeof value === 'string') {
      return get(this._config, value);
    }

    this._config = value;
    return this;
  }

  error(message) {
    return new ScolaError(message);
  }

  http(options = null) {
    if (options === null) {
      return this._http;
    }

    this._http = new HttpConnection()
      .http({ request })
      .codec(options.codec)
      .host(options.host)
      .port(options.port);

    return this;
  }

  i18n(options = null) {
    if (options === null) {
      return this._i18n;
    }

    this._i18n = i18nFactory()
      .locale(options.locale)
      .timezone(options.timezone);

    return this;
  }

  main(modifier = (e) => e.size()) {
    this._mainModifier = modifier;
    this._router.target('main').render(this._handleMain);

    return this;
  }

  menu(name, modifier = (e) => e.size()) {
    this._menuModifiers.set(name, modifier);
    this._router.target(name).render(this._handleMenu);

    return this;
  }

  pubsub(options = null) {
    if (this._pubsub === null) {
      this._pubsub = new PubSub();
    }

    if (options === null) {
      return this._pubsub;
    }

    if (options === true) {
      this._pubsub.connection(this._ws);
      return this;
    }

    options.factory = (u, p) => {
      return new WebSocket(u, p);
    };

    const connection = new WsConnection()
      .codec(options.codec)
      .reconnector(options);

    this._pubsub.connection(connection);
    return this;
  }

  route() {
    return new Route()
      .client(this);
  }

  router(options = null) {
    if (options === null) {
      return this._router;
    }

    const model = modelFactory(options.name, true);
    this._router = routerFactory().model(model);

    this._bindRouter();
    return this;
  }

  storage(value = null) {
    if (value === null) {
      return this._storage;
    }

    this._storage = value;
    return this;
  }

  user(value = null) {
    if (value === null) {
      return this._user;
    }

    this._user = value === false ?
      null : value;

    if (this._ws) {
      this._ws.user(value);
    }

    if (this._http) {
      this._http.user(value);
    }

    if (this._router) {
      this._router.user(value);
    }

    return this;
  }

  ws(options = null) {
    if (options === null) {
      return this._ws;
    }

    options = Object.assign({}, options);

    options.dictionary = options.dictionary || dictionary;
    options.factory = (u, p) => {
      return new WebSocket(u, p);
    };

    this._ws = new WsConnection()
      .codec(options.codec)
      .dictionary(options.dictionary)
      .reconnector(options);

    this._bindWs();
    return this;
  }

  start() {
    es7.shim();

    loadApi(this);
    loadValidator(this);

    if (this._pubsub) {
      this._pubsub.open();
    }

    if (this._auth === null) {
      this._popState();
      return this;
    }

    loadAuth(this);
    setUser(this, () => this._popState());

    return this;
  }

  _bindAuth() {
    if (this._auth) {
      this.setMaxListeners(this.getMaxListeners() + 1);
      this.on('auth', this._handleSetAuth);
    }
  }

  _unbindAuth() {
    if (this._auth) {
      this.setMaxListeners(this.getMaxListeners() - 1);
      this.removeListener('auth', this._handleSetAuth);
    }
  }

  _bindRouter() {
    if (this._router) {
      this._router.setMaxListeners(this._router.getMaxListeners() + 1);
      this._router.on('error', this._handleError);
    }
  }

  _unbindRouter() {
    if (this._router) {
      this._router.setMaxListeners(this._router.getMaxListeners() - 1);
      this._router.removeListener('error', this._handleError);
    }
  }

  _bindWs() {
    if (this._ws) {
      window.addEventListener('online', this._handleOnline);
      this._ws.setMaxListeners(this._ws.getMaxListeners() + 1);
      this._ws.on('close', this._handleClose);
      this._ws.on('error', this._handleError);
      this._ws.on('open', this._handleOpen);
    }
  }

  _unbindWs() {
    if (this._ws) {
      window.removeEventListener('online', this._handleOnline);
      this._ws.setMaxListeners(this._ws.getMaxListeners() - 1);
      this._ws.removeListener('close', this._handleClose);
      this._ws.removeListener('error', this._handleError);
      this._ws.removeListener('open', this._handleOpen);
    }
  }

  _popState() {
    const filter = this._user === null ? ['scola.auth'] : null;

    this._router.popState(filter);

    if (this._ws) {
      if (window.navigator.onLine === true) {
        this._ws.open();
      }
    }
  }

  _setAuth(value) {
    if (value !== 'valid' && this._mainModifier) {
      this._router.target('main').destroy();
    }
  }

  _serializeAuth(data) {
    return {
      token: data.user.token
    };
  }

  _error(error) {
    if (error.status === 500) {
      return;
    }

    if (error.status === 401 || error.status === 403) {
      logOut(this);
      return;
    }

    this.emit('error', error);
  }

  _main(target) {
    let element = mainFactory()
      .mode('over');

    element = this._mainModifier(element);
    const menus = Array.from(this._menuModifiers.keys());

    menus.forEach((name) => {
      const menu = target
        .router()
        .target(name)
        .element();

      if (menu !== null) {
        element.append(menu);
      }
    });

    document.body.appendChild(element.root().node());
    element.show(true);

    target
      .element(element)
      .once('destroy', () => {
        element.show(false).on('end', () => {
          element.destroy();
          target.routes(false);

          menus.forEach((name) => {
            target
              .router()
              .target(name)
              .destroy();
          });
        });
      });
  }

  _menu(target) {
    const modifier = this._menuModifiers.get(target.name());

    let element = menuFactory()
      .position('left');

    element = modifier(element);

    const main = target
      .router()
      .target('main')
      .element();

    if (main !== null) {
      main.append(element);
    }

    target
      .element(element)
      .once('destroy', () => {
        element.destroy();
        target.routes(false);
      });
  }

  _close() {
    this.state('open', false);
  }

  _online() {
    if (this._ws) {
      this._ws.open();
    }
  }

  _open() {
    this.state('open', true);

    if (this._auth) {
      logIn(this);
    }
  }
}
<|endoftext|>


<commit_before>$.get( "https://api.github.com/repos/bros-bioinfo/bros-bioinfo.github.io/git/trees/master?recursive=1", function( data ) {
  var text = data;
  data.replace(/"path": (.+)/g);
  console.log(data);
});
<commit_msg>regex fix 1<commit_after>$.get( "https://api.github.com/repos/bros-bioinfo/bros-bioinfo.github.io/git/trees/master?recursive=1", function( data ) {
  var text = data;
  var text2 = text.match(/"path": (.+)/g);
  console.log(text2);
});
<|endoftext|>


<commit_before>/* Conway's Game of Life */

document.addEventListener("DOMContentLoaded", function () {
  window.gol = {

    // BASIC ATTRIBUTES =======================================================

    canvas: document.getElementById("gol"),
    ctx: document.getElementById("gol").getContext("2d"),

    fps: 10,

    idealCellSize: 20,
    cellSize: [20, 20], // This gets updated dynamically.

    boardSize: [10, 10],

    board: undefined,

    // HELPER FUNCTIONS =======================================================

    _getBlankBoard: function() {
      var array = [];
      for (var i=0; i<this.boardSize[0]; i++) {
        array.push(
          new Array(this.boardSize[1]).fill(false)
        );
      }
      return array;
    },

    // MAIN FUNCTIONS =========================================================

    // Called to update the game if the canvas size
    // changes.

    sizeChanged: function() {
      var width = gol.canvas.offsetWidth,
          height = gol.canvas.offsetHeight;
      // Update canvas coordinate system
      gol.canvas.setAttribute("width", width);
      gol.canvas.setAttribute("height", height);

      // Update tile size by finding a width that will
      // evenly fill the canvas and is closest to the
      // idealCellSize, then doing the same thing for
      // height.
      gol.cellSize = [
        width / Math.round(width / gol.idealCellSize),
        height / Math.round(height / gol.idealCellSize)
      ];

      // TODO: when board size changes, kill cells that
      // are cut off on resize, randomize new terrain.
      gol.boardSize = [
        width / gol.cellSize[0],
        height / gol.cellSize[1]
      ];
    },

    // Randomize the game state

    randomize: function() {
      var width = this.boardSize[0],
          height = this.boardSize[1];

      var cells = [];

      for (var x=0; x<width; x++) {
        cells.push([]);
        for (var y=0; y<height; y++) {
          cells[x].push(Math.random() < 0.125);
        }
      }
      this.board = cells;
    },

    // Render the board on the canvas

    redraw: function() {
      var width = this.canvas.getAttribute("width"),
          height = this.canvas.getAttribute("height");
      this.ctx.clearRect(0, 0, width, height);
      this.ctx.fillStyle = "#37474f"; // $background-blue

      // Render board
      for (var x=0; x<this.board.length; x++) {
        for (var y=0; y<this.board[x].length; y++) {
          if (this.board[x][y]) {
            this.ctx.fillRect(
              this.cellSize[0] * x,
              this.cellSize[1] * y,
              this.cellSize[0],
              this.cellSize[1]
            );
          }
        }
      }
    },

    step: function() {
      // TODO: Advance the simulation
    },

    // Begin the loop

    start: function() {
      gol.step();
      gol.redraw();
      setTimeout(gol.start, 1000 / gol.fps);
    },

    // Initialize and begin

    init: function() {
      // Calculate sizes
      this.sizeChanged();
      // Initialize board
      this.board = this._getBlankBoard();
      this.randomize();
      this.start();
    }
  };

  window.addEventListener("resize", gol.sizeChanged);
  gol.init();

});
<commit_msg>Track board size changes<commit_after>/* Conway's Game of Life */

document.addEventListener("DOMContentLoaded", function () {
  window.gol = {

    // BASIC ATTRIBUTES =======================================================

    canvas: document.getElementById("gol"),
    ctx: document.getElementById("gol").getContext("2d"),

    fps: 10,

    idealCellSize: 20,
    cellSize: [20, 20], // This gets updated dynamically.

    boardSize: [10, 10],

    board: undefined,

    // HELPER FUNCTIONS =======================================================

    _getBlankBoard: function() {
      var array = [];
      for (var i=0; i<this.boardSize[0]; i++) {
        array.push(
          new Array(this.boardSize[1]).fill(false)
        );
      }
      return array;
    },

    // MAIN FUNCTIONS =========================================================

    // Called to update the game if the canvas size
    // changes.

    sizeChanged: function() {
      var width = gol.canvas.offsetWidth,
          height = gol.canvas.offsetHeight;
      // Update canvas coordinate system
      gol.canvas.setAttribute("width", width);
      gol.canvas.setAttribute("height", height);

      // Update tile size by finding a width that will
      // evenly fill the canvas and is closest to the
      // idealCellSize, then doing the same thing for
      // height.
      gol.cellSize = [
        width / Math.round(width / gol.idealCellSize),
        height / Math.round(height / gol.idealCellSize)
      ];

      // When board size changes, kill cells that are
      // cut off and randomize new terrain.

      var oldBoardSize = gol.boardSize;  // Store old size
      gol.boardSize = [  // Adjust size
        Math.round(width / gol.cellSize[0]),
        Math.round(height / gol.cellSize[1])
      ];
      var diff = [  // Calculate size difference
        gol.boardSize[0] - oldBoardSize[0],
        gol.boardSize[1] - oldBoardSize[1]
      ];

      // Kill dead cells

      if (diff[0] < 0) {
        console.log("x shrunk by " + -diff[0]);
      }
      if (diff[1] < 0) {
        console.log("y shrunk by " + -diff[1]);
      }

      // Populate new cells
      if (diff[0] > 0) {
        console.log("x grew by " + diff[0]);
      }
      if (diff[1] > 0) {
        console.log("y grew by " + diff[1]);
      }
    },

    // Randomize the game state

    randomize: function() {
      var width = this.boardSize[0],
          height = this.boardSize[1];

      var cells = [];

      for (var x=0; x<width; x++) {
        cells.push([]);
        for (var y=0; y<height; y++) {
          cells[x].push(Math.random() < 0.125);
        }
      }
      this.board = cells;
    },

    // Render the board on the canvas

    redraw: function() {
      var width = this.canvas.getAttribute("width"),
          height = this.canvas.getAttribute("height");
      this.ctx.clearRect(0, 0, width, height);
      this.ctx.fillStyle = "#37474f"; // $background-blue

      // Render board
      for (var x=0; x<this.board.length; x++) {
        for (var y=0; y<this.board[x].length; y++) {
          if (this.board[x][y]) {
            this.ctx.fillRect(
              this.cellSize[0] * x,
              this.cellSize[1] * y,
              this.cellSize[0],
              this.cellSize[1]
            );
          }
        }
      }
    },

    step: function() {
      // TODO: Advance the simulation
    },

    // Begin the loop

    start: function() {
      gol.step();
      gol.redraw();
      setTimeout(gol.start, 1000 / gol.fps);
    },

    // Initialize and begin

    init: function() {
      // Calculate sizes
      this.sizeChanged();
      // Initialize board
      this.board = this._getBlankBoard();
      this.randomize();
      this.start();
    }
  };

  window.addEventListener("resize", gol.sizeChanged);
  gol.init();

});
<|endoftext|>


<commit_before>(function(){

  var margin = {top: 20, right: 20, bottom: 20, left: 20};
  var innerX = {top: 0, right: 50, bottom: 30, left: 80};
  var innerY = {top: 30, right: 80, bottom: 50, left: 30};

  d3.selection.prototype.moveToFront = function() {
    return this.each(function() {
      this.parentNode.appendChild(this);
    });
  };

  var containerWidth = document.getElementById('vis').offsetWidth;

  var width = Math.max(containerWidth, 768) - margin.left - margin.right,
      height = 468 - margin.top - margin.bottom;

  var parseYear = d3.time.format("%Y").parse;

  var innerXWidth = width - innerX.right - innerX.left;
  var x = d3.time.scale()
      .range([0, innerXWidth]);

  var innerYHeight = height - innerY.top - innerY.bottom;
  var y = d3.scale.linear()
      .domain([0, 100])
      .range([innerYHeight, 0]);

  var yAxis = d3.svg.axis()
      .scale(y)
      .tickSize(-width, 0, 0)
      .ticks(5)
      .tickFormat(function(d){ return d + '%'; })
      .orient("left");

  var xAxis = d3.svg.axis()
      .scale(x)
      .tickSize(-height + innerY.bottom, 0, 0)
      .tickPadding(6)
      .orient("top");

  var circleRadius = d3.scale.sqrt()
      .rangeRound([1, IFGVis.maxDotSize]);

  var connectionLine = d3.svg.line()
    .x(function(d) { return d.x; })
    .y(function(d) { return d.y; })
    .interpolate("basis")
    .defined(function(d){
      return d.defined;
    });

  var svg = d3.select("#vis").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom);

  var filter = svg.append('defs')
    .append('filter')
      .attr('id', 'highlight')
      .attr('x', '0')
      .attr('y', '0')
      .attr('width', '1')
      .attr('height', '1');

  filter.append('feFlood')
    .attr('flood-color', '#fff')
    .attr('result', 'out1');
  filter.append('feComposite')
    .attr('in', 'SourceGraphic')
    .attr('in2', 'out1')
    .attr('operator', 'over');

  svg = svg.append("g")
      .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

  svg.append("g")
    .attr("class", "y axis")
    .attr('transform', 'translate(' + innerY.left + ',' + innerY.top + ')')
    .call(yAxis);

  svg.select('.y.axis .major line').classed('bottomline', true);

  var activeGroups = 0;

  var activateGroup = function(key, hover) {
    return function(){
      var obj = groups[key];
      obj.group.moveToFront();
      svg.selectAll("." + key).style("fill", IFGVis.colors[key]).classed('active', true);
      obj.group.select('.line').style('display', 'block');
      if (stack[stack.length - 1] === key) {
        svg.select('#label')
          .text(IFGVis.labels[key])
          .style('fill', IFGVis.colors[key])
          .attr('transform', 'translate(' + (innerXWidth + innerX.left + 40) + ',' + (obj.labelpos + 12) + ')');
        svg.select('#label-triangle')
          .attr('transform', 'translate(' + (innerXWidth + innerX.left) + ',' + (obj.labelpos + 20) + ')');
        svg.selectAll('.label').style('display', 'block');
        obj.group.selectAll('.circle-number').style('display', 'block');
      } else {
        obj.group.selectAll('.circle-number').style('display', 'none');
      }
      activeInForeground();
    };
  };

  var permanentlyActivateGroup = function(key){
    return function(){
      var obj = groups[key];
      obj.isActive = !obj.isActive;
      if (obj.isActive) {
        activateGroup(key)();
      } else {
        deactivateGroup(key)();
      }
    };
  };

  var deactivateGroup = function(key) {
    return function() {
      var obj = groups[key];
      if (obj.isActive) { return; }
      obj.group.select('.line').style('display', 'none');
      obj.group.selectAll(".dot").style("fill", "").classed('active', false);
      obj.group.selectAll('.circle-number').style('display', 'none');
      refreshAllActiveGroups();
    };
  };

  var activeInForeground = function(){
    for (var key in groups){
      if (groups[key].isActive){
        groups[key].group.moveToFront();
      }
    }
    if (stack.length > 0) {
      groups[stack[stack.length - 1]].group.moveToFront();
    }
    svg.selectAll('.label').moveToFront();
  };

  var refreshAllActiveGroups = function(){
    for (var key in groups){
      if (groups[key].isActive){
        activateGroup(key)();
      }
    }
    activeInForeground();
  };

  var groups = {};

  var getLineData = function(groupData){
    var newData = [], d, rad, dist;
    for (var i = 0; i < groupData.length; i += 1){
      if (i < groupData.length - 1) {
        dist = x(groupData[1].year) - x(groupData[0].year);
        dist = Math.round((dist - 50) / 2);
      }
      rad = dist;
      if (i > 0){
        d = $.extend({}, groupData[i]);
        d.rad = rad;
        d.x = x(d.year) - rad;
        d.y = y(d.transparency);
        d.defined = true;
        newData.push(d);
      }
      d = $.extend({}, groupData[i]);
      d.x = x(d.year);
      d.y = y(d.transparency);
      d.defined = true;
      newData.push(d);
      if (i < groupData.length - 1) {
        d = $.extend({}, groupData[i]);
        d.x = x(d.year) + rad;
        d.y = y(d.transparency);
        d.defined = true;
        newData.push(d);
      }
    }

    return newData;
  };

  var makeTriangle = (function() {
    var t = d3.svg.symbol();
    t.size(100);
    return t;
  }());

  var makeGroup = function(key, groupData){
    var group = svg.append('g')
      .attr('transform', 'translate(' + innerX.left + ',' + innerY.top + ')')
      .attr('class', 'group ' + key);

    var connectionData = getLineData(groupData);

    group.append("svg:path")
        .attr('class', 'line')
        .style('stroke', IFGVis.colors[key])
        .style('display', 'none')
        .attr("d", connectionLine(connectionData));

    var groupSelect = group
      .selectAll("." + key)
      .data(groupData);

    var circleGroup = groupSelect
      .enter().append("g");
    circleGroup
      .append('circle')
      .attr("class", "dot " + key)
      .attr("r", function(d) {
        return circleRadius(d.count);
      })
      .attr("cx", function(d) { return x(d.year); })
      .attr("cy", function(d) { return y(d.transparency); });

    groupSelect.filter(function(d, i){
      return circleRadius(d.count) <= IFGVis.dotSizeNeedsHelp;
    }).append('circle')
      .attr("r", IFGVis.helpDotSize)
      .attr("class", "helpdot")
      .attr("cx", function(d) { return x(d.year); })
      .attr("cy", function(d) { return y(d.transparency); });

    circleGroup.append('path')
      .attr('d', makeTriangle.type('triangle-up')())
      .attr('class', 'triangle circle-number')
      .attr('transform', function(d){
        return 'translate(' + (x(d.year)) + ',' + (y(d.transparency) + 10) + ')';
      })
      .style('display', 'none');

    var t = circleGroup.append('text')
      .attr('class', 'circle-number highlight')
      .style('fill', IFGVis.colors[key])
      .attr('transform', function(d){
        return 'translate(' + (x(d.year)) + ',' + (y(d.transparency) + 26) + ')';
      })
      .style('display', 'none')
      .attr('text-anchor', 'middle');

    t.append('tspan')
      .attr('x', 0)
      .text(function(d){
          return d.transparency + '%';
      });
    t.append('tspan')
      .attr('x', 0)
      .attr('dy', 15)
      .text(function(d){
          return 'von ' + d.count;
      });
    t.append('tspan')
      .attr('x', 0)
      .attr('dy', 15)
      .text(function(d){
        return d.count === 1 ? 'Antrag' : 'Anträgen';
      });
    t.append('tspan')
      .attr('x', 0)
      .attr('dy', 15)
      .text('bewilligt');

    group.data(groupData)
      .on("mouseover", activateGroup(key, true))
      .on("mouseout", deactivateGroup(key))
      .on("touch", navigateToKey(key))
      .on("click", navigateToKey(key));

    var lastBubble = groupData[groupData.length - 1];
    var labelpos = y(lastBubble.transparency);

    return {
      labelpos: labelpos,
      group: group,
      isActive: false
    };
  };

  var dataLoaded = function(error, data) {
    data.forEach(function(d) {
      d.year = parseYear(d.year);
      d.count = parseInt(d.count, 10);
      d.transparency = parseInt(d.transparency, 10);
    });
    data = data.filter(function(d){
      return d.count > 0;
    })
    .sort(function(a, b){
      return a.year - b.year;
    });

    x.domain(d3.extent(data, function(d) { return d.year; }));

    svg.append("g")
      .attr("class", "x axis")
      .attr('transform', 'translate(' + innerX.left + ',' + innerX.top + ')')
      .call(xAxis);

    svg.append('text')
      .attr('text-anchor', 'end')
      .attr('transform', 'translate(' + (innerXWidth) + ',' + (innerY.top) + ')')
      .attr('class', 'highlight label')
      .attr('id', 'label');

    svg.append('path')
      .attr('id', 'label-triangle')
      .attr('d', makeTriangle.type('triangle-down')())
      .attr('class', 'triangle label')
      .style('display', 'none');

    circleRadius.domain(d3.extent(data, function(d) { return d.count; }));

    var filterFunc = function(key){
      return function(d){ return d.name === key; };
    };

    for (var key in IFGVis.colors) {
      groups[key] = makeGroup(key, data.filter(filterFunc(key)));
    }

    init();
  };

  var initial = true, stack = [];

  var WorkspaceRouter = Backbone.Router.extend({
    routes: {
      "*args": "show"
    },

    home: function(){

    },

    show: function(args) {
      if (initial && args === "") {
        router.navigate(IFGVis.defaultInstitution, {trigger: true});
        initial = false;
        return;
      }
      initial = false;
      args = args.split('&');
      $('.label').hide();
      $('input').prop('checked', false);
      for (var key in groups){
        groups[key].isActive = false;
        deactivateGroup(key)();
      }
      activeGroups = 0;
      stack = [];
      for (var i = 0; i < args.length; i += 1) {
        if (groups[args[i]] !== undefined) {
          stack.push(args[i]);
          $('input[value="' + args[i] + '"]').prop('checked', true);
          activeGroups += 1;
          permanentlyActivateGroup(args[i])();
        }
      }
      refreshAllActiveGroups();
    }

  });

  var init = function(){
    Backbone.history.start();
  };

  var router = new WorkspaceRouter();

  var navigateToKey = function(key){
    return function(){
      var checked = $('input[value="' + key + '"]').prop('checked');
      $('input[value="' + key + '"]').prop('checked', !checked);
      toggleOnStack(key, !checked);
      updateNav();
    };
  };

  var toggleOnStack = function(key, add){
    if (add) {
      stack.push(key);
    } else {
      stack = stack.filter(function(el){
        return el !== key;
      });
    }
  };

  var updateNav = function(){
    router.navigate(stack.join('&'), {trigger: true});
  };

  $(function(){
    $('#auswahl-button').on('click touchstart', function(e){
      e.preventDefault();
      $('#auswahl').slideToggle();
    });
    $('#choose-all').on('click touchstart', function(e){
      e.preventDefault();
      $('.auswahl-liste input').prop('checked', true);
      stack = [];
      $('.auswahl-liste input').each(function(i, el){
        stack.push($(el).val());
      });
      updateNav();
    });
    $('#choose-none').on('click touchstart', function(e){
      e.preventDefault();
      $('.auswahl-liste input').prop('checked', false);
      stack = [];
      updateNav();
    });
    $('.auswahl-liste input').change(function(e){
      toggleOnStack($(this).val(), $(this).prop('checked'));
      updateNav();
    });
    $('.close').on('click touchstart', function(e){
      e.preventDefault();
      $('#auswahl').slideUp();
    });
  });

  dataLoaded(null, IFGVis.data);
  // d3.csv("data.csv", dataLoaded);

}());
<commit_msg>Sort circles by size, move out of group<commit_after>(function(){

  var margin = {top: 20, right: 20, bottom: 20, left: 20};
  var innerX = {top: 0, right: 50, bottom: 30, left: 80};
  var innerY = {top: 30, right: 80, bottom: 50, left: 30};

  d3.selection.prototype.moveToFront = function() {
    return this.each(function() {
      this.parentNode.appendChild(this);
    });
  };

  var containerWidth = document.getElementById('vis').offsetWidth;

  var width = Math.max(containerWidth, 768) - margin.left - margin.right,
      height = 468 - margin.top - margin.bottom;

  var parseYear = d3.time.format("%Y").parse;

  var innerXWidth = width - innerX.right - innerX.left;
  var x = d3.time.scale()
      .range([0, innerXWidth]);

  var innerYHeight = height - innerY.top - innerY.bottom;
  var y = d3.scale.linear()
      .domain([0, 100])
      .range([innerYHeight, 0]);

  var yAxis = d3.svg.axis()
      .scale(y)
      .tickSize(-width, 0, 0)
      .ticks(5)
      .tickFormat(function(d){ return d + '%'; })
      .orient("left");

  var xAxis = d3.svg.axis()
      .scale(x)
      .tickSize(-height + innerY.bottom, 0, 0)
      .tickPadding(6)
      .orient("top");

  var circleRadius = d3.scale.sqrt()
      .rangeRound([1, IFGVis.maxDotSize]);

  var connectionLine = d3.svg.line()
    .x(function(d) { return d.x; })
    .y(function(d) { return d.y; })
    .interpolate("basis")
    .defined(function(d){
      return d.defined;
    });

  var svg = d3.select("#vis").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom);

  var filter = svg.append('defs')
    .append('filter')
      .attr('id', 'highlight')
      .attr('x', '0')
      .attr('y', '0')
      .attr('width', '1')
      .attr('height', '1');

  filter.append('feFlood')
    .attr('flood-color', '#fff')
    .attr('result', 'out1');
  filter.append('feComposite')
    .attr('in', 'SourceGraphic')
    .attr('in2', 'out1')
    .attr('operator', 'over');

  svg = svg.append("g")
      .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

  svg.append("g")
    .attr("class", "y axis")
    .attr('transform', 'translate(' + innerY.left + ',' + innerY.top + ')')
    .call(yAxis);

  svg.select('.y.axis .major line').classed('bottomline', true);

  var activeGroups = 0;

  var activateGroup = function(key, hover) {
    return function(){
      var obj = groups[key];
      obj.group.moveToFront();
      svg.selectAll("." + key).style("fill", IFGVis.colors[key]).classed('active', true);
      obj.group.select('.line').style('display', 'block');
      if (stack[stack.length - 1] === key) {
        svg.select('#label')
          .text(IFGVis.labels[key])
          .style('fill', IFGVis.colors[key])
          .attr('transform', 'translate(' + (innerXWidth + innerX.left + 40) + ',' + (obj.labelpos + 12) + ')');
        svg.select('#label-triangle')
          .attr('transform', 'translate(' + (innerXWidth + innerX.left) + ',' + (obj.labelpos + 20) + ')');
        svg.selectAll('.label').style('display', 'block');
        obj.group.selectAll('.circle-number').style('display', 'block');
      } else {
        obj.group.selectAll('.circle-number').style('display', 'none');
      }
      activeInForeground();
    };
  };

  var permanentlyActivateGroup = function(key){
    return function(){
      var obj = groups[key];
      obj.isActive = !obj.isActive;
      if (obj.isActive) {
        activateGroup(key)();
      } else {
        deactivateGroup(key)();
      }
    };
  };

  var deactivateGroup = function(key) {
    return function() {
      var obj = groups[key];
      if (obj.isActive) { return; }
      obj.group.select('.line').style('display', 'none');
      svg.selectAll(".dot").style("fill", "").classed('active', false);
      obj.group.selectAll('.circle-number').style('display', 'none');
      refreshAllActiveGroups();
    };
  };

  var activeInForeground = function(){
    for (var key in groups){
      if (groups[key].isActive){
        groups[key].group.moveToFront();
      }
    }
    if (stack.length > 0) {
      groups[stack[stack.length - 1]].group.moveToFront();
    }
    svg.selectAll('.label').moveToFront();
  };

  var refreshAllActiveGroups = function(){
    for (var key in groups){
      if (groups[key].isActive){
        activateGroup(key)();
      }
    }
    activeInForeground();
  };

  var groups = {};

  var getLineData = function(groupData){
    var newData = [], d, rad, dist;
    for (var i = 0; i < groupData.length; i += 1){
      if (i < groupData.length - 1) {
        dist = x(groupData[1].year) - x(groupData[0].year);
        dist = Math.round((dist - 50) / 2);
      }
      rad = dist;
      if (i > 0){
        d = $.extend({}, groupData[i]);
        d.rad = rad;
        d.x = x(d.year) - rad;
        d.y = y(d.transparency);
        d.defined = true;
        newData.push(d);
      }
      d = $.extend({}, groupData[i]);
      d.x = x(d.year);
      d.y = y(d.transparency);
      d.defined = true;
      newData.push(d);
      if (i < groupData.length - 1) {
        d = $.extend({}, groupData[i]);
        d.x = x(d.year) + rad;
        d.y = y(d.transparency);
        d.defined = true;
        newData.push(d);
      }
    }

    return newData;
  };

  var makeTriangle = (function() {
    var t = d3.svg.symbol();
    t.size(100);
    return t;
  }());

  var makeGroup = function(key, groupData){
    var group = svg.append('g')
      .attr('transform', 'translate(' + innerX.left + ',' + innerY.top + ')')
      .attr('class', 'group ' + key);

    var connectionData = getLineData(groupData);

    group.append("svg:path")
        .attr('class', 'line')
        .style('stroke', IFGVis.colors[key])
        .style('display', 'none')
        .attr("d", connectionLine(connectionData));

    var groupSelect = group
      .selectAll("." + key)
      .data(groupData);

    var circleGroup = groupSelect
      .enter().append("g");

    circleGroup.append('path')
      .attr('d', makeTriangle.type('triangle-up')())
      .attr('class', 'triangle circle-number')
      .attr('transform', function(d){
        return 'translate(' + (x(d.year)) + ',' + (y(d.transparency) + 10) + ')';
      })
      .style('display', 'none');

    var t = circleGroup.append('text')
      .attr('class', 'circle-number highlight')
      .style('fill', IFGVis.colors[key])
      .attr('transform', function(d){
        return 'translate(' + (x(d.year)) + ',' + (y(d.transparency) + 26) + ')';
      })
      .style('display', 'none')
      .attr('text-anchor', 'middle');

    t.append('tspan')
      .attr('x', 0)
      .text(function(d){
          return d.transparency + '%';
      });
    t.append('tspan')
      .attr('x', 0)
      .attr('dy', 15)
      .text(function(d){
          return 'von ' + d.count;
      });
    t.append('tspan')
      .attr('x', 0)
      .attr('dy', 15)
      .text(function(d){
        return d.count === 1 ? 'Antrag' : 'Anträgen';
      });
    t.append('tspan')
      .attr('x', 0)
      .attr('dy', 15)
      .text('bewilligt');

    group.data(groupData)
      .on("mouseover", activateGroup(key, true))
      .on("mouseout", deactivateGroup(key))
      .on("touch", navigateToKey(key))
      .on("click", navigateToKey(key));

    var lastBubble = groupData[groupData.length - 1];
    var labelpos = y(lastBubble.transparency);

    return {
      labelpos: labelpos,
      group: group,
      isActive: false
    };
  };

  var dataLoaded = function(error, data) {
    data.forEach(function(d) {
      d.year = parseYear(d.year);
      d.count = parseInt(d.count, 10);
      d.transparency = parseInt(d.transparency, 10);
    });
    data = data.filter(function(d){
      return d.count > 0;
    })
    .sort(function(a, b){
      return a.year - b.year;
    });

    x.domain(d3.extent(data, function(d) { return d.year; }));

    svg.append("g")
      .attr("class", "x axis")
      .attr('transform', 'translate(' + innerX.left + ',' + innerX.top + ')')
      .call(xAxis);

    svg.append('text')
      .attr('text-anchor', 'end')
      .attr('transform', 'translate(' + (innerXWidth) + ',' + (innerY.top) + ')')
      .attr('class', 'highlight label')
      .attr('id', 'label');

    svg.append('path')
      .attr('id', 'label-triangle')
      .attr('d', makeTriangle.type('triangle-down')())
      .attr('class', 'triangle label')
      .style('display', 'none');

    circleRadius.domain(d3.extent(data, function(d) { return d.count; }));

    var filterFunc = function(key){
      return function(d){ return d.name === key; };
    };

    // Add Circles independent from group
    var circleData = data.slice();
    circleData.sort(function(a, b){
      return b.count - a.count;
    });
    svg.selectAll('.dot')
      .data(circleData)
      .enter()
      .append('circle')
      .attr("class", function(d){
        return "dot circle " + d.name;
      })
      .attr("r", function(d) {
        return circleRadius(d.count);
      });

    var helpCircleData = circleData.slice().filter(function(d, i){
      return circleRadius(d.count) <= IFGVis.dotSizeNeedsHelp;
    });
    svg.selectAll('.helpdot')
      .data(helpCircleData)
      .enter()
      .append('circle')
      .attr("r", IFGVis.helpDotSize)
      .attr("class", "helpdot circle");

    svg.selectAll('.circle')
      .attr('transform', 'translate(' + innerX.left + ',' + innerY.top + ')')
      .attr("cx", function(d) { return x(d.year); })
      .attr("cy", function(d) { return y(d.transparency); })
      .on("mouseover", function(d){
        activateGroup(d.name, true)();
      })
      .on("mouseout", function(d){
        deactivateGroup(d.name)();
      })
      .on("touch", function(d){
        navigateToKey(d.name)();
      })
      .on("click", function(d){
        navigateToKey(d.name)();
      });

    for (var key in IFGVis.colors) {
      groups[key] = makeGroup(key, data.filter(filterFunc(key)));
    }

    init();
  };

  var initial = true, stack = [];

  var WorkspaceRouter = Backbone.Router.extend({
    routes: {
      "*args": "show"
    },

    home: function(){

    },

    show: function(args) {
      if (initial && args === "") {
        router.navigate(IFGVis.defaultInstitution, {trigger: true});
        initial = false;
        return;
      }
      initial = false;
      args = args.split('&');
      $('.label').hide();
      $('input').prop('checked', false);
      for (var key in groups){
        groups[key].isActive = false;
        deactivateGroup(key)();
      }
      activeGroups = 0;
      stack = [];
      for (var i = 0; i < args.length; i += 1) {
        if (groups[args[i]] !== undefined) {
          stack.push(args[i]);
          $('input[value="' + args[i] + '"]').prop('checked', true);
          activeGroups += 1;
          permanentlyActivateGroup(args[i])();
        }
      }
      refreshAllActiveGroups();
    }

  });

  var init = function(){
    Backbone.history.start();
  };

  var router = new WorkspaceRouter();

  var navigateToKey = function(key){
    return function(){
      var checked = $('input[value="' + key + '"]').prop('checked');
      $('input[value="' + key + '"]').prop('checked', !checked);
      toggleOnStack(key, !checked);
      updateNav();
    };
  };

  var toggleOnStack = function(key, add){
    if (add) {
      stack.push(key);
    } else {
      stack = stack.filter(function(el){
        return el !== key;
      });
    }
  };

  var updateNav = function(){
    router.navigate(stack.join('&'), {trigger: true});
  };

  $(function(){
    $('#auswahl-button').on('click touchstart', function(e){
      e.preventDefault();
      $('#auswahl').slideToggle();
    });
    $('#choose-all').on('click touchstart', function(e){
      e.preventDefault();
      $('.auswahl-liste input').prop('checked', true);
      stack = [];
      $('.auswahl-liste input').each(function(i, el){
        stack.push($(el).val());
      });
      updateNav();
    });
    $('#choose-none').on('click touchstart', function(e){
      e.preventDefault();
      $('.auswahl-liste input').prop('checked', false);
      stack = [];
      updateNav();
    });
    $('.auswahl-liste input').change(function(e){
      toggleOnStack($(this).val(), $(this).prop('checked'));
      updateNav();
    });
    $('.close').on('click touchstart', function(e){
      e.preventDefault();
      $('#auswahl').slideUp();
    });
  });

  dataLoaded(null, IFGVis.data);
  // d3.csv("data.csv", dataLoaded);

}());
<|endoftext|>


<commit_before>// kkk.js
var nrTempEnd = false;
var neighborsTemp = [];
var racksTemp = [];
var isMap = false;
var wpid = -1;
$(function(){

	$( "#day" ).click(function() {
		setDay();
	});

	$( "#day-today" ).click(function() {
		setToday();
	});

	$( "#day-tomorrow" ).click(function() {
		setTomorrow();
	});

	$( "#time" ).click(function() {
		var temp = ($(this).text().substr(0,2)*1 +1)%24;
		$("#time").text($( "#time-"+temp ).text());
	});

	for(var i = 0; i < 24; i++){
		var temp = i;
		$( "#time-"+temp ).click(function() {
			$( "#time" ).text($(this).text());
	});
	}

	$( "#btn-findmap" ).click(function() {

		resetDrop();
		initReserveView();
	});

	$( "#btn-back" ).click(function() {
		//setButtons();
		initReserveView();
	});

	$( "#btn-lastRackHistory" ).click(function() {
		initReserveView();

		if(!(window.localStorage.getItem('lastRackHistory') == "" ||
			window.localStorage.getItem('lastRackHistory') == null)){
			// these functions are in googlemap.js
			showRackState(window.localStorage.getItem('lastRackHistory'));
			oneRackOnMap(window.localStorage.getItem('lastRackHistory'));
		}
	});

	$( "#btn-nearestRack" ).click(function() {
		initReserveView();
		racksTemp = [];
		neighborsTemp = [];
		nrTempEnd = false;
		jQuery.get('/racks', function(response) {
		    for(var i = 0; i < response.data.length; i++){
		    	racksTemp.push(response.data[i].rid);
		    	neighborsTemp.push(new google.maps.LatLng(response.data[i].latitude, response.data[i].longitude));
		    }
		    nrTempEnd = true;
	  	});

	  	wpid = navigator.geolocation.watchPosition(geo_success, geo_error, geo_options);
	});

	$( "#btn-reserve" ).click(function() {
		if (currentRid == -1) {
			console.log("rid error");
			return false;
		}

		$.post('/bicycle/reserve',
		{
			'rid' : ''+currentRid
		},
		function(response) {
			// Success!
			window.localStorage.setItem('lastRackHistory', currentRid);
			//location.href = '/reservation';
			showRackState(currentRid);
		}, 'json')
		.fail(function(jqxhr) {
				// Fail.
				alert(jqxhr.responseJSON.data);
		});

		return false;
	});

	if(window.localStorage.getItem('lastRackHistory') == "" ||
		window.localStorage.getItem('lastRackHistory') == null ){
		$( "#btn-lastRackHistory").addClass("disabled");
	} else {
		$( "#btn-lastRackHistory").removeClass("disabled");
	}

});

var dayByday = true;
var time = 0;

function setButtons(){

	if(isMap){

		$("#btn-back").css("visibility","hidden");
		$("#map-canvas").css("visibility","hidden");
		$("#div-time").css("visibility", "hidden");
		$("#div-day").css("visibility", "hidden");
		$("#div-probar").css("visibility", "hidden");
		$("#btn-reserve").css("visibility", "hidden");

		$(".span6 .btn-racksearch-menu").css("display", "inline");
	} else {

		$("#btn-back").css("visibility","visible");
		$("#map-canvas").css("visibility","visible");
		$("#div-time").css("visibility", "visible");
		$("#div-day").css("visibility", "visible");
		$("#div-probar").css("visibility", "visible");
		$("#btn-reserve").css("visibility", "visible");
		// this function is in googlemap.js
		//resetDrop();
		$(".span6 .btn-racksearch-menu").css("display", "none");

	}

	isMap = !isMap;

}

function setDay(){
	if(dayByday){
		$( "#day" ).text("Tomorrow");
	}else{
		$( "#day" ).text("Today");
	}

	dayByday = !dayByday;
}

function setToday(){
	$( "#day" ).text("Today");
	dayByday = true;
}

function setTomorrow(){
	$( "#day" ).text("Tomorrow");
	dayByday = false;
}

function initReserveView(){
	if(wpid > 0){
		navigator.geolocation.clearWatch(wpid);
		wpid = -1;
	}

	$( "#btn-reserve").addClass("disabled");
	$( "#bar-free").width("0%");
	$( "#bar-rest").width("0%");
	$("#locationInfo").text("");
	currentRid = -1;
	if (gBrowser.mobile) {
		setButtons();
	}
}

function clickResereBtn(){

}

function nearestNeighborhood(latit, longi){
	if(nrTempEnd === true){
		var currentLocation = new google.maps.LatLng(latit, longi);

		var minValue = calcDistance(currentLocation, neighborsTemp[0]);
		var minIndex = 0;

		for(var i = 1; i < neighborsTemp.length; i++) {
			var result = calcDistance(currentLocation, neighborsTemp[i]);

			if(minValue > result){
				minValue = result;
				minIndex = i;
			}
		}

		return racksTemp[minIndex];
	}

	return -1;

}

function calcDistance(p1, p2){
	//return (google.maps.geometry.spherical.computeDistanceBetween(p1, p2) / 1000).toFixed(2);
	return google.maps.geometry.spherical.computeDistanceBetween(p1, p2);
}

function geo_success(position) {

	var minRackId = nearestNeighborhood(position.coords.latitude, position.coords.longitude);
	if(minRackId > -1){
		showRackState(minRackId);
		oneRackOnMap(minRackId);
	}

}

function geo_error() {
	alert("위치 정보를 사용할 수 없습니다.");
}

var geo_options = {
	enableHighAccuracy: true,
	maximumAge        : 70000,
	timeout           : 30000
};

function geo_success_now(latit, longi) {
	var nTemp = [];
	var rTemp = [];
	jQuery.get('/racks', function(response) {
	    for(var i = 0; i < response.data.length; i++){
	    	rTemp.push(response.data[i].rid);
	    	nTemp.push(new google.maps.LatLng(response.data[i].latitude, response.data[i].longitude));
	    }

	    var currentLocation = new google.maps.LatLng(latit, longi);

		var minValue = calcDistance(currentLocation, nTemp[0]);
		var minIndex = 0;

		for(var i = 1; i < nTemp.length; i++) {
			var result = calcDistance(currentLocation, nTemp[i]);

			if(minValue > result){
				minValue = result;
				minIndex = i;
			}
		}

		currentRid = rTemp[minIndex];
		console.log(nTemp);
		console.log(rTemp);
		console.log(currentLocation);
		console.log(currentRid);
		$( "#btn-reserve" ).click();

  	});

}<commit_msg>Revolution<commit_after>// kkk.js
var nrTempEnd = false;
var neighborsTemp = [];
var racksTemp = [];
var isMap = false;
var wpid = -1;
$(function(){

	$( "#day" ).click(function() {
		setDay();
	});

	$( "#day-today" ).click(function() {
		setToday();
	});

	$( "#day-tomorrow" ).click(function() {
		setTomorrow();
	});

	$( "#time" ).click(function() {
		var temp = ($(this).text().substr(0,2)*1 +1)%24;
		$("#time").text($( "#time-"+temp ).text());
	});

	for(var i = 0; i < 24; i++){
		var temp = i;
		$( "#time-"+temp ).click(function() {
			$( "#time" ).text($(this).text());
	});
	}

	$( "#btn-findmap" ).click(function() {

		resetDrop();
		initReserveView();
	});

	$( "#btn-back" ).click(function() {
		//setButtons();
		initReserveView();
	});

	$( "#btn-lastRackHistory" ).click(function() {
		initReserveView();

		if(!(window.localStorage.getItem('lastRackHistory') == "" ||
			window.localStorage.getItem('lastRackHistory') == null)){
			// these functions are in googlemap.js
			showRackState(window.localStorage.getItem('lastRackHistory'));
			oneRackOnMap(window.localStorage.getItem('lastRackHistory'));
		}
	});

	$( "#btn-nearestRack" ).click(function() {
		initReserveView();
		racksTemp = [];
		neighborsTemp = [];
		nrTempEnd = false;
		jQuery.get('/racks', function(response) {
		    for(var i = 0; i < response.data.length; i++){
		    	racksTemp.push(response.data[i].rid);
		    	neighborsTemp.push(new google.maps.LatLng(response.data[i].latitude, response.data[i].longitude));
		    }
		    nrTempEnd = true;
	  	});

	  	wpid = navigator.geolocation.watchPosition(geo_success, geo_error, geo_options);
	});

	$( "#btn-reserve" ).click(function() {
		console.log("start");
		if (currentRid == -1) {
			console.log("rid error");
			return false;
		}
		console.log(currentRid);
		$.post('/bicycle/reserve',
		{
			'rid' : ''+currentRid
		},
		function(response) {
			// Success!
			window.localStorage.setItem('lastRackHistory', currentRid);
			//location.href = '/reservation';
			showRackState(currentRid);
		}, 'json')
		.fail(function(jqxhr) {
				// Fail.
				alert(jqxhr.responseJSON.data);
		});

		return false;
	});

	if(window.localStorage.getItem('lastRackHistory') == "" ||
		window.localStorage.getItem('lastRackHistory') == null ){
		$( "#btn-lastRackHistory").addClass("disabled");
	} else {
		$( "#btn-lastRackHistory").removeClass("disabled");
	}

});

var dayByday = true;
var time = 0;

function setButtons(){

	if(isMap){

		$("#btn-back").css("visibility","hidden");
		$("#map-canvas").css("visibility","hidden");
		$("#div-time").css("visibility", "hidden");
		$("#div-day").css("visibility", "hidden");
		$("#div-probar").css("visibility", "hidden");
		$("#btn-reserve").css("visibility", "hidden");

		$(".span6 .btn-racksearch-menu").css("display", "inline");
	} else {

		$("#btn-back").css("visibility","visible");
		$("#map-canvas").css("visibility","visible");
		$("#div-time").css("visibility", "visible");
		$("#div-day").css("visibility", "visible");
		$("#div-probar").css("visibility", "visible");
		$("#btn-reserve").css("visibility", "visible");
		// this function is in googlemap.js
		//resetDrop();
		$(".span6 .btn-racksearch-menu").css("display", "none");

	}

	isMap = !isMap;

}

function setDay(){
	if(dayByday){
		$( "#day" ).text("Tomorrow");
	}else{
		$( "#day" ).text("Today");
	}

	dayByday = !dayByday;
}

function setToday(){
	$( "#day" ).text("Today");
	dayByday = true;
}

function setTomorrow(){
	$( "#day" ).text("Tomorrow");
	dayByday = false;
}

function initReserveView(){
	if(wpid > 0){
		navigator.geolocation.clearWatch(wpid);
		wpid = -1;
	}

	$( "#btn-reserve").addClass("disabled");
	$( "#bar-free").width("0%");
	$( "#bar-rest").width("0%");
	$("#locationInfo").text("");
	currentRid = -1;
	if (gBrowser.mobile) {
		setButtons();
	}
}

function clickResereBtn(){

}

function nearestNeighborhood(latit, longi){
	if(nrTempEnd === true){
		var currentLocation = new google.maps.LatLng(latit, longi);

		var minValue = calcDistance(currentLocation, neighborsTemp[0]);
		var minIndex = 0;

		for(var i = 1; i < neighborsTemp.length; i++) {
			var result = calcDistance(currentLocation, neighborsTemp[i]);

			if(minValue > result){
				minValue = result;
				minIndex = i;
			}
		}

		return racksTemp[minIndex];
	}

	return -1;

}

function calcDistance(p1, p2){
	//return (google.maps.geometry.spherical.computeDistanceBetween(p1, p2) / 1000).toFixed(2);
	return google.maps.geometry.spherical.computeDistanceBetween(p1, p2);
}

function geo_success(position) {

	var minRackId = nearestNeighborhood(position.coords.latitude, position.coords.longitude);
	if(minRackId > -1){
		showRackState(minRackId);
		oneRackOnMap(minRackId);
	}

}

function geo_error() {
	alert("위치 정보를 사용할 수 없습니다.");
}

var geo_options = {
	enableHighAccuracy: true,
	maximumAge        : 70000,
	timeout           : 30000
};

function geo_success_now(latit, longi) {
	var nTemp = [];
	var rTemp = [];
	jQuery.get('/racks', function(response) {
	    for(var i = 0; i < response.data.length; i++){
	    	rTemp.push(response.data[i].rid);
	    	nTemp.push(new google.maps.LatLng(response.data[i].latitude, response.data[i].longitude));
	    }

	    var currentLocation = new google.maps.LatLng(latit, longi);

		var minValue = calcDistance(currentLocation, nTemp[0]);
		var minIndex = 0;

		for(var i = 1; i < nTemp.length; i++) {
			var result = calcDistance(currentLocation, nTemp[i]);

			if(minValue > result){
				minValue = result;
				minIndex = i;
			}
		}

		currentRid = rTemp[minIndex];

		$( "#btn-reserve" ).click();

  	});

}<|endoftext|>


<commit_before>(function($) {
    var map = null;
    var mapReady = false;
    var settings = null;
    var mapDefaults = null;;
    var markerCluster = null;
    var checkinAfterInit = false;
    var since = null;
    var icon = null;
    var myIcon = null;
    var cookieName = 'ae_checkin_location';
    var openwindow = null;

    window.aeMapReady = function() {
        mapReady = true;
        aeFetchLocations();
    }

    $(function() {
        $('body').on('click', '[data-ae-close]', function(e) {
            e.preventDefault();
            $('.ae_modal').hide();
        });
    });

    function aeDoCheckin() {
        $('#ae_login').hide();
        $('#ae_checkin').hide();
        $('#ae_thanks').show();
        var center = map.getCenter();
        $.ajax({
            url: settings.base_url + 'ae/v1/checkin',
            method: 'POST',
            headers: {'x-wp-nonce':settings.nonce},
            data: {
                lat: center.lat(),
                lon: center.lng(),
                content: aeGetCheckinText(),
                status: 'publish',
            }
        }).done(function (response) {
            aePollLocations();
        });
    }

    // TODO: serialize the whole form
    function aeGetCheckinText() {
        return $('#ae_checkin form input[name="content"]').val();
    }

    function aeSetCheckinText(text) {
        return $('#ae_checkin form input[name="content"]').val(text || '');
    }

    window.aeSettings = function (_settings) {
        settings = _settings;
        icon = settings.marker ? new google.maps.MarkerImage(settings.marker.url,
            new google.maps.Size(settings.marker.width, settings.marker.height),
            new google.maps.Point(0, 0),
            new google.maps.Point(settings.marker.vertexX, settings.marker.vertexY)
        ) : null;
        myIcon = settings.my_marker ? new google.maps.MarkerImage(settings.my_marker.url,
            new google.maps.Size(settings.my_marker.width, settings.my_marker.height),
            new google.maps.Point(0, 0),
            new google.maps.Point(settings.my_marker.vertexX, settings.my_marker.vertexY)
        ) : null;
        var handleCheckin = function(evt) {
            evt.preventDefault();
            if (settings.loggedin) {
                aeDoCheckin();
            } else {
                var center = map.getCenter();
                document.cookie = cookieName + '=' + escape(JSON.stringify({
                    lat: center.lat(),
                    lng: center.lng(),
                    zoom: map.getZoom(),
                    checkinText: aeGetCheckinText(),
                })) + ';path=/'
                $('#ae_login').show();
                $('#ae_checkin').hide();
            }
        };
        $('#ae_checkin a[data-checkin]').click(handleCheckin);
        $('#ae_checkin form[data-checkin]').submit(handleCheckin);
        aeFetchLocations();
    }

    if ("geolocation" in navigator) {
        navigator.geolocation.getCurrentPosition(function(position) {
            var center = {
                lat: position.coords.latitude,
                lng: position.coords.longitude
            };
            var zoom = 15;
            if (!mapDefaults) {
                if (map) {
                    map.panTo(center);
                    map.setZoom(zoom);
                } else {
                    mapDefaults = {
                        zoom: zoom,
                        center: center,
                    };
                }
            }
        });
    }

    function aePollLocations() {
        var separator = settings.base_url.indexOf('?') === -1 ? '?' : '&';
        $.ajax({
            url: settings.base_url + 'ae/v1/checkin' + separator + 'since=' + (since || ''),
            headers: {'x-wp-nonce':settings.nonce},
        }).done(function (response) {
            since = response.since;
            $('.ae-count').text(response.count);
            aeAddLocations(response.results);
        });
    }

    function aeFetchLocations() {
        if (!settings || !mapReady) {
            return;
        }
        if (document.cookie) {
            var key = cookieName + '=';
            var cookie = document.cookie;
            var start = cookie.indexOf(key);
            if (start !== -1) {
                var end = cookie.indexOf(';', start);
                if (end === -1) {
                    end = cookie.length;
                }
                try {
                    var cookieData = JSON.parse(unescape(cookie.substr(start + key.length, end - start - key.length)));
                    mapDefaults = {
                        zoom: parseFloat(cookieData.zoom),
                        center: {lat: cookieData.lat, lng: cookieData.lng},
                    };
                    aeSetCheckinText(cookieData.checkinText);
                    if (settings.loggedin) {
                        checkinAfterInit = true;
                    }
                } catch (e) {
                }
                document.cookie = cookieName + '=;expires=Thu, 01 Jan 1970 00:00:01 GMT;path=/'
            }
        }
        $.ajax({
            url: settings.base_url + 'ae/v1/checkin',
            headers: {'x-wp-nonce':settings.nonce},
        }).done(function (response) {
            since = response.since;
            aeInitMap(response.results);
        });
        setInterval(aePollLocations, 30000);
    };

    function aeAddLocations(locations) {
        markerCluster.addMarkers(locations.map(function(post) {
            var infowindow;
            if (settings.checkin_html) {
                var post_content = $('<div>').text(post.post_content || '').html();
                var html = settings.checkin_html.replace(/\[ae-checkin-text\]/g, post_content);
                if (html) {
                    infowindow  = new google.maps.InfoWindow({
                        content: html,
                    });
                }
            }
            var marker = new google.maps.Marker({
                position: {
                    lat: post.lat,
                    lng: post.lng,
                },
                icon: post.current_user ? myIcon : icon,
            });
            google.maps.event.addListener(marker, 'click', function() {
                if (infowindow) {
                    infowindow.open(map, marker);
                }
                if (openwindow) {
                    openwindow.close();
                }
                if (openwindow === infowindow) {
                    openwindow = null;
                } else {
                    openwindow = infowindow;
                }
            });
            return marker;
        }));
    }
    function aeInitMap(locations) {
        var options = mapDefaults || {
            streetViewControl: false,
            zoom: 4,
            center: {lat: -35.376184, lng: -63.998128},
        };
        options.styles = settings.styles;
        map = new google.maps.Map(document.getElementById('ae_map'), options);
        markerCluster = new MarkerClusterer(map, [], settings.cluster_options);
        aeAddLocations(locations);
        if (checkinAfterInit) {
            aeDoCheckin();
        }
    }
})(jQuery);
<commit_msg>remove satellite option<commit_after>(function($) {
    var map = null;
    var mapReady = false;
    var settings = null;
    var mapDefaults = null;;
    var markerCluster = null;
    var checkinAfterInit = false;
    var since = null;
    var icon = null;
    var myIcon = null;
    var cookieName = 'ae_checkin_location';
    var openwindow = null;

    window.aeMapReady = function() {
        mapReady = true;
        aeFetchLocations();
    }

    $(function() {
        $('body').on('click', '[data-ae-close]', function(e) {
            e.preventDefault();
            $('.ae_modal').hide();
        });
    });

    function aeDoCheckin() {
        $('#ae_login').hide();
        $('#ae_checkin').hide();
        $('#ae_thanks').show();
        var center = map.getCenter();
        $.ajax({
            url: settings.base_url + 'ae/v1/checkin',
            method: 'POST',
            headers: {'x-wp-nonce':settings.nonce},
            data: {
                lat: center.lat(),
                lon: center.lng(),
                content: aeGetCheckinText(),
                status: 'publish',
            }
        }).done(function (response) {
            aePollLocations();
        });
    }

    // TODO: serialize the whole form
    function aeGetCheckinText() {
        return $('#ae_checkin form input[name="content"]').val();
    }

    function aeSetCheckinText(text) {
        return $('#ae_checkin form input[name="content"]').val(text || '');
    }

    window.aeSettings = function (_settings) {
        settings = _settings;
        icon = settings.marker ? new google.maps.MarkerImage(settings.marker.url,
            new google.maps.Size(settings.marker.width, settings.marker.height),
            new google.maps.Point(0, 0),
            new google.maps.Point(settings.marker.vertexX, settings.marker.vertexY)
        ) : null;
        myIcon = settings.my_marker ? new google.maps.MarkerImage(settings.my_marker.url,
            new google.maps.Size(settings.my_marker.width, settings.my_marker.height),
            new google.maps.Point(0, 0),
            new google.maps.Point(settings.my_marker.vertexX, settings.my_marker.vertexY)
        ) : null;
        var handleCheckin = function(evt) {
            evt.preventDefault();
            if (settings.loggedin) {
                aeDoCheckin();
            } else {
                var center = map.getCenter();
                document.cookie = cookieName + '=' + escape(JSON.stringify({
                    lat: center.lat(),
                    lng: center.lng(),
                    zoom: map.getZoom(),
                    checkinText: aeGetCheckinText(),
                })) + ';path=/'
                $('#ae_login').show();
                $('#ae_checkin').hide();
            }
        };
        $('#ae_checkin a[data-checkin]').click(handleCheckin);
        $('#ae_checkin form[data-checkin]').submit(handleCheckin);
        aeFetchLocations();
    }

    if ("geolocation" in navigator) {
        navigator.geolocation.getCurrentPosition(function(position) {
            var center = {
                lat: position.coords.latitude,
                lng: position.coords.longitude
            };
            var zoom = 15;
            if (!mapDefaults) {
                if (map) {
                    map.panTo(center);
                    map.setZoom(zoom);
                } else {
                    mapDefaults = {
                        zoom: zoom,
                        center: center,
                    };
                }
            }
        });
    }

    function aePollLocations() {
        var separator = settings.base_url.indexOf('?') === -1 ? '?' : '&';
        $.ajax({
            url: settings.base_url + 'ae/v1/checkin' + separator + 'since=' + (since || ''),
            headers: {'x-wp-nonce':settings.nonce},
        }).done(function (response) {
            since = response.since;
            $('.ae-count').text(response.count);
            aeAddLocations(response.results);
        });
    }

    function aeFetchLocations() {
        if (!settings || !mapReady) {
            return;
        }
        if (document.cookie) {
            var key = cookieName + '=';
            var cookie = document.cookie;
            var start = cookie.indexOf(key);
            if (start !== -1) {
                var end = cookie.indexOf(';', start);
                if (end === -1) {
                    end = cookie.length;
                }
                try {
                    var cookieData = JSON.parse(unescape(cookie.substr(start + key.length, end - start - key.length)));
                    mapDefaults = {
                        zoom: parseFloat(cookieData.zoom),
                        center: {lat: cookieData.lat, lng: cookieData.lng},
                    };
                    aeSetCheckinText(cookieData.checkinText);
                    if (settings.loggedin) {
                        checkinAfterInit = true;
                    }
                } catch (e) {
                }
                document.cookie = cookieName + '=;expires=Thu, 01 Jan 1970 00:00:01 GMT;path=/'
            }
        }
        $.ajax({
            url: settings.base_url + 'ae/v1/checkin',
            headers: {'x-wp-nonce':settings.nonce},
        }).done(function (response) {
            since = response.since;
            aeInitMap(response.results);
        });
        setInterval(aePollLocations, 30000);
    };

    function aeAddLocations(locations) {
        markerCluster.addMarkers(locations.map(function(post) {
            var infowindow;
            if (settings.checkin_html) {
                var post_content = $('<div>').text(post.post_content || '').html();
                var html = settings.checkin_html.replace(/\[ae-checkin-text\]/g, post_content);
                if (html) {
                    infowindow  = new google.maps.InfoWindow({
                        content: html,
                    });
                }
            }
            var marker = new google.maps.Marker({
                position: {
                    lat: post.lat,
                    lng: post.lng,
                },
                icon: post.current_user ? myIcon : icon,
            });
            google.maps.event.addListener(marker, 'click', function() {
                if (infowindow) {
                    infowindow.open(map, marker);
                }
                if (openwindow) {
                    openwindow.close();
                }
                if (openwindow === infowindow) {
                    openwindow = null;
                } else {
                    openwindow = infowindow;
                }
            });
            return marker;
        }));
    }
    function aeInitMap(locations) {
        var options = mapDefaults || {
            streetViewControl: false,
            zoom: 4,
            center: {lat: -35.376184, lng: -63.998128},
        };
        options.styles = settings.styles;
        options.mapTypeControlOptions = {mapTypeIds: google.maps.MapTypeId.ROADMAP};
        map = new google.maps.Map(document.getElementById('ae_map'), options);
        markerCluster = new MarkerClusterer(map, [], settings.cluster_options);
        aeAddLocations(locations);
        if (checkinAfterInit) {
            aeDoCheckin();
        }
    }
})(jQuery);
<|endoftext|>


<commit_before>var map;
$(document).ready(function() {

    $("#settingsbtn-map").click({
        param: 'settings_view'
    }, showView);

});

var GeoIcon = L.Icon.Default.extend({
    options: {
        iconUrl: 'js/libs/images/bus-icon.png'
    }
});

var geoIcon = new GeoIcon();

function onLocationFound(e) {
    var radius = e.accuracy / 2;
    var markerGeo = L.marker(e.latlng, {
        icon: geoIcon
    }).addTo(map);
    L.circle(e.latlng, radius).addTo(map);
}
<commit_msg>fixed geoIcon<commit_after>var map;

var GeoIcon = L.Icon.Default.extend({
    options: {
        iconUrl: 'js/libs/images/bus-icon.png'
    }
});

var geoIcon = new GeoIcon();

$(document).ready(function() {

    $("#settingsbtn-map").click({
        param: 'settings_view'
    }, showView);

});

function onLocationFound(e) {
    var radius = e.accuracy / 2;
    var markerGeo = L.marker(e.latlng, {
        icon: geoIcon
    }).addTo(map);
    L.circle(e.latlng, radius).addTo(map);
}
<|endoftext|>