<commit_before>/* global require, APP */
/**
 * Created by hristo on 8/4/14.
 */
var LocalStats = require("./LocalStatsCollector.js");
var RTPStats = require("./RTPStatsCollector.js");
var EventEmitter = require("events");
var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
var XMPPEvents = require("../../service/xmpp/XMPPEvents");
var CallStats = require("./CallStats");
var RTCEvents = require("../../service/RTC/RTCEvents");
var StatisticsEvents = require("../../service/statistics/Events");

var eventEmitter = new EventEmitter();

var localStats = null;

var rtpStats = null;

function stopLocal() {
    if (localStats) {
        localStats.stop();
        localStats = null;
    }
}

function stopRemote() {
    if (rtpStats) {
        rtpStats.stop();
        eventEmitter.emit(StatisticsEvents.STOP);
        rtpStats = null;
    }
}

function startRemoteStats (peerconnection) {
    if (rtpStats) {
        rtpStats.stop();
    }

    rtpStats = new RTPStats(peerconnection, 200, 2000, eventEmitter);
    rtpStats.start();
}

function onStreamCreated(stream) {
    if(stream.getOriginalStream().getAudioTracks().length === 0) {
        return;
    }

    localStats = new LocalStats(stream.getOriginalStream(), 200, statistics,
        eventEmitter);
    localStats.start();
}

function onDisposeConference(onUnload) {
    CallStats.sendTerminateEvent();
    stopRemote();
    if(onUnload) {
        stopLocal();
        eventEmitter.removeAllListeners();
    }
}

var statistics = {
    /**
     * Indicates that this audio level is for local jid.
     * @type {string}
     */
    LOCAL_JID: 'local',

    addListener: function(type, listener) {
        eventEmitter.on(type, listener);
    },
    removeListener: function (type, listener) {
        eventEmitter.removeListener(type, listener);
    },
    stop: function () {
        stopLocal();
        stopRemote();
        if(eventEmitter)
        {
            eventEmitter.removeAllListeners();
        }
    },
    stopRemoteStatistics: function()
    {
        stopRemote();
    },
    start: function () {
        APP.RTC.addStreamListener(onStreamCreated,
            StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
        APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE,
                             onDisposeConference);
        //FIXME: we may want to change CALL INCOMING event to
        // onnegotiationneeded
        APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
            startRemoteStats(event.peerconnection);
//            CallStats.init(event);
        });
        APP.xmpp.addListener(XMPPEvents.PEERCONNECTION_READY,
            function (session) {
            CallStats.init(session);
        });
        APP.RTC.addListener(RTCEvents.AUDIO_MUTE, function (mute) {
            CallStats.sendMuteEvent(mute, "audio");
        });
        APP.xmpp.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED, function () {
            CallStats.sendSetupFailedEvent();
        });
        APP.RTC.addListener(RTCEvents.VIDEO_MUTE, function (mute) {
            CallStats.sendMuteEvent(mute, "video");
        });

        APP.RTC.addListener(RTCEvents.GET_USER_MEDIA_FAILED, function (e) {
            CallStats.sendGetUserMediaFailed(e);
        });
        APP.xmpp.addListener(RTCEvents.CREATE_OFFER_FAILED, function (e) {
            CallStats.sendCreateOfferFailed(e);
        });
        APP.xmpp.addListener(RTCEvents.CREATE_ANSWER_FAILED, function (e) {
            CallStats.sendCreateAnswerFailed(e);
        });
        APP.xmpp.addListener(RTCEvents.SET_LOCAL_DESCRIPTION_FAILED, function (e) {
            CallStats.sendSetLocalDescFailed(e);
        });
        APP.xmpp.addListener(RTCEvents.SET_REMOTE_DESCRIPTION_FAILED, function (e) {
            CallStats.sendSetRemoteDescFailed(e);
        });
        APP.xmpp.addListener(RTCEvents.ADD_ICE_CANDIDATE_FAILED, function (e) {
            CallStats.sendAddIceCandidateFailed(e);
        });
    }
};

module.exports = statistics;<commit_msg>Fixes long lines.<commit_after>/* global require, APP */
/**
 * Created by hristo on 8/4/14.
 */
var LocalStats = require("./LocalStatsCollector.js");
var RTPStats = require("./RTPStatsCollector.js");
var EventEmitter = require("events");
var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
var XMPPEvents = require("../../service/xmpp/XMPPEvents");
var CallStats = require("./CallStats");
var RTCEvents = require("../../service/RTC/RTCEvents");
var StatisticsEvents = require("../../service/statistics/Events");

var eventEmitter = new EventEmitter();

var localStats = null;

var rtpStats = null;

function stopLocal() {
    if (localStats) {
        localStats.stop();
        localStats = null;
    }
}

function stopRemote() {
    if (rtpStats) {
        rtpStats.stop();
        eventEmitter.emit(StatisticsEvents.STOP);
        rtpStats = null;
    }
}

function startRemoteStats (peerconnection) {
    if (rtpStats) {
        rtpStats.stop();
    }

    rtpStats = new RTPStats(peerconnection, 200, 2000, eventEmitter);
    rtpStats.start();
}

function onStreamCreated(stream) {
    if(stream.getOriginalStream().getAudioTracks().length === 0) {
        return;
    }

    localStats = new LocalStats(stream.getOriginalStream(), 200, statistics,
        eventEmitter);
    localStats.start();
}

function onDisposeConference(onUnload) {
    CallStats.sendTerminateEvent();
    stopRemote();
    if(onUnload) {
        stopLocal();
        eventEmitter.removeAllListeners();
    }
}

var statistics = {
    /**
     * Indicates that this audio level is for local jid.
     * @type {string}
     */
    LOCAL_JID: 'local',

    addListener: function(type, listener) {
        eventEmitter.on(type, listener);
    },
    removeListener: function (type, listener) {
        eventEmitter.removeListener(type, listener);
    },
    stop: function () {
        stopLocal();
        stopRemote();
        if(eventEmitter)
        {
            eventEmitter.removeAllListeners();
        }
    },
    stopRemoteStatistics: function()
    {
        stopRemote();
    },
    start: function () {
        APP.RTC.addStreamListener(onStreamCreated,
            StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
        APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE,
                             onDisposeConference);
        //FIXME: we may want to change CALL INCOMING event to
        // onnegotiationneeded
        APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
            startRemoteStats(event.peerconnection);
//            CallStats.init(event);
        });
        APP.xmpp.addListener(XMPPEvents.PEERCONNECTION_READY,
            function (session) {
            CallStats.init(session);
        });
        APP.RTC.addListener(RTCEvents.AUDIO_MUTE, function (mute) {
            CallStats.sendMuteEvent(mute, "audio");
        });
        APP.xmpp.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED, function () {
            CallStats.sendSetupFailedEvent();
        });
        APP.RTC.addListener(RTCEvents.VIDEO_MUTE, function (mute) {
            CallStats.sendMuteEvent(mute, "video");
        });

        APP.RTC.addListener(RTCEvents.GET_USER_MEDIA_FAILED, function (e) {
            CallStats.sendGetUserMediaFailed(e);
        });
        APP.xmpp.addListener(RTCEvents.CREATE_OFFER_FAILED, function (e) {
            CallStats.sendCreateOfferFailed(e);
        });
        APP.xmpp.addListener(RTCEvents.CREATE_ANSWER_FAILED, function (e) {
            CallStats.sendCreateAnswerFailed(e);
        });
        APP.xmpp.addListener(
            RTCEvents.SET_LOCAL_DESCRIPTION_FAILED,
            function (e) {
                CallStats.sendSetLocalDescFailed(e);
        });
        APP.xmpp.addListener(
            RTCEvents.SET_REMOTE_DESCRIPTION_FAILED,
            function (e) {
                CallStats.sendSetRemoteDescFailed(e);
        });
        APP.xmpp.addListener(RTCEvents.ADD_ICE_CANDIDATE_FAILED, function (e) {
            CallStats.sendAddIceCandidateFailed(e);
        });
    }
};

module.exports = statistics;<|endoftext|>


<commit_before>/**
 * Module Name: Link
 * Description: Stores recent channel links, with commands to retrieve
 * information about links.
 */
var request = require('request'),
    _ = require('underscore')._;

var link = function(dbot) {
    var urlRegex = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
    var links = {};
    var fetchTitle = function(event, link) {
        request(link, function (error, response, body) {
            if(!error && response.statusCode == 200) {
                body = body.replace(/(\r\n|\n\r|\n)/gm, " ");
                var title = body.valMatch(/<title>(.*)<\/title>/, 2);
                if(title) {
                    event.reply(title[1]);
                }
            }
        });
    };

    var commands = {
        '~title': function(event) {
            var link = links[event.channel.name];
            if(_.isUndefined(event.params[1])) {
                var urlMatches = event.params[1].match(urlRegex);
                if(urlMatches !== null) {
                    link = urlMatches[0];
                }
            }
            fetchTitle(event, link);
        }
    };

    return {
        'name': 'link',
        'ignorable': true,
        'commands': commands,

        'listener': function(event) {
            var urlMatches = event.message.match(urlRegex);
            if(urlMatches !== null) {
                links[event.channel.name] = urlMatches[0];

                if(dbot.config.link.autoTitle == true) {
                    fetchTitle(event, urlMatches[0]);
                }
            }
        },
        'on': 'PRIVMSG'
    };
};

exports.fetch = function(dbot) {
    return link(dbot);
};
<commit_msg>fixt link [#131]<commit_after>/**
 * Module Name: Link
 * Description: Stores recent channel links, with commands to retrieve
 * information about links.
 */
var request = require('request'),
    _ = require('underscore')._;

var link = function(dbot) {
    this.urlRegex = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
    this.links = {};
    this.fetchTitle = function(event, link) {
        request(link, function (error, response, body) {
            if(!error && response.statusCode == 200) {
                body = body.replace(/(\r\n|\n\r|\n)/gm, " ");
                var title = body.valMatch(/<title>(.*)<\/title>/, 2);
                if(title) {
                    event.reply(title[1]);
                }
            }
        });
    };

    var commands = {
        '~title': function(event) {
            var link = this.links[event.channel.name];
            if(!_.isUndefined(event.params[1])) {
                var urlMatches = event.params[1].match(this.urlRegex);
                if(urlMatches !== null) {
                    link = urlMatches[0];
                }
            }
            this.fetchTitle(event, link);
        }
    };

    this.name = 'link';
    this.ignorable = true;
    this.commands = commands;

    this.listener = function(event) {
        var urlMatches = event.message.match(this.urlRegex);
        if(urlMatches !== null) {
            this.links[event.channel.name] = urlMatches[0];

            if(dbot.config.link.autoTitle == true) {
                this.fetchTitle(event, urlMatches[0]);
            }
        }
    }.bind(this);
    this.on = 'PRIVMSG';
};

exports.fetch = function(dbot) {
    return new link(dbot);
};
<|endoftext|>


<commit_before>PhoneApp.pack('PhoneApp.types', function() {
  /*jshint camelcase:false, devel:true*/
  'use strict';

  var mutableCount = 0;
  var hashed = {};

  this.Object = function() {
    this.__class__ = '[PhoneApp.Object]';
  };

  this.Object.prototype.toString = function() {
    return this.__class__;
  };

  var makeProperty = function(scope, key, w) {
    var initial;
    var needCompute = true;
    var initialArgs;
    var s, ke;
    w.__property__.forEach(function(item) {
      var tup = pullPoint(this, item) || pullPoint(window, item);
      if (tup) {
        s = tup.shift();
        ke = tup.shift();
        var hashTable = hashed[this.__id__];
        s.addObserver(ke, function(k, o, n) {
          initialArgs = [undefined, s, ke, n];
          // No observer? Don't recompute immediately
          if (!hashTable[key]) {
            needCompute = true;
            return;
          }
          // Otherwise, recompute
          var ov = initial;
          var rn = w.apply(scope, initialArgs);
          // If it changed, fire observers
          if (ov != rn) {
            initial = rn;
            hashTable[key].forEach(function(cbk) {
              window.setTimeout(function() {
                if (cbk.collapse && (scope[key] !== rn))
                  return;
                cbk.apply(scope, [key, ov, rn]);
              }, 1);
            });
          }
        });
      }else {
        console.error('Trying to property non-existent', item);
      }
    }, scope);

    // XXX Make properties observable
    Object.defineProperty(scope, key, {
      enumerable: true,
      configurable: true,
      // writable: false,
      get: function() {
        // XXX Optimization compute only at first demand
        if (needCompute) {
          needCompute = false;
          if (!initialArgs)
            initialArgs = [undefined, s, ke, s && s[ke]];
          initial = w.apply(this, initialArgs);
        }
        return initial;
      },
      set: function(value) {
        if (!initialArgs)
          initialArgs = [value, s, ke];
        else
          initialArgs[0] = value;
        initial = w.apply(this, initialArgs);
        initialArgs[0] = undefined;
        return initial;
        // XXX notify?
      }
    });
  };

  this.Object.create = this.Object.prototype.create = function(o) {
    /*jshint forin:false*/
    var ret = new (this.extend(o))();

    ret.init();
    if (typeof ret.__id__ == 'undefined') {
      console.error('You broke init you perv!!! Observes and Properties won\'t work on this one!', ret);
      throw new Error('BANG_BANG!');
    }

    var doo = [];
    for (var i in ret)
      doo.push(i);

    doo.forEach(function(key) {
      var w = this[key];
      if (!w)
        return;
      if (w.hasOwnProperty('__observes__')) {
        // Resolve points
        w.__observes__.forEach(function(item) {
          var tup = pullPoint(this, item) || pullPoint(window, item);
          if (tup) {
            var s = tup.shift();
            var ke = tup.shift();
            if (!('addObserver' in s))
              throw new Error('NOT_OBSERVABLE: ' + s);
            s.addObserver(ke, function(/*k, o, n*/) {
              w.apply(s, [s, ke]);
            });
          }else {
            console.error('Trying to observe non existent', item);
          }
        }, this);
      }

      if (w.hasOwnProperty('__property__')) {
        makeProperty(this, key, w);
      }
    }, ret);

    return ret;
  };

  this.Object._super = this.Object.prototype._super = function(methodName, scope, args) {
    return this.prototype[methodName].apply(scope || this, args);
  };

  this.Object.extend = this.Object.prototype.extend = function(o) {
    /*jshint newcap:false*/
    o = o || {};
    var construct;
    if (o.constructor != Function) {
      construct = function() {
        Object.keys(o).forEach(function(k) {
          this[k] = o[k];
        }, this);
      };
    }else {
      construct = o;
    }

    construct.prototype = new this();
    construct.extend = this.extend;
    construct.create = this.create;
    // construct.isExtensionOf = this.isExtensionOf;
    construct._super = this._super;
    return construct;
  };

  this.Object.prototype.init = function() {
    // console.log('-> Base PhoneApp Object init');
    hashed[this.__id__ = mutableCount++] = {};
  };

  this.Object.prototype.addObserver = function(key, listener, collapse) {
    var m;
    if (!(key in hashed[this.__id__]))
      hashed[this.__id__][key] = [];
    m = hashed[this.__id__][key];
    if (m.indexOf(listener) == -1) {
      listener.collapse = (collapse === undefined) || collapse;
      m.push(listener);
    }
  };

  this.Object.prototype.removeObserver = function(key, listener) {
    if (!(key in hashed[this.__id__]))
      return;
    var m = hashed[this.__id__][key];
    var n = m.indexOf(listener);
    if (n == -1)
      return;
    m.splice(n, 1);
  };

  this.Object.prototype.set = function(key, value) {
    var tup = pullConstructivePoint(this, key);
    var scope = tup.shift();
    key = tup.shift();
    var ov = scope[key];
    if (value === ov)
      return;
    scope[key] = value;
    (hashed[scope.__id__][key] || []).forEach(function(cbk) {
      window.setTimeout(function() {
        if (cbk.collapse && (scope[key] !== value))
          return;
        cbk.apply(scope, [key, ov, value]);
      }, 1);
    });
  };

  this.Object.prototype.destroy = function() {
    /*jshint forin:false*/
    delete hashed[this.__id__];
    for (var i in this)
      delete this[i];
  };

  this.Object.isExtensionOf = function(Class, ParentClass) {
    return Class && Class.prototype && (Class.prototype instanceof ParentClass);
  };

  /**
   * Property and Observes helpers
   */
  var pullPoint = function(scope, strKey) {
    var po = strKey.split('.');
    while (scope && po.length > 1) {
      scope = scope[po.shift()];
    }
    if (scope && !(po[po.length - 1] in scope))
      scope = null;
    return scope ? [scope, po.shift()] : undefined;
  };

  var pullConstructivePoint = function(scope, strKey) {
    var po = strKey.split('.'), k;
    while (po.length > 1) {
      k = po.shift();
      if (!(k in scope))
        scope[k] = {};
      scope = scope[k];
    }
    return [scope, po.shift()];
  };

  this.Object.prototype.get = function(path) {
    var ret = pullPoint(this, path) || pullPoint(window, path);
    if (ret)
      ret = (ret.shift())[ret.pop()];
    return ret;
  };

  var f;
  var t;
  PhoneApp.Binding = {
    oneWay: function(path) {
      return (function(n, s, k, v) {
        return v;
      }.property(path));
    },
    bothWays: function(path) {
      return (function(n, s, k, v) {
        if (n === undefined)
          return v;
        s.set(k, n);
        return n;
      }.property(path));
    },
    from: function(path) {
      f = path;
      return this;
    },
    to: function(key) {
      t = key;
      return this;
    },
    connect: function(scope) {
      this.bind(scope, t, f);
      f = undefined;
      t = undefined;
    }
  };

  PhoneApp.Binding.bind = function(scope, key, path) {
    makeProperty(scope, key, this.bothWays(path));
  };
  // (MyApp.anotherObject, "value", "MyApp.someController.value");

  // totoBinding = Ember.Binding.oneWay('App.user.fullName')

  // binding = Ember.Binding.from(this.valueBinding).to("value");

  Function.prototype.observes = function() {
    this.__observes__ = Array.prototype.slice.call(arguments);
    return this;
  };

  Function.prototype.property = function() {
    this.__property__ = Array.prototype.slice.call(arguments);
    return this;
  };

});

<commit_msg>-> Array of<commit_after>PhoneApp.pack('PhoneApp.types', function() {
  /*jshint camelcase:false, devel:true*/
  'use strict';

  var mutableCount = 0;
  var hashed = {};

  this.Object = function() {
    this.__class__ = '[PhoneApp.Object]';
  };

  this.Object.prototype.toString = function() {
    return this.__class__;
  };

  var makeProperty = function(scope, key, w) {
    var initial;
    var needCompute = true;
    var initialArgs;
    var s, ke;
    w.__property__.forEach(function(item) {
      var tup = pullPoint(this, item) || pullPoint(window, item);
      if (tup) {
        s = tup.shift();
        ke = tup.shift();
        var hashTable = hashed[this.__id__];
        s.addObserver(ke, function(k, o, n) {
          initialArgs = [undefined, s, ke, n];
          // No observer? Don't recompute immediately
          if (!hashTable[key]) {
            needCompute = true;
            return;
          }
          // Otherwise, recompute
          var ov = initial;
          var rn = w.apply(scope, initialArgs);
          // If it changed, fire observers
          if (ov != rn) {
            initial = rn;
            hashTable[key].forEach(function(cbk) {
              window.setTimeout(function() {
                if (cbk.collapse && (scope[key] !== rn))
                  return;
                cbk.apply(scope, [key, ov, rn]);
              }, 1);
            });
          }
        });
      }else {
        console.error('Trying to property non-existent', item);
      }
    }, scope);

    // XXX Make properties observable
    Object.defineProperty(scope, key, {
      enumerable: true,
      configurable: true,
      // writable: false,
      get: function() {
        // XXX Optimization compute only at first demand
        if (needCompute) {
          needCompute = false;
          if (!initialArgs)
            initialArgs = [undefined, s, ke, s && s[ke]];
          initial = w.apply(this, initialArgs);
        }
        return initial;
      },
      set: function(value) {
        if (!initialArgs)
          initialArgs = [value, s, ke];
        else
          initialArgs[0] = value;
        initial = w.apply(this, initialArgs);
        initialArgs[0] = undefined;
        return initial;
        // XXX notify?
      }
    });
  };

  this.Object.create = this.Object.prototype.create = function(o) {
    /*jshint forin:false*/
    var ret = new (this.extend(o))();

    ret.init();
    if (typeof ret.__id__ == 'undefined') {
      console.error('You broke init you perv!!! Observes and Properties won\'t work on this one!', ret);
      throw new Error('BANG_BANG!');
    }

    var doo = [];
    for (var i in ret)
      doo.push(i);

    doo.forEach(function(key) {
      var w = this[key];
      if (!w)
        return;
      if (w.hasOwnProperty('__observes__')) {
        // Resolve points
        w.__observes__.forEach(function(item) {
          var tup = pullPoint(this, item) || pullPoint(window, item);
          if (tup) {
            var s = tup.shift();
            var ke = tup.shift();
            if (!('addObserver' in s))
              throw new Error('NOT_OBSERVABLE: ' + s);
            s.addObserver(ke, function(/*k, o, n*/) {
              w.apply(s, [s, ke]);
            });
          }else {
            console.error('Trying to observe non existent', item);
          }
        }, this);
      }

      if (w.hasOwnProperty('__property__')) {
        makeProperty(this, key, w);
      }
    }, ret);

    return ret;
  };

  this.Object._super = this.Object.prototype._super = function(methodName, scope, args) {
    return this.prototype[methodName].apply(scope || this, args);
  };

  this.Object.extend = this.Object.prototype.extend = function(o) {
    /*jshint newcap:false*/
    o = o || {};
    var construct;
    if (o.constructor != Function) {
      construct = function() {
        Object.keys(o).forEach(function(k) {
          this[k] = o[k];
        }, this);
      };
    }else {
      construct = o;
    }

    construct.prototype = new this();
    construct.extend = this.extend;
    construct.create = this.create;
    // construct.isExtensionOf = this.isExtensionOf;
    construct._super = this._super;
    return construct;
  };

  this.Object.prototype.init = function() {
    // console.log('-> Base PhoneApp Object init');
    hashed[this.__id__ = mutableCount++] = {};
  };

  this.Object.prototype.addObserver = function(key, listener, collapse) {
    var m;
    if (!(key in hashed[this.__id__]))
      hashed[this.__id__][key] = [];
    m = hashed[this.__id__][key];
    if (m.indexOf(listener) == -1) {
      listener.collapse = (collapse === undefined) || collapse;
      m.push(listener);
    }
  };

  this.Object.prototype.removeObserver = function(key, listener) {
    if (!(key in hashed[this.__id__]))
      return;
    var m = hashed[this.__id__][key];
    var n = m.indexOf(listener);
    if (n == -1)
      return;
    m.splice(n, 1);
  };

  this.Object.prototype.set = function(key, value) {
    var tup = pullConstructivePoint(this, key);
    var scope = tup.shift();
    key = tup.shift();
    var ov = scope[key];
    if (value === ov)
      return;
    scope[key] = value;
    (hashed[scope.__id__][key] || []).forEach(function(cbk) {
      window.setTimeout(function() {
        if (cbk.collapse && (scope[key] !== value))
          return;
        cbk.apply(scope, [key, ov, value]);
      }, 1);
    });
  };

  this.Object.prototype.destroy = function() {
    /*jshint forin:false*/
    delete hashed[this.__id__];
    for (var i in this)
      delete this[i];
  };

  this.Object.isExtensionOf = function(Class, ParentClass) {
    return Class && Class.prototype && (Class.prototype instanceof ParentClass);
  };

  /**
   * Property and Observes helpers
   */
  var pullPoint = function(scope, strKey) {
    var po = strKey.split('.');
    while (scope && po.length > 1) {
      scope = scope[po.shift()];
    }
    if (scope && !(po[po.length - 1] in scope))
      scope = null;
    return scope ? [scope, po.shift()] : undefined;
  };

  var pullConstructivePoint = function(scope, strKey) {
    var po = strKey.split('.'), k;
    while (po.length > 1) {
      k = po.shift();
      if (!(k in scope))
        scope[k] = {};
      scope = scope[k];
    }
    return [scope, po.shift()];
  };

  this.Object.prototype.get = function(path) {
    var ret = pullPoint(this, path) || pullPoint(window, path);
    if (ret)
      ret = (ret.shift())[ret.pop()];
    return ret;
  };

  var f;
  var t;
  PhoneApp.Binding = {
    oneWay: function(path) {
      return (function(n, s, k, v) {
        return v;
      }.property(path));
    },
    bothWays: function(path) {
      return (function(n, s, k, v) {
        if (n === undefined)
          return v;
        s.set(k, n);
        return n;
      }.property(path));
    },
    from: function(path) {
      f = path;
      return this;
    },
    to: function(key) {
      t = key;
      return this;
    },
    connect: function(scope) {
      this.bind(scope, t, f);
      f = undefined;
      t = undefined;
    }
  };

  PhoneApp.Binding.bind = function(scope, key, path) {
    makeProperty(scope, key, this.bothWays(path));
  };
  // (MyApp.anotherObject, "value", "MyApp.someController.value");

  // totoBinding = Ember.Binding.oneWay('App.user.fullName')

  // binding = Ember.Binding.from(this.valueBinding).to("value");

  Function.prototype.observes = function() {
    this.__observes__ = Array.of(arguments);
    return this;
  };

  Function.prototype.property = function() {
    this.__property__ = Array.of(arguments);
    return this;
  };

});

<|endoftext|>


<commit_before>var map;
var service;
var actualPosition;
var markers = [];
var defaultMarkerColor = "FE7569";
var somePlaceIsSelected = false;

function initMap() {
    var myLatLng = {lat: 52.54063980000001, lng: -1.8916148000000703};
    var mapDiv = document.getElementById('map');
    map = new google.maps.Map(mapDiv, {
        center: myLatLng,
        zoom: 16
    });

    var infoWindow = new google.maps.InfoWindow({map: map});

    // Try HTML5 geolocation.
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
            actualPosition = {
                lat: position.coords.latitude,
                lng: position.coords.longitude
            };
            createMarkerOnMap(actualPosition, "Vaše poloha", "FFFFFF")

            map.setCenter(actualPosition);
            console.log("map initialized");

            document.getElementById('radius-input').addEventListener('change', getNearbyLocations);
            getNearbyLocations();
        }, function() {
            handleLocationError(true, infoWindow, map.getCenter());
        });
    } else {
        // Browser doesn't support Geolocation
        handleLocationError(false, infoWindow, map.getCenter());
    }
}

function handleLocationError(browserHasGeolocation, infoWindow, pos) {
    infoWindow.setPosition(pos);
    infoWindow.setContent(browserHasGeolocation ?
        'Error: The Geolocation service failed.' :
        'Error: Your browser doesn\'t support geolocation.');
}

function getNearbyLocations() {
    for( var i = 0; i < markers.length; i++ ) {
        markers[i].setMap(null);
    }
    markers = [];
    var request = {
        location: actualPosition,
        radius: document.getElementById('radius-input').value,
        types: ['restaurant', 'food'],
    };
    service = new google.maps.places.PlacesService(map);
    service.nearbySearch(request, markNearbyPlaces);
}

function markNearbyPlaces(results, status) {
    if (status == google.maps.places.PlacesServiceStatus.OK) {
        var userId = localStorage.getItem("id");
        var userPlaces;
        if(userId != null && userId != undefined){
            makeCorsRequest("GET", "https://ivebeenthereapi-matyapav.rhcloud.com/userPlaces/"+userId, null, function (responseText) {
                if(responseText){
                    userPlaces = JSON.parse(responseText);
                }
                results.forEach(function (v,i) {
                    var place = results[i];

                    var isUsers = false;
                    userPlaces.forEach(function (userPlace) {
                        if(userPlace != null) {
                            if (encodeURIComponent(userPlace.name) == encodeURIComponent(place.name)) {
                                isUsers = true;
                            }
                        }
                    });

                    var color = null;
                    var clickedColor = null;
                    if(isUsers){
                        color = "00ff00";
                        clickedColor = "006400";
                    }else{
                        color = defaultMarkerColor;
                        clickedColor = "7f3a34";
                    }
                    var marker = createMarkerOnMap(place.geometry.location, place.name, color);
                    if(marker != null && color != null && clickedColor != null){
                        markers.push({placeName: place.name, marker: marker, color: color});
                        marker.addListener('click', function(){
                            markers.forEach(function (v,i) {
                                setMarkerColor(markers[i].marker, markers[i].color);
                            });
                            setMarkerColor(marker, clickedColor)
                            showInfoAboutPlace(place);
                        });
                    }
                });
            });
        }else{
            results.forEach(function (v,i) {
                var place = results[i];
                var marker = createMarkerOnMap(place.geometry.location, place.name, defaultMarkerColor );
                markers.push({placeName: place.name, marker: marker});
                marker.addListener('click', function(){
                    markers.forEach(function (v,i) {
                        setMarkerColor(markers[i].marker, defaultMarkerColor)
                    });
                    setMarkerColor(marker, "7f3a34")
                    showInfoAboutPlace(place);
                });
            });
        }
    }
}

function createMarkerOnMap(position, title, pinColor) {
    var pinImage = new google.maps.MarkerImage("https://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|" + pinColor,
        new google.maps.Size(21, 34),
        new google.maps.Point(0, 0),
        new google.maps.Point(10, 34));
    var pinShadow = new google.maps.MarkerImage("https://chart.apis.google.com/chart?chst=d_map_pin_shadow",
        new google.maps.Size(40, 37),
        new google.maps.Point(0, 0),
        new google.maps.Point(12, 35));

    var marker = new google.maps.Marker({
        position: position,
        map: map,
        icon: pinImage,
        shadow: pinShadow,
        title: title
    });
    return marker;
}

function showInfoAboutPlace(place){

    document.getElementById('place-name').innerText = place.name;
    document.getElementById('place-address').innerText = place.vicinity;
    if(place.opening_hours != null){
        document.getElementById('place-open').innerText = place.opening_hours.open_now? 'Ano':'Ne';
    }else{
        document.getElementById('place-open').innerText = "-";
    }

    document.getElementById('actions').style = "visibility: visible";

    somePlaceIsSelected = true;
    console.log(place)
    document.getElementById('iwasthere').addEventListener('click', function () {
        var placeObj = {name: place.name, address: place.vicinity};
        userId = localStorage.getItem("id");
        markPlaceForUser(placeObj, userId);
    })
}

function setMarkerColor(marker, color) {
    marker.setIcon(new google.maps.MarkerImage("https://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|"+color ,
        new google.maps.Size(21, 34),
        new google.maps.Point(0, 0),
        new google.maps.Point(10, 34)));
}<commit_msg>Implementing "I was there" action #17<commit_after>var map;
var service;
var actualPosition;
var markers = [];
var defaultMarkerColor = "FE7569";
var somePlaceIsSelected = false;

function initMap() {
    var myLatLng = {lat: 52.54063980000001, lng: -1.8916148000000703};
    var mapDiv = document.getElementById('map');
    map = new google.maps.Map(mapDiv, {
        center: myLatLng,
        zoom: 16
    });

    var infoWindow = new google.maps.InfoWindow({map: map});

    // Try HTML5 geolocation.
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
            actualPosition = {
                lat: position.coords.latitude,
                lng: position.coords.longitude
            };
            createMarkerOnMap(actualPosition, "Vaše poloha", "FFFFFF")

            map.setCenter(actualPosition);
            console.log("map initialized");

            document.getElementById('radius-input').addEventListener('change', getNearbyLocations);
            getNearbyLocations();
        }, function() {
            handleLocationError(true, infoWindow, map.getCenter());
        });
    } else {
        // Browser doesn't support Geolocation
        handleLocationError(false, infoWindow, map.getCenter());
    }
}

function handleLocationError(browserHasGeolocation, infoWindow, pos) {
    infoWindow.setPosition(pos);
    infoWindow.setContent(browserHasGeolocation ?
        'Error: The Geolocation service failed.' :
        'Error: Your browser doesn\'t support geolocation.');
}

function getNearbyLocations() {
    for( var i = 0; i < markers.length; i++ ) {
        markers[i].setMap(null);
    }
    markers = [];
    var request = {
        location: actualPosition,
        radius: document.getElementById('radius-input').value,
        types: ['restaurant', 'food'],
    };
    service = new google.maps.places.PlacesService(map);
    service.nearbySearch(request, markNearbyPlaces);
}

function markNearbyPlaces(results, status) {
    if (status == google.maps.places.PlacesServiceStatus.OK) {
        var userId = localStorage.getItem("id");
        var userPlaces;
        if(userId != null && userId != undefined){
            makeCorsRequest("GET", "https://ivebeenthereapi-matyapav.rhcloud.com/userPlaces/"+userId, null, function (responseText) {
                if(responseText){
                    userPlaces = JSON.parse(responseText);
                }
                results.forEach(function (v,i) {
                    var place = results[i];
                    var marker = null;
                    var color = null;
                    var clickedColor = null;
                    userPlaces.forEach(function (userPlace) {
                        if(userPlace != null) {
                            if (encodeURIComponent(userPlace.name) == encodeURIComponent(place.name)) {
                                color = "00ff00";
                                clickedColor = "006400";
                            }else{
                                color = defaultMarkerColor;
                                clickedColor = "7f3a34";
                            }
                            marker = createMarkerOnMap(place.geometry.location, place.name, color);
                        }
                    });
                    if(marker != null && color != null && clickedColor != null){
                        markers.push({placeName: place.name, marker: marker, color: color});
                        marker.addListener('click', function(){
                            markers.forEach(function (v,i) {
                                setMarkerColor(markers[i].marker, markers[i].color);
                            });
                            setMarkerColor(marker, clickedColor)
                            showInfoAboutPlace(place);
                        });
                    }
                });
            });
        }else{
            results.forEach(function (v,i) {
                var place = results[i];
                var marker = createMarkerOnMap(place.geometry.location, place.name, defaultMarkerColor );
                markers.push({placeName: place.name, marker: marker});
                marker.addListener('click', function(){
                    markers.forEach(function (v,i) {
                        setMarkerColor(markers[i].marker, defaultMarkerColor)
                    });
                    setMarkerColor(marker, "7f3a34")
                    showInfoAboutPlace(place);
                });
            });
        }
    }
}

function createMarkerOnMap(position, title, pinColor) {
    var pinImage = new google.maps.MarkerImage("https://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|" + pinColor,
        new google.maps.Size(21, 34),
        new google.maps.Point(0, 0),
        new google.maps.Point(10, 34));
    var pinShadow = new google.maps.MarkerImage("https://chart.apis.google.com/chart?chst=d_map_pin_shadow",
        new google.maps.Size(40, 37),
        new google.maps.Point(0, 0),
        new google.maps.Point(12, 35));

    var marker = new google.maps.Marker({
        position: position,
        map: map,
        icon: pinImage,
        shadow: pinShadow,
        title: title
    });
    return marker;
}

function showInfoAboutPlace(place){

    document.getElementById('place-name').innerText = place.name;
    document.getElementById('place-address').innerText = place.vicinity;
    if(place.opening_hours != null){
        document.getElementById('place-open').innerText = place.opening_hours.open_now? 'Ano':'Ne';
    }else{
        document.getElementById('place-open').innerText = "-";
    }

    document.getElementById('actions').style = "visibility: visible";

    somePlaceIsSelected = true;
    console.log(place)
    document.getElementById('iwasthere').addEventListener('click', function () {
        var placeObj = {name: place.name, address: place.vicinity};
        userId = localStorage.getItem("id");
        markPlaceForUser(placeObj, userId);
    })
}

function setMarkerColor(marker, color) {
    marker.setIcon(new google.maps.MarkerImage("https://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|"+color ,
        new google.maps.Size(21, 34),
        new google.maps.Point(0, 0),
        new google.maps.Point(10, 34)));
}<|endoftext|>


<commit_before>var DB = require('./database');
var PATH = require('path');
var QUERYSTRING = require('querystring');
var MAPNIK = require('mapnik');

MAP = (function() {
	/**
	 * [COLORS description]
	 * @type {Array}
	 */
	var COLORS = ["FFFFFF", "FFF7FB", "ECE7F2", "D0D1E6", "A6BDDB", "74A9CF", "3690C0", "0570B0", "045A8D", "023858"]

	/**
	 * [ELSE_COLOR description]
	 * @type {String}
	 */
	var ELSE_COLOR = "ae3825";

	/**
	 * [OPACITY description]
	 * @type {Number}
	 */
	var OPACITY = 0.5;

	/**
	 * [MERCATOR description]
	 * @type {[type]}
	 */
	var MERCATOR = require(PATH.resolve(__dirname, '../node_modules/mapnik/examples/utils/sphericalmercator.js'));

	/**
	 * [PARSE_XYZ description]
	 * @type {[type]}
	 */
	var PARSE_XYZ = require(PATH.resolve(__dirname, '../node_modules/mapnik/examples/utils/tile.js')).parseXYZ;

	/**
	 * [TMS_SCHEME description]
	 * @type {Boolean}
	 */
	var TMS_SCHEME = false;

	/**
	 * [ATTRIBUTES description]
	 * @type {Object}
	 */
	var ATTRIBUTES;

	/**
	 *
	 */
	var DB_CONNECTOR;

	/* **********************************************************************************
	 * EVENT HANDLER
	 * *********************************************************************************/

	/**
	 * [handleAttributeInfo description]
	 * @param  {[type]} result [description]
	 */
	var handleAttributeInfo = function(result) {
		ATTRIBUTES = result;
		console.log('Attribute information successfully loaded. Service ready.');
	}

	/* **********************************************************************************
	 * CONTROL FUNCTIONS
	 * *********************************************************************************/

	/**
	 * Constructor
	 * @param  {[type]} dbConfig [description]
	 */
	var map = function (dbConfig) {
		DB_CONNECTOR = new DB(dbConfig);
		getAttributeInfo();
	}

	/**
	 * [getAttributeInfo description]
	 * @return {[type]} [description]
	 */
	var getAttributeInfo = function() {
		DB_CONNECTOR.getAttributeInfo(handleAttributeInfo);
	}

	/**
	 * [getFilter description]
	 * @param  {[type]} lowerBound [description]
	 * @param  {[type]} upperBound [description]
	 * @return {[type]}            [description]
	 */
	var getFilter = function(lowerBound, upperBound) {
		var filter = [];

		filter.push('<Filter>');

		if (lowerBound) filter.push('[value] > ' + lowerBound);
		if (lowerBound && upperBound) filter.push(' and ');
		if (upperBound) filter.push('[value] <= ' + upperBound);

		filter.push('</Filter>');
		return filter.join('');
	}

	/**
	 * [getSymolizer description]
	 * @param  {[type]} color         [description]
	 * @param  {[type]} renderOutline [description]
	 * @param  {[type]} renderLabel   [description]
	 * @return {[type]}               [description]
	 */
	var getSymolizer = function(color, renderOutline, renderLabel) {
		var symbolizer = ['<PolygonSymbolizer gamma=".65" fill-opacity="' + OPACITY + '" fill="#' + color +'"/>'];

		if (renderOutline) symbolizer.push(renderOutline);
		if (renderLabel) symbolizer.push(renderLabel);

		return symbolizer;
	}

	/**
	 * [getStyleXML description] // NOT TESTED YET
	 * @param  {[type]} layer [description]
	 * @param  {[type]} zoom  [description]
	 * @return {[type]}       [description]
	 */
	var getStyleXML = function(layer, zoom) {
		var renderLabel,
			renderOutline,
			strokeWidth = 1,
			quantiles = ATTRIBUTES[layer].quantiles;

			if (zoom > 11) strokeWidth = 2;
			if (zoom > 12) {
				renderLabel = '<TextSymbolizer face-name="DejaVu Sans Book" size="16" dy="-10" fill="black" halo-fill= "white" halo-radius="2" character-spacing="1">[cell_id]</TextSymbolizer><TextSymbolizer face-name="DejaVu Sans Book" size="16" dy="10" fill="black" halo-fill= "white" halo-radius="2" character-spacing="1">[label]</TextSymbolizer>';
				renderOutline = '<LineSymbolizer stroke="#000000" stroke-width="2"/>';
			}

		var style = [
			'<?xml version="1.0" encoding="utf-8"?>',
			'<Map minimum-version="2.0.0" buffer-size="128">',
			'<Style name="' + layer + '" filter-mode="first">'
		];

		quantiles.forEach(function(quantil, i) {
			style.push('<Rule>');

			if (i === 0) style.push(getFilter(undefined, quantil));
			else style.push(getFilter(quantiles[i-1], quantil));

			style.push(getSymolizer(COLORS[i], renderOutline, renderLabel));

			if (i === quantiles.length-1) {
				style.push('</Rule>');
				style.push('<Rule>');
				style.push(getFilter(quantil, undefined));
				style.push(getSymolizer(COLORS[i+1], renderOutline, renderLabel));
			}

			style.push('</Rule>');
		});

		style.push('<Rule><ElseFilter/>');
		style.push(getSymolizer(ELSE_COLOR, renderOutline, renderLabel));
		style.push('</Rule>');
		style.push('</Style>');

		style.push('<Style name="cells"><Rule><LineSymbolizer stroke="#ccc" stroke-width="' + strokeWidth + '"/></Rule></Style>');
		style.push('</Map>');
		return style.join('');

	}

	/**
	 * [getTile description]
	 * @param  {[type]}   req  [description]
	 * @param  {[type]}   res  [description]
	 * @param  {Function} next [description]
	 * @return {[type]}        [description]
	 */
	var getTile = function (req, res, next) {
		var table = ATTRIBUTES[req.params.layer].table,
			queryParams = QUERYSTRING.parse(req.query),
			bbox = MERCATOR.xyz_to_envelope(parseInt(queryParams.x), parseInt(queryParams.y), parseInt(queryParams.z), false);
			map = new MAPNIK.Map(256, 256, MERCATOR.proj4);

		PARSE_XYZ(req, TMS_SCHEME, function(error,params) {
			if (!error) {
				map.bufferSize = 64;
        		map.fromStringSync(getStyleXML(req.params.layer, queryParams.z), {strict: true});

        		if (queryParams.z > 8) {
					var cellsLayer = new MAPNIK.Layer('tile', MERCATOR.proj4);
   		     		cellsLayer.datasource = new MAPNIK.Datasource(DB_CONNECTOR.getMapnikDatasourceConfig(table, bbox, queryParams.timestamp, req.params.layer.toLowerCase().indexOf('date') == 0));
	        		cellsLayer.styles = ['cells'];
	        		map.add_layer(cellsLayer);
        		}

        		var attributesLayer = new MAPNIK.Layer('tile', MERCATOR.proj4);
        		attributesLayer.datasource = new MAPNIK.Datasource(DB_CONNECTOR.getMapnikDatasourceConfig(table, bbox, queryParams.timestamp, req.params.layer.toLowerCase().indexOf('date') == 0));
        		attributesLayer.styles = [req.params.layer];
        		map.add_layer(attributesLayer);

        		map.extent = bbox;
            	var im = new MAPNIK.Image(map.width, map.height);
			    map.render(im, function(err, im) {
              		if (err) {
                		throw err;
              		} else {
                		res.writeHead(200, {'Content-Type': 'image/png'});
                		res.end(im.encodeSync('png'));
              		}
           		});
			} else {
				res.writeHead(500, {'Content-Type': 'text/plain'});
				res.end(error.message);
			}
		});
	}

	/**
	 * [getLegend description] // NOT TESTED YET
	 * @param  {[type]}   req  [description]
	 * @param  {[type]}   res  [description]
	 * @param  {Function} next [description]
	 * @return {[type]}        [description]
	 */
	var getLegend = function (req, res, next) {
		var quantiles = ATTRIBUTES[req.params.layer].quantiles;

		var entries = [];
		quantiles.forEach(function(quantil, i) {
			entries.push({
				'color': '#' + COLORS[i],
				'label': ((i === 0) ? ('[value] <=' + quantil) : (quantiles[i-1] + ' < [value] <= ' + quantil))
			});
		});

		entries.push({'color': '#' + COLORS[quantiles.length], 'label': quantiles[quantiles.length - 1] + ' < [value]'});
		entries.push({'color': '#' + ELSE_COLOR, 'label': 'Other values'});

		res.send('{"attributeName": "' + req.params.layer + '", "labels": ' + JSON.stringify(entries) + '}');
		next();
	}

	map.prototype.getTile = getTile;
	map.prototype.getLegend = getLegend;
	return map;
}());

module.exports = MAP;<commit_msg>Add comments to map module<commit_after>var DB = require('./database');
var PATH = require('path');
var QUERYSTRING = require('querystring');
var MAPNIK = require('mapnik');

MAP = (function() {
	/**
	 * Defines the color scheme of the map.
	 * @type {Array}
	 */
	var COLORS = ["FFFFFF", "FFF7FB", "ECE7F2", "D0D1E6", "A6BDDB", "74A9CF", "3690C0", "0570B0", "045A8D", "023858"]

	/**
	 * Defines the color of features not covered by the color scheme.
	 * @type {String}
	 */
	var ELSE_COLOR = "ae3825";

	/**
	 * The opacity of the OSMatrix layer.
	 * @type {Number}
	 */
	var OPACITY = 0.5;

	/**
	 * Map projection object. Used to render map.
	 * @type {Object}
	 */
	var MERCATOR = require(PATH.resolve(__dirname, '../node_modules/mapnik/examples/utils/sphericalmercator.js'));

	/**
	 * Parses the XYZ scheme into bounding box.
	 * @type {Function}
	 */
	var PARSE_XYZ = require(PATH.resolve(__dirname, '../node_modules/mapnik/examples/utils/tile.js')).parseXYZ;

	/**
	 * Indicates if the request follows TMS scheme.
	 * @type {Boolean}
	 */
	var TMS_SCHEME = false;

	/**
	 * Contains table names and quantile thresholds for attributes.
	 * @type {Object}
	 */
	var ATTRIBUTES;

	/**
	 *
	 */
	var DB_CONNECTOR;

	/* **********************************************************************************
	 * EVENT HANDLER
	 * *********************************************************************************/

	/**
	 * Handles results of getAttribute Info
	 * @param  {Object} result Attrbute information as returned from getAttributeInfo
	 */
	var handleAttributeInfo = function(result) {
		ATTRIBUTES = result;
		console.log('Attribute information successfully loaded. Service ready.');
	}

	/* **********************************************************************************
	 * CONTROL FUNCTIONS
	 * *********************************************************************************/

	/**
	 * Constructor
	 * @param  {Object} dbConfig Database configuration info including user name, password, host and table.
	 */
	var map = function (dbConfig) {
		DB_CONNECTOR = new DB(dbConfig);
		getAttributeInfo();
	}

	/**
	 * Gets information on tables and quantil threshold from database.
	 */
	var getAttributeInfo = function() {
		DB_CONNECTOR.getAttributeInfo(handleAttributeInfo);
	}

	/**
	 * Returns filter definition for given bounds
	 * @param  {Number} lowerBound The lower bound of the filter.
	 * @param  {Number} upperBound The upper bound of the filter.
	 * @return {String}            The filter definition encoded in Mapnik XML.
	 */
	var getFilter = function(lowerBound, upperBound) {
		var filter = [];

		filter.push('<Filter>');

		if (lowerBound) filter.push('[value] > ' + lowerBound);
		if (lowerBound && upperBound) filter.push(' and ');
		if (upperBound) filter.push('[value] <= ' + upperBound);

		filter.push('</Filter>');
		return filter.join('');
	}

	/**
	 * Returns defintion of the symbolizer
	 * @param  {String} color         The fill color hexcode.
	 * @param  {String} renderOutline The feature outline definition.
	 * @param  {String} renderLabel   The feature label definition.
	 * @return {String}               The symbolizer encoded in Mapnik XML.
	 */
	var getSymolizer = function(color, renderOutline, renderLabel) {
		var symbolizer = ['<PolygonSymbolizer gamma=".65" fill-opacity="' + OPACITY + '" fill="#' + color +'"/>'];

		if (renderOutline) symbolizer.push(renderOutline);
		if (renderLabel) symbolizer.push(renderLabel);

		return symbolizer;
	}

	/**
	 * Returns the style XML for the layer and zoom level
	 * @param  {String} layer The layer for which the style is created.
	 * @param  {Number} zoom  The zoom for which the style is created.
	 * @return {String}       The style definition encoded in Mapnik XML.
	 */
	var getStyleXML = function(layer, zoom) {
		var renderLabel,
			renderOutline,
			strokeWidth = 1,
			quantiles = ATTRIBUTES[layer].quantiles;

			if (zoom > 11) strokeWidth = 2;
			if (zoom > 12) {
				renderLabel = '<TextSymbolizer face-name="DejaVu Sans Book" size="16" dy="-10" fill="black" halo-fill= "white" halo-radius="2" character-spacing="1">[cell_id]</TextSymbolizer><TextSymbolizer face-name="DejaVu Sans Book" size="16" dy="10" fill="black" halo-fill= "white" halo-radius="2" character-spacing="1">[label]</TextSymbolizer>';
				renderOutline = '<LineSymbolizer stroke="#000000" stroke-width="2"/>';
			}

		var style = [
			'<?xml version="1.0" encoding="utf-8"?>',
			'<Map minimum-version="2.0.0" buffer-size="128">',
			'<Style name="' + layer + '" filter-mode="first">'
		];

		quantiles.forEach(function(quantil, i) {
			style.push('<Rule>');

			if (i === 0) style.push(getFilter(undefined, quantil));
			else style.push(getFilter(quantiles[i-1], quantil));

			style.push(getSymolizer(COLORS[i], renderOutline, renderLabel));

			if (i === quantiles.length-1) {
				style.push('</Rule>');
				style.push('<Rule>');
				style.push(getFilter(quantil, undefined));
				style.push(getSymolizer(COLORS[i+1], renderOutline, renderLabel));
			}

			style.push('</Rule>');
		});

		style.push('<Rule><ElseFilter/>');
		style.push(getSymolizer(ELSE_COLOR, renderOutline, renderLabel));
		style.push('</Rule>');
		style.push('</Style>');

		style.push('<Style name="cells"><Rule><LineSymbolizer stroke="#ccc" stroke-width="' + strokeWidth + '"/></Rule></Style>');
		style.push('</Map>');
		return style.join('');

	}

	/**
	 * Responds tohe getTile request by sending the image of the tile. See http://mcavage.github.com/node-restify/#Routing for parameter description.
	 */
	var getTile = function (req, res, next) {
		var table = ATTRIBUTES[req.params.layer].table,
			queryParams = QUERYSTRING.parse(req.query),
			bbox = MERCATOR.xyz_to_envelope(parseInt(queryParams.x), parseInt(queryParams.y), parseInt(queryParams.z), false);
			map = new MAPNIK.Map(256, 256, MERCATOR.proj4);

		PARSE_XYZ(req, TMS_SCHEME, function(error,params) {
			if (!error) {
				map.bufferSize = 64;
        		map.fromStringSync(getStyleXML(req.params.layer, queryParams.z), {strict: true});

        		if (queryParams.z > 8) {
					var cellsLayer = new MAPNIK.Layer('tile', MERCATOR.proj4);
   		     		cellsLayer.datasource = new MAPNIK.Datasource(DB_CONNECTOR.getMapnikDatasourceConfig(table, bbox, queryParams.timestamp, req.params.layer.toLowerCase().indexOf('date') == 0));
	        		cellsLayer.styles = ['cells'];
	        		map.add_layer(cellsLayer);
        		}

        		var attributesLayer = new MAPNIK.Layer('tile', MERCATOR.proj4);
        		attributesLayer.datasource = new MAPNIK.Datasource(DB_CONNECTOR.getMapnikDatasourceConfig(table, bbox, queryParams.timestamp, req.params.layer.toLowerCase().indexOf('date') == 0));
        		attributesLayer.styles = [req.params.layer];
        		map.add_layer(attributesLayer);

        		map.extent = bbox;
            	var im = new MAPNIK.Image(map.width, map.height);
			    map.render(im, function(err, im) {
              		if (err) {
                		throw err;
              		} else {
                		res.writeHead(200, {'Content-Type': 'image/png'});
                		res.end(im.encodeSync('png'));
              		}
           		});
			} else {
				res.writeHead(500, {'Content-Type': 'text/plain'});
				res.end(error.message);
			}
		});
	}

	/**
	 * Responds tohe getLegend request by sending the image of the tile. See http://mcavage.github.com/node-restify/#Routing for parameter description.
	 */
	var getLegend = function (req, res, next) {
		var quantiles = ATTRIBUTES[req.params.layer].quantiles;

		var entries = [];
		quantiles.forEach(function(quantil, i) {
			entries.push({
				'color': '#' + COLORS[i],
				'label': ((i === 0) ? ('[value] <=' + quantil) : (quantiles[i-1] + ' < [value] <= ' + quantil))
			});
		});

		entries.push({'color': '#' + COLORS[quantiles.length], 'label': quantiles[quantiles.length - 1] + ' < [value]'});
		entries.push({'color': '#' + ELSE_COLOR, 'label': 'Other values'});

		res.send('{"attributeName": "' + req.params.layer + '", "labels": ' + JSON.stringify(entries) + '}');
		next();
	}

	map.prototype.getTile = getTile;
	map.prototype.getLegend = getLegend;
	return map;
}());

module.exports = MAP;<|endoftext|>


<commit_before>/*
	This file is part of cdauth’s map.

	OSM Route Manager is free software: you can redistribute it and/or modify
	it under the terms of the GNU Affero General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	cdauth’s map is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU Affero General Public License for more details.

	You should have received a copy of the GNU Affero General Public License
	along with cdauth’s map.  If not, see <http://www.gnu.org/licenses/>.

	Obtain the source code from http://svn.cdauth.de/viewvc.cgi/Tools/osm/map/
	or svn://svn.cdauth.de/tools/osm/map/.
*/

var map;
var layerMarkers;
var layerResults;
var lastHash;
var newLocationHash;
var icon;
var iconHighlight;
var lastSearch;
var lastSearchLayer;

function initMap()
{
	if(location.search.length > 1)
	{ // Move query string to location hash part
		var search_obj = decodeQueryString(location.search.substr(1));
		var hash_obj = decodeQueryString(location.hash.substr(1));
		for(var i in search_obj)
			hash_obj[i] = search_obj[i];
		location.replace(location.pathname+"#"+encodeQueryString(hash_obj));
		return;
	}

	OpenLayers.Layer.cdauth.XML.proxy = "gpx.php";
	map = new OpenLayers.Map.cdauth("map");

	icon = new OpenLayers.Icon('marker.png', new OpenLayers.Size(21,25), new OpenLayers.Pixel(-9, -25));
	iconHighlight = new OpenLayers.Icon('marker-green.png', new OpenLayers.Size(21,25), new OpenLayers.Pixel(-9, -25));

	map.addAllAvailableLayers();

	map.addLayer(new OpenLayers.Layer.cdauth.markers.OpenStreetBugs("OpenStreetBugs", "openstreetbugs.php", { visibility: false }));

	layerMarkers = new OpenLayers.Layer.cdauth.markers.LonLat("Markers");
	map.addLayer(layerMarkers);
	layerMarkers.addClickControl();

	layerResults = new OpenLayers.Layer.cdauth.markers.GeoSearch("Search results", "namefinder.php", icon, iconHighlight);
	map.addLayer(layerResults);

	doUpdateLocationHash();
	setInterval(doUpdateLocationHash, 500);
	map.events.register("newHash", map, updateLocationHash);

	layerResults.events.register("searchBegin", map, function(){
		document.getElementById("search-input").disabled = document.getElementById("search-button").disabled = document.getElementById("search-button-reset").disabled = true;
	});
	layerResults.events.register("searchSuccess", map, function(){
		document.getElementById("search-input").disabled = document.getElementById("search-button").disabled = document.getElementById("search-button-reset").disabled = false;
	});
	layerResults.events.register("searchFailure", map, function(){
		document.getElementById("search-input").disabled = document.getElementById("search-button").disabled = document.getElementById("search-button-reset").disabled = false;
	});
}

function geoSearch(onlygpx, dontzoomgpx)
{
	var search = document.getElementById("search-input").value;

	var gpx = false;
	if(search.match(/^http:\/\//))
	{
		var m;
		if(m = search.match(/[#?](.*)$/))
		{
			var query_string = decodeQueryString(m[1]);
			if(typeof query_string.lon == "undefined" || typeof query_string.lat == "undefined")
				gpx = true;
		}
		else
			gpx = true;
	}
	else
	{
		var m = search.match(/^(node|way|relation|trace)\s*#?\s*(\d+)$/i);
		if(m)
		{
			gpx = true;
			switch(m[1].toLowerCase())
			{
				case "node": search = "http://www.openstreetmap.org/api/0.6/node/"+m[2]; break;
				case "way": search = "http://www.openstreetmap.org/api/0.6/way/"+m[2]+"/full"; break;
				case "relation": search = "http://osm.cdauth.de/route-manager/gpx.php?relation="+m[2]; break;
				case "trace": search = "http://www.openstreetmap.org/trace/"+m[2]+"/data"; break;
			}
		}
	}

	if(gpx)
	{
		layerResults.geoSearch("");

		document.getElementById("search-input").disabled = document.getElementById("search-button").disabled = document.getElementById("search-button-reset").disabled = true;
		var layer = new OpenLayers.Layer.cdauth.XML(null, search, { removableInLayerSwitcher: true });
		map.addLayer(layer);
		layer.events.register("loadend", layer, function() {
			if(!dontzoomgpx)
			{
				var extent = this.getDataExtent();
				if(extent)
					map.zoomToExtent(extent);
			}
			document.getElementById("search-input").disabled = document.getElementById("search-button").disabled = document.getElementById("search-button-reset").disabled = false;
		});
		return layer;
	}
	else if(!onlygpx)
		layerResults.geoSearch(search);

	return false;
}

function updateLocationHash()
{
	newLocationHash = true;
}

function doUpdateLocationHash()
{
	if(newLocationHash)
	{
		location.hash = "#"+encodeQueryString(map.getQueryObject(layerMarkers, layerResults));
		lastHash = location.hash;
		newLocationHash = false;
	}
	else
	{
		var do_zoom = (location.hash != lastHash);
		lastHash = location.hash;
		if(do_zoom)
		{
			var query_object = decodeQueryString(location.hash.replace(/^#/, ""));
			if(typeof query_object.search != "undefined")
			{
				document.getElementById("search-input").value = query_object.search;
				var gpx_layer = geoSearch(true, (typeof query_object.lon != "undefined" && typeof query_object.lat != "undefined"));
				if(gpx_layer)
				{
					delete query_object.search;
					var i=0;
					if(query_object.xml)
					{
						while(typeof query_object.xml[i] != "undefined")
							i++;
					}
					else
						query_object.xml = { };
					query_object.xml[i] = gpx_layer.cdauthURL;
				}
			}
			map.zoomToQuery(query_object, layerMarkers, layerResults);
		}
	}
}

/*
var format;
			if(string.match(/\.gpx$/i))
				format = OpenLayers.Format.GPX;
			else if(string.match(/\.gml$/i))
				format = OpenLayers.Format.GML;
			else if(string.match(/\.osm$/i))
				format = OpenLayers.Format.OSM;
			lastSearchLayer = new OpenLayers.Layer.GML("Geographic file", string, { format: format });
			map.addLayer(lastSearchLayer);
			if(!zoomback)
				map.zoomToExtent(lastSearchLayer.getMaxExtent());
*/
<commit_msg>- Added keyboard control - Added MousePosition and ScaleLine - Fixed bug that lead to creating markers when clicking on other markers or on close buttons<commit_after>/*
	This file is part of cdauth’s map.

	OSM Route Manager is free software: you can redistribute it and/or modify
	it under the terms of the GNU Affero General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	cdauth’s map is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU Affero General Public License for more details.

	You should have received a copy of the GNU Affero General Public License
	along with cdauth’s map.  If not, see <http://www.gnu.org/licenses/>.

	Obtain the source code from http://svn.cdauth.de/viewvc.cgi/Tools/osm/map/
	or svn://svn.cdauth.de/tools/osm/map/.
*/

var map;
var layerMarkers;
var layerResults;
var lastHash;
var newLocationHash;
var icon;
var iconHighlight;
var lastSearch;
var lastSearchLayer;

function initMap()
{
	if(location.search.length > 1)
	{ // Move query string to location hash part
		var search_obj = decodeQueryString(location.search.substr(1));
		var hash_obj = decodeQueryString(location.hash.substr(1));
		for(var i in search_obj)
			hash_obj[i] = search_obj[i];
		location.replace(location.pathname+"#"+encodeQueryString(hash_obj));
		return;
	}

	OpenLayers.Layer.cdauth.XML.proxy = "gpx.php";
	map = new OpenLayers.Map.cdauth("map");

	icon = new OpenLayers.Icon('marker.png', new OpenLayers.Size(21,25), new OpenLayers.Pixel(-9, -25));
	iconHighlight = new OpenLayers.Icon('marker-green.png', new OpenLayers.Size(21,25), new OpenLayers.Pixel(-9, -25));

	map.addAllAvailableLayers();

	map.addLayer(new OpenLayers.Layer.cdauth.markers.OpenStreetBugs("OpenStreetBugs", "openstreetbugs.php", { visibility: false }));

	layerMarkers = new OpenLayers.Layer.cdauth.markers.LonLat("Markers");
	map.addLayer(layerMarkers);
	layerMarkers.addClickControl();

	layerResults = new OpenLayers.Layer.cdauth.markers.GeoSearch("Search results", "namefinder.php", icon, iconHighlight);
	map.addLayer(layerResults);

	doUpdateLocationHash();
	setInterval(doUpdateLocationHash, 500);
	map.events.register("newHash", map, updateLocationHash);

	layerResults.events.register("searchBegin", map, function(){
		document.getElementById("search-input").disabled = document.getElementById("search-button").disabled = document.getElementById("search-button-reset").disabled = true;
	});
	layerResults.events.register("searchSuccess", map, function(){
		document.getElementById("search-input").disabled = document.getElementById("search-button").disabled = document.getElementById("search-button-reset").disabled = false;
	});
	layerResults.events.register("searchFailure", map, function(){
		document.getElementById("search-input").disabled = document.getElementById("search-button").disabled = document.getElementById("search-button-reset").disabled = false;
	});

	var keyboardControl = null;
	for(var i=0; i<map.controls.length; i++)
	{
		if(map.controls[i].CLASS_NAME == "OpenLayers.Control.KeyboardDefaults")
		{
			keyboardControl = map.controls[i];
			break;
		}
	}
	if(keyboardControl)
	{
		OpenLayers.Event.observe(document.getElementById("search-input"), "focus", OpenLayers.Function.bindAsEventListener(function(e){ keyboardControl.deactivate() }, null));
		OpenLayers.Event.observe(document.getElementById("search-input"), "blur", OpenLayers.Function.bindAsEventListener(function(e){ keyboardControl.activate() }, null));
	}
}

function geoSearch(onlygpx, dontzoomgpx)
{
	var search = document.getElementById("search-input").value;

	var gpx = false;
	if(search.match(/^http:\/\//))
	{
		var m;
		if(m = search.match(/[#?](.*)$/))
		{
			var query_string = decodeQueryString(m[1]);
			if(typeof query_string.lon == "undefined" || typeof query_string.lat == "undefined")
				gpx = true;
		}
		else
			gpx = true;
	}
	else
	{
		var m = search.match(/^(node|way|relation|trace)\s*#?\s*(\d+)$/i);
		if(m)
		{
			gpx = true;
			switch(m[1].toLowerCase())
			{
				case "node": search = "http://www.openstreetmap.org/api/0.6/node/"+m[2]; break;
				case "way": search = "http://www.openstreetmap.org/api/0.6/way/"+m[2]+"/full"; break;
				case "relation": search = "http://osm.cdauth.de/route-manager/gpx.php?relation="+m[2]; break;
				case "trace": search = "http://www.openstreetmap.org/trace/"+m[2]+"/data"; break;
			}
		}
	}

	if(gpx)
	{
		layerResults.geoSearch("");

		document.getElementById("search-input").disabled = document.getElementById("search-button").disabled = document.getElementById("search-button-reset").disabled = true;
		var layer = new OpenLayers.Layer.cdauth.XML(null, search, { removableInLayerSwitcher: true });
		map.addLayer(layer);
		layer.events.register("loadend", layer, function() {
			if(!dontzoomgpx)
			{
				var extent = this.getDataExtent();
				if(extent)
					map.zoomToExtent(extent);
			}
			document.getElementById("search-input").disabled = document.getElementById("search-button").disabled = document.getElementById("search-button-reset").disabled = false;
		});
		return layer;
	}
	else if(!onlygpx)
		layerResults.geoSearch(search);

	return false;
}

function updateLocationHash()
{
	newLocationHash = true;
}

function doUpdateLocationHash()
{
	if(newLocationHash)
	{
		location.hash = "#"+encodeQueryString(map.getQueryObject(layerMarkers, layerResults));
		lastHash = location.hash;
		newLocationHash = false;
	}
	else
	{
		var do_zoom = (location.hash != lastHash);
		lastHash = location.hash;
		if(do_zoom)
		{
			var query_object = decodeQueryString(location.hash.replace(/^#/, ""));
			if(typeof query_object.search != "undefined")
			{
				document.getElementById("search-input").value = query_object.search;
				var gpx_layer = geoSearch(true, (typeof query_object.lon != "undefined" && typeof query_object.lat != "undefined"));
				if(gpx_layer)
				{
					delete query_object.search;
					var i=0;
					if(query_object.xml)
					{
						while(typeof query_object.xml[i] != "undefined")
							i++;
					}
					else
						query_object.xml = { };
					query_object.xml[i] = gpx_layer.cdauthURL;
				}
			}
			map.zoomToQuery(query_object, layerMarkers, layerResults);
		}
	}
}

/*
var format;
			if(string.match(/\.gpx$/i))
				format = OpenLayers.Format.GPX;
			else if(string.match(/\.gml$/i))
				format = OpenLayers.Format.GML;
			else if(string.match(/\.osm$/i))
				format = OpenLayers.Format.OSM;
			lastSearchLayer = new OpenLayers.Layer.GML("Geographic file", string, { format: format });
			map.addLayer(lastSearchLayer);
			if(!zoomback)
				map.zoomToExtent(lastSearchLayer.getMaxExtent());
*/
<|endoftext|>


<commit_before>function mergeData(data) {
  map = {};
  for (var key in data["people"]) {
    if(map[key] === undefined) {
      map[key] = {};
    }
    for(k2 in data) {
      map[key][k2] = data[k2][key];
    }
  }

  return map;
}

function drawMap(data) {
  means = meanValues(data);
  mergedData = mergeData(data);
  mapData = data["people"];
  regionName = "";
  happiness = happinessScore(mergedData, means);

  $('#map').vectorMap({
    map: 'se_merc_en',
    backgroundColor: 'transparent', /*#e1f7ff*/
    regionsSelectable: true,
    regionsSelectableOne: true,
    regionStyle: {
      initial: {
        fill: 'white',
        "fill-opacity": 1,
        stroke: 'black',
        "stroke-width": 2,
        "stroke-opacity": 1
      },
      hover: { // other style when hovering a region
        "fill-opacity": 0.5
      },
      selected: { // other style when a region is selected
        fill: "#01AEA1",
        //stroke: "#FCFCC9",
        //"stroke-width": 4,
      },
      selectedHover: {} // other styles when hovering a selected region
    },

    //Text on label shown when hovering
    //event.preventDefault(); // remove label

    onRegionTipShow: function(event, label, code){
      if (label.html() == 'Orebro') {
        regionName = 'Örebro';
        label.html('
Örebros län
 Score: '+ happiness[code].toFixed(3)); //Set label text
      }
      else{
        regionName = label.html();
        label.html('
'+label.html()+'s län
 Score: '+ happiness[code].toFixed(3));
      }
    },
    /*onRegionClick: function(event, code){
      event.preventDefault();
      // your "some code" of region selected
    },*/

    series: {
     regions: [{
         //define the range of color values
         //Blue scale ['#DEEBF7', '#08519C']
         scale: ['#DEEBF7', '#08519C'],
         //define the function that maps data to color range polynomial/linear
         normalizeFunction: 'linear',
         //define the coloration method
         attribute: 'fill',
         //define the array of country data
         values: happiness
       }]
     },

     onRegionSelected: function(event, label, isSelected){
      if(!isSelected) {
        return;
      }

      regionData = mergedData[label];
      income = regionData["money"];
      people = regionData["people"];
      working = (regionData["work"]/people*100).toFixed(1);
      unhealthy = (regionData["health"]/people*100).toFixed(1);
      newlyMarried = (regionData["married"]/people*100).toFixed(1);

      var htmlString =
      '
'+
      '

Statistik för '+regionName+'s län
'+
      '
Antal invånare: '+people+'

'+
      '
'+
      '
'+
      '

'+
      '

Medelinkomst:
' + income + '00 SEK

'+
      '

'+
      '

Andel sysselsatta:
' + working + '%

'+
      '
'+
      '
'+
      '

'+
      '

Antal friska: ' + unhealthy + '%

'+
      '

'+
      '

Nygifta: ' + newlyMarried + '%

'+
      '
'
      $('#stats').html(htmlString);
    }

  });
}

$(document).ready(function() {
  data = {};
  money(function(money) {
    data["money"] = money;
    people(function(people) {
      data["people"] = people;
      health(function(health) {
        data["health"] = health;
        married(function(married) {
          data["married"] = married;
          work(function(work) {
            data["work"] = work;
            drawMap(data);
          });
        });
      }, people);
    });
  });
});
<commit_msg>Lyckoscore<commit_after>function mergeData(data) {
  map = {};
  for (var key in data["people"]) {
    if(map[key] === undefined) {
      map[key] = {};
    }
    for(k2 in data) {
      map[key][k2] = data[k2][key];
    }
  }

  return map;
}

function drawMap(data) {
  means = meanValues(data);
  mergedData = mergeData(data);
  mapData = data["people"];
  regionName = "";
  happiness = happinessScore(mergedData, means);

  $('#map').vectorMap({
    map: 'se_merc_en',
    backgroundColor: 'transparent', /*#e1f7ff*/
    regionsSelectable: true,
    regionsSelectableOne: true,
    regionStyle: {
      initial: {
        fill: 'white',
        "fill-opacity": 1,
        stroke: 'black',
        "stroke-width": 2,
        "stroke-opacity": 1
      },
      hover: { // other style when hovering a region
        "fill-opacity": 0.5
      },
      selected: { // other style when a region is selected
        fill: "#01AEA1",
        //stroke: "#FCFCC9",
        //"stroke-width": 4,
      },
      selectedHover: {} // other styles when hovering a selected region
    },

    //Text on label shown when hovering
    //event.preventDefault(); // remove label

    onRegionTipShow: function(event, label, code){
      if (label.html() == 'Orebro') {
        regionName = 'Örebro';
        label.html('
Örebros län
 Lyckoscore: '+ happiness[code].toFixed(3)); //Set label text
      }
      else{
        regionName = label.html();
        label.html('
'+label.html()+'s län
 Lyckoscore: '+ happiness[code].toFixed(3));
      }
    },
    /*onRegionClick: function(event, code){
      event.preventDefault();
      // your "some code" of region selected
    },*/

    series: {
     regions: [{
         //define the range of color values
         //Blue scale ['#DEEBF7', '#08519C']
         scale: ['#DEEBF7', '#08519C'],
         //define the function that maps data to color range polynomial/linear
         normalizeFunction: 'linear',
         //define the coloration method
         attribute: 'fill',
         //define the array of country data
         values: happiness
       }]
     },

     onRegionSelected: function(event, label, isSelected){
      if(!isSelected) {
        return;
      }

      regionData = mergedData[label];
      income = regionData["money"];
      people = regionData["people"];
      working = (regionData["work"]/people*100).toFixed(1);
      unhealthy = (regionData["health"]/people*100).toFixed(1);
      newlyMarried = (regionData["married"]/people*100).toFixed(1);

      var htmlString =
      '
'+
      '

Statistik för '+regionName+'s län
'+
      '
Antal invånare: '+people+'

'+
      '
'+
      '
'+
      '

'+
      '

Medelinkomst:
' + income + '00 SEK

'+
      '

'+
      '

Andel sysselsatta:
' + working + '%

'+
      '
'+
      '
'+
      '

'+
      '

Antal friska:
' + unhealthy + '%

'+
      '

'+
      '

Nygifta:
' + newlyMarried + '%

'+
      '
'
      $('#stats').html(htmlString);
    }

  });
}

$(document).ready(function() {
  data = {};
  money(function(money) {
    data["money"] = money;
    people(function(people) {
      data["people"] = people;
      health(function(health) {
        data["health"] = health;
        married(function(married) {
          data["married"] = married;
          work(function(work) {
            data["work"] = work;
            drawMap(data);
          });
        });
      }, people);
    });
  });
});
<|endoftext|>


<commit_before>/********************************************************************
 *
 * The class for keyboard shortcut
 *
 * @public {class} Shortcut
 *
 *******************************************************************/

this.EXPORTED_SYMBOLS = ["Shortcut"];

/**
 * Shortcut class
 */

// possible values of nsIXULRuntime.OS:
// https://developer.mozilla.org/en/OS_TARGET
const nsIXULRuntime = Components.classes["@mozilla.org/xre/app-info;1"].getService(Components.interfaces.nsIXULRuntime);
const isMac = (nsIXULRuntime.OS.substring(0, 3).toLowerCase() == "mac");
const keyCodeToNameMap = {};
const keyNameToCodeMap = {};

// Ths list of nsIDOMKeyEvent constants can be found here:
// https://dxr.mozilla.org/mozilla-central/source/dom/interfaces/events/nsIDOMKeyEvent.idl
(function () {
    var keys = Components.interfaces.nsIDOMKeyEvent;
    for (var name in keys) {
        if (name.match(/^DOM_VK_/)) {
            var keyName = RegExp.rightContext.toLowerCase().replace(/(^|_)([a-z])/g, function(){
                return arguments[1] + arguments[2].toUpperCase();
            });
            var keyCode = keys[name];
            keyCodeToNameMap[keyCode] = keyName;
            keyNameToCodeMap[keyName] = keyCode;
        }
    }
})();

function Shortcut(data) {
    this.keyCode = data.keyCode;
    this.modifiers = [];
    // unify the order
    if (data.modifiers.indexOf("Ctrl") !== -1) this.modifiers.push("Ctrl");
    if (data.modifiers.indexOf("Alt") !== -1) this.modifiers.push("Alt");
    if (data.modifiers.indexOf("Shift") !== -1) this.modifiers.push("Shift");
}

// A combination with all modifiers e.g. Ctrl+Alt is incomplete
Shortcut.prototype.isComplete = function () {
    var keyName = keyCodeToNameMap[this.keyCode];
    if (!keyName) return false;
    return (["Win", "Control", "Alt", "Shift"].indexOf(keyName) == -1);
};

Shortcut.prototype.isPrintable = function () {
    var keyName = keyCodeToNameMap[this.keyCode];
    if (!keyName) return false;
    return /^[0-9A-Za-z]$/.test(keyName);
};

// returns the normalized string
Shortcut.prototype.toString = function () {
    var keyName = keyCodeToNameMap[this.keyCode];

    // if the key is not registered, return empty string
    if (!keyName) return "";

    var parts = Array.prototype.slice.call(this.modifiers);
    if (["Win", "Control", "Alt", "Shift"].indexOf(keyName) == -1) {
        parts.push(keyName);
    } else {
        parts.push("");
    }

    return parts.join("+");
};

// return the modifiers attribute for XUL <key> elements
Shortcut.prototype.getModifiers = function () {
    var keys = this.toString();

    // if this shortcut is not effective, return empty string
    if (!keys) return "";

    var modifiers = [];
    if (this.modifiers.indexOf("Ctrl") != -1) modifiers.push("accel");
    if (this.modifiers.indexOf("Alt") != -1) modifiers.push("alt");
    if (this.modifiers.indexOf("Shift") != -1) modifiers.push("shift");
    return modifiers.join(" ");
};

// return the string which is nice to show in the UI
Shortcut.prototype.getUIString = function () {
    var keys = this.toString();

    // if this shortcut is not effective, return empty string
    if (!keys) return "";

    if (isMac) {
        keys = keys.replace("Ctrl", "\u2318").replace("Alt", "\u2325").replace("Shift", "\u21E7");
    }
    return keys;
};

// returns new object from a normalized string
Shortcut.fromString = function (str) {
    var data = {}
    var parts = str.split("+");
    data.keyCode = keyNameToCodeMap[parts.pop()];
    data.modifiers = [].concat(parts);
    return new Shortcut(data);
};

Shortcut.fromEvent = function (event) {
    var data = {};

    data.keyCode = event.keyCode;

    // normalized Ctrl = Command on Mac
    // normalized Alt = Option on Mac
    var modifiers = [];
    if ((event.ctrlKey && !isMac) || (event.metaKey && isMac)) modifiers.push("Ctrl");
    if (event.altKey) modifiers.push("Alt");
    if (event.shiftKey) modifiers.push("Shift");
    data.modifiers = modifiers;

    return new Shortcut(data);
};
<commit_msg>core: shortcut use getter<commit_after>/********************************************************************
 *
 * The class for keyboard shortcut
 *
 * @public {class} Shortcut
 *
 *******************************************************************/

this.EXPORTED_SYMBOLS = ["Shortcut"];

/**
 * Shortcut class
 */

// possible values of nsIXULRuntime.OS:
// https://developer.mozilla.org/en/OS_TARGET
const nsIXULRuntime = Components.classes["@mozilla.org/xre/app-info;1"].getService(Components.interfaces.nsIXULRuntime);
const isMac = (nsIXULRuntime.OS.substring(0, 3).toLowerCase() == "mac");
const keyCodeToNameMap = {};
const keyNameToCodeMap = {};

// Ths list of nsIDOMKeyEvent constants can be found here:
// https://dxr.mozilla.org/mozilla-central/source/dom/interfaces/events/nsIDOMKeyEvent.idl
(function () {
    var keys = Components.interfaces.nsIDOMKeyEvent;
    for (var name in keys) {
        if (name.match(/^DOM_VK_/)) {
            var keyName = RegExp.rightContext.toLowerCase().replace(/(^|_)([a-z])/g, function(){
                return arguments[1] + arguments[2].toUpperCase();
            });
            var keyCode = keys[name];
            keyCodeToNameMap[keyCode] = keyName;
            keyNameToCodeMap[keyName] = keyCode;
        }
    }
})();

var printableRegex = /^[0-9A-Za-z]$/;

function Shortcut(data) {
    this.keyCode = data.keyCode;
    this.keyName = keyCodeToNameMap[this.keyCode];
    // unify the order
    this.modifiers = [];
    if (data.modifiers.indexOf("Ctrl") !== -1) this.modifiers.push("Ctrl");
    if (data.modifiers.indexOf("Alt") !== -1) this.modifiers.push("Alt");
    if (data.modifiers.indexOf("Shift") !== -1) this.modifiers.push("Shift");
}

Shortcut.prototype = {
    // A combination with all modifiers e.g. Ctrl+Alt is incomplete
    get isComplete() {
        delete this.isComplete;
        if (!this.keyName) return this.isComplete = false;
        return this.isComplete = (["Win", "Control", "Alt", "Shift"].indexOf(this.keyName) == -1);
    },

    get isPrintable() {
        delete this.isPrintable;
        if (!this.keyName) return this.isPrintable = false;
        return this.isPrintable = printableRegex.test(this.keyName);
    },

    // returns the normalized string
    toString: function () {
        // if the key is not registered, return empty string
        if (!this.keyName) return "";

        var parts = Array.prototype.slice.call(this.modifiers);
        if (["Win", "Control", "Alt", "Shift"].indexOf(this.keyName) == -1) {
            parts.push(this.keyName);
        } else {
            parts.push("");
        }

        return parts.join("+");
    },

    // return the modifiers attribute for XUL <key> elements
    getModifiers: function () {
        // if the key is not registered, return empty string
        if (!this.keyName) return "";

        var modifiers = [];
        if (this.modifiers.indexOf("Ctrl") != -1) modifiers.push("accel");
        if (this.modifiers.indexOf("Alt") != -1) modifiers.push("alt");
        if (this.modifiers.indexOf("Shift") != -1) modifiers.push("shift");
        return modifiers.join(" ");
    },

    // return the string which is nice to show in the UI
    getUIString: function () {
        var keys = this.toString();

        if (isMac) {
            keys = keys.replace("Ctrl", "\u2318").replace("Alt", "\u2325").replace("Shift", "\u21E7");
        }

        return keys;
    },
};

// returns new object from a normalized string
Shortcut.fromString = function (str) {
    var data = {}
    var parts = str.split("+");
    data.keyCode = keyNameToCodeMap[parts.pop()];
    data.modifiers = [].concat(parts);
    return new Shortcut(data);
};

Shortcut.fromEvent = function (event) {
    var data = {};

    data.keyCode = event.keyCode;

    // normalized Ctrl = Command on Mac
    // normalized Alt = Option on Mac
    var modifiers = [];
    if ((event.ctrlKey && !isMac) || (event.metaKey && isMac)) modifiers.push("Ctrl");
    if (event.altKey) modifiers.push("Alt");
    if (event.shiftKey) modifiers.push("Shift");
    data.modifiers = modifiers;

    return new Shortcut(data);
};
<|endoftext|>


<commit_before>// @flow

import type { Project } from './types';

const { Lokka } = require('lokka');
const { Transport } = require('lokka-transport-http');
const R = require('ramda');
const { createJWTWithoutSshKey } = require('./jwt');
const { logger } = require('./local-logging');

const { JWTSECRET, JWTAUDIENCE } = process.env;
const API_HOST = R.propOr('http://api:3000', 'API_HOST', process.env);

if (JWTSECRET == null) {
  logger.warn(
    'No JWTSECRET env variable set... this will cause api requests to fail',
  );
}

if (JWTAUDIENCE == null) {
  logger.warn(
    'No JWTAUDIENCE env variable set... this *might* cause api requests to fail',
  );
}

const apiAdminToken = createJWTWithoutSshKey({
  payload: {
    role: 'admin',
    iss: 'lagoon-commons',
    aud: JWTAUDIENCE || 'api.amazee.io',
  },
  jwtSecret: JWTSECRET || '',
});

const options = {
  headers: {
    Authorization: `Bearer ${apiAdminToken}`,
  },
};

const transport = new Transport(`${API_HOST}/graphql`, options);

const graphqlapi = new Lokka({ transport });

class ProjectNotFound extends Error {
  constructor(message: string) {
    super(message);
    this.name = 'ProjectNotFound';
  }
}

class EnvironmentNotFound extends Error {
  constructor(message: string) {
    super(message);
    this.name = 'EnvironmentNotFound';
  }
}

class NoActiveSystemsDefined extends Error {
  constructor(message: string) {
    super(message);
    this.name = 'NoActiveSystemsDefined';
  }
}

async function getProjectsByGitUrl(gitUrl: string): Promise<Project[]> {
  const result = await graphqlapi.query(`
    {
      allProjects(gitUrl: "${gitUrl}") {
        name
        production_environment
        openshift {
          console_url
          token
          project_user
          router_pattern
        }
      }
    }
  `);

  if (!result || !result.allProjects || !result.allProjects.length) {
    throw new ProjectNotFound(`Cannot find project for git repo ${gitUrl}`);
  }

  return result.allProjects;
}

async function getRocketChatInfoForProject(project: string): Project {
  const notificationsFragment = graphqlapi.createFragment(`
    fragment on NotificationRocketChat {
      webhook
      channel
    }
  `);

  const result = await graphqlapi.query(`
    {
      project:projectByName(name: "${project}") {
        rocketchats: notifications(type: ROCKETCHAT) {
          ...${notificationsFragment}
        }
      }
    }
  `);

  if (!result || !result.project || !result.project.rocketchats) {
    throw new ProjectNotFound(
      `Cannot find rocketchat information for project ${project}`,
    );
  }

  return result.project.rocketchats;
}

async function getSlackinfoForProject(project: string): Promise<Project> {
  const notificationsFragment = graphqlapi.createFragment(`
    fragment on NotificationSlack {
      webhook
      channel
    }
  `);

  const result = await graphqlapi.query(`
    {
      project:projectByName(name: "${project}") {
        slacks: notifications(type: SLACK) {
          ...${notificationsFragment}
        }
      }
    }
  `);

  if (!result || !result.project || !result.project.slacks) {
    throw new ProjectNotFound(
      `Cannot find slack information for project ${project}`,
    );
  }

  return result.project.slacks;
}

async function getActiveSystemForProject(
  project: string,
  task: string,
): Promise<Object> {
  const result = await graphqlapi.query(`
    {
      project:projectByName(name: "${project}"){
        active_systems_${task}
        branches
        pullrequests
      }
    }
  `);

  if (!result || !result.project) {
    throw new ProjectNotFound(
      `Cannot find active-systems information for project ${project}`,
    );
  }

  if (!result.project[`active_systems_${task}`]) {
    throw new NoActiveSystemsDefined(
      `Cannot find active system for task ${task} in project ${project}`,
    );
  }

  return result.project;
}

async function getEnvironmentByName(
  name: string,
  projectId: number
): Promise<Project[]> {
  const result = await graphqlapi.query(`
    {
      environmentByName(name: "${name}",project:${projectId}) {
        id,
        name,
        lagoon_route,
        lagoon_routes,
        deploy_type,
        environment_type,
        openshift_projectname,
        updated,
        created,
        deleted,
      }
    }
  `);

  if (!result || !result.environmentByName) {
    throw new EnvironmentNotFound(`Cannot find environment for projectId ${projectId}, name ${name}\n${result.environmentByName}`);
  }

  return result;
}

const addOrUpdateEnvironment = (
  name: string,
  projectId: number,
  deploy_type: string,
  environment_type: string,
  openshift_projectname: string,
): Promise<Object> =>
  graphqlapi.query(`
  mutation {
    addOrUpdateEnvironment(input: {
        name: "${name}",
        project: ${projectId},
        deploy_type: ${deploy_type},
        environment_type: ${environment_type},
        openshift_projectname: "${openshift_projectname}"
    }) {
      id
      name
      project {
        name
      }
      deploy_type
      environment_type
      openshift_projectname
    }
  }
`);

const updateEnvironment = (
  name: string,
  environmentId: number,
  patch: string,
): Promise<Object> =>
  graphqlapi.query(`
    mutation {
      updateEnvironment(input: {
        name: "${name}",
        id: ${environmentId},
        patch: ${patch}
      }) {
        id
        name
      }
    }
  `);

async function deleteEnvironment(
  name: string,
  project: string,
): Promise<Object> {
  const result = await graphqlapi.query(`
    {
      project:projectByName(name: "${project}"){
        id
      }
    }
  `);

  if (!result || !result.project) {
    throw new ProjectNotFound(`Cannot load id for project ${project}`);
  }

  return graphqlapi.query(`
    mutation {
      deleteEnvironment(input: {name: "${name}", project: ${result.project.id}})
    }
  `);
}

const getOpenShiftInfoForProject = (project: string): Promise<Object> =>
  graphqlapi.query(`
    {
      project:projectByName(name: "${project}"){
        id
        openshift  {
          console_url
          token
          project_user
          router_pattern
        }
        customer {
          private_key
        }
        git_url
        subfolder
        openshift_project_pattern
        production_environment
      }
    }
`);

const getProductionEnvironmentForProject = (project: string): Promise<Object> =>
  graphqlapi.query(`
    {
      project:projectByName(name: "${project}"){
        production_environment
      }
    }
`);

module.exports = {
  getProjectsByGitUrl,
  getRocketChatInfoForProject,
  getSlackinfoForProject,
  getActiveSystemForProject,
  getOpenShiftInfoForProject,
  getProductionEnvironmentForProject,
  addOrUpdateEnvironment,
  deleteEnvironment,
};
<commit_msg>#492 - export the new functions<commit_after>// @flow

import type { Project } from './types';

const { Lokka } = require('lokka');
const { Transport } = require('lokka-transport-http');
const R = require('ramda');
const { createJWTWithoutSshKey } = require('./jwt');
const { logger } = require('./local-logging');

const { JWTSECRET, JWTAUDIENCE } = process.env;
const API_HOST = R.propOr('http://api:3000', 'API_HOST', process.env);

if (JWTSECRET == null) {
  logger.warn(
    'No JWTSECRET env variable set... this will cause api requests to fail',
  );
}

if (JWTAUDIENCE == null) {
  logger.warn(
    'No JWTAUDIENCE env variable set... this *might* cause api requests to fail',
  );
}

const apiAdminToken = createJWTWithoutSshKey({
  payload: {
    role: 'admin',
    iss: 'lagoon-commons',
    aud: JWTAUDIENCE || 'api.amazee.io',
  },
  jwtSecret: JWTSECRET || '',
});

const options = {
  headers: {
    Authorization: `Bearer ${apiAdminToken}`,
  },
};

const transport = new Transport(`${API_HOST}/graphql`, options);

const graphqlapi = new Lokka({ transport });

class ProjectNotFound extends Error {
  constructor(message: string) {
    super(message);
    this.name = 'ProjectNotFound';
  }
}

class EnvironmentNotFound extends Error {
  constructor(message: string) {
    super(message);
    this.name = 'EnvironmentNotFound';
  }
}

class NoActiveSystemsDefined extends Error {
  constructor(message: string) {
    super(message);
    this.name = 'NoActiveSystemsDefined';
  }
}

async function getProjectsByGitUrl(gitUrl: string): Promise<Project[]> {
  const result = await graphqlapi.query(`
    {
      allProjects(gitUrl: "${gitUrl}") {
        name
        production_environment
        openshift {
          console_url
          token
          project_user
          router_pattern
        }
      }
    }
  `);

  if (!result || !result.allProjects || !result.allProjects.length) {
    throw new ProjectNotFound(`Cannot find project for git repo ${gitUrl}`);
  }

  return result.allProjects;
}

async function getRocketChatInfoForProject(project: string): Project {
  const notificationsFragment = graphqlapi.createFragment(`
    fragment on NotificationRocketChat {
      webhook
      channel
    }
  `);

  const result = await graphqlapi.query(`
    {
      project:projectByName(name: "${project}") {
        rocketchats: notifications(type: ROCKETCHAT) {
          ...${notificationsFragment}
        }
      }
    }
  `);

  if (!result || !result.project || !result.project.rocketchats) {
    throw new ProjectNotFound(
      `Cannot find rocketchat information for project ${project}`,
    );
  }

  return result.project.rocketchats;
}

async function getSlackinfoForProject(project: string): Promise<Project> {
  const notificationsFragment = graphqlapi.createFragment(`
    fragment on NotificationSlack {
      webhook
      channel
    }
  `);

  const result = await graphqlapi.query(`
    {
      project:projectByName(name: "${project}") {
        slacks: notifications(type: SLACK) {
          ...${notificationsFragment}
        }
      }
    }
  `);

  if (!result || !result.project || !result.project.slacks) {
    throw new ProjectNotFound(
      `Cannot find slack information for project ${project}`,
    );
  }

  return result.project.slacks;
}

async function getActiveSystemForProject(
  project: string,
  task: string,
): Promise<Object> {
  const result = await graphqlapi.query(`
    {
      project:projectByName(name: "${project}"){
        active_systems_${task}
        branches
        pullrequests
      }
    }
  `);

  if (!result || !result.project) {
    throw new ProjectNotFound(
      `Cannot find active-systems information for project ${project}`,
    );
  }

  if (!result.project[`active_systems_${task}`]) {
    throw new NoActiveSystemsDefined(
      `Cannot find active system for task ${task} in project ${project}`,
    );
  }

  return result.project;
}

async function getEnvironmentByName(
  name: string,
  projectId: number
): Promise<Project[]> {
  const result = await graphqlapi.query(`
    {
      environmentByName(name: "${name}",project:${projectId}) {
        id,
        name,
        lagoon_route,
        lagoon_routes,
        deploy_type,
        environment_type,
        openshift_projectname,
        updated,
        created,
        deleted,
      }
    }
  `);

  if (!result || !result.environmentByName) {
    throw new EnvironmentNotFound(`Cannot find environment for projectId ${projectId}, name ${name}\n${result.environmentByName}`);
  }

  return result;
}

const addOrUpdateEnvironment = (
  name: string,
  projectId: number,
  deploy_type: string,
  environment_type: string,
  openshift_projectname: string,
): Promise<Object> =>
  graphqlapi.query(`
  mutation {
    addOrUpdateEnvironment(input: {
        name: "${name}",
        project: ${projectId},
        deploy_type: ${deploy_type},
        environment_type: ${environment_type},
        openshift_projectname: "${openshift_projectname}"
    }) {
      id
      name
      project {
        name
      }
      deploy_type
      environment_type
      openshift_projectname
    }
  }
`);

const updateEnvironment = (
  name: string,
  environmentId: number,
  patch: string,
): Promise<Object> =>
  graphqlapi.query(`
    mutation {
      updateEnvironment(input: {
        name: "${name}",
        id: ${environmentId},
        patch: ${patch}
      }) {
        id
        name
      }
    }
  `);

async function deleteEnvironment(
  name: string,
  project: string,
): Promise<Object> {
  const result = await graphqlapi.query(`
    {
      project:projectByName(name: "${project}"){
        id
      }
    }
  `);

  if (!result || !result.project) {
    throw new ProjectNotFound(`Cannot load id for project ${project}`);
  }

  return graphqlapi.query(`
    mutation {
      deleteEnvironment(input: {name: "${name}", project: ${result.project.id}})
    }
  `);
}

const getOpenShiftInfoForProject = (project: string): Promise<Object> =>
  graphqlapi.query(`
    {
      project:projectByName(name: "${project}"){
        id
        openshift  {
          console_url
          token
          project_user
          router_pattern
        }
        customer {
          private_key
        }
        git_url
        subfolder
        openshift_project_pattern
        production_environment
      }
    }
`);

const getProductionEnvironmentForProject = (project: string): Promise<Object> =>
  graphqlapi.query(`
    {
      project:projectByName(name: "${project}"){
        production_environment
      }
    }
`);

module.exports = {
  getProjectsByGitUrl,
  getRocketChatInfoForProject,
  getSlackinfoForProject,
  getActiveSystemForProject,
  getOpenShiftInfoForProject,
  getEnvironmentByName,
  getProductionEnvironmentForProject,
  addOrUpdateEnvironment,
  updateEnvironment,
  deleteEnvironment,
};
<|endoftext|>