<commit_before>'use strict';

var github = require('./github');
var npm = require('./npm');
var db = require('./db');
var email = require('./email');

var _ = require('underscore');

var cache = {};

var yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);

npm.getLatestPackages(yesterday, function(error, packages) {
	if (error) {
		return console.error(error);
	}

	cache = packages;
    console.info('There are ' + cache.length + ' package updates.');

	db.readSubscriptions(function(error, subscriptions) {
		if (error) {
			return console.error(error);
		}

        _.each(subscriptions, function(subscription) {
            var user = github.getUserFromUrl(subscription.repourl);
            var repo = github.getRepoFromUrl(subscription.repourl);
            github.getPackageJson(user, repo, processPackageJson(subscription));
        });
	});
});

function processPackageJson(subscription) {
	return function(error, json) {
		if (error) {
			return console.error(error);
		}

        var packages = _.filter(_.extend(json.dependencies || {}, json.devDependencies || {}), isPackageInCache);

        _.each(packages, function(packageName) {
            var cached = cache[packageName];
            var versionRange = packages[packageName];

            email.send(subscription.email, subscription.repourl, packageName, versionRange, cached.version);
		});
	};
}

function isPackageInCache(dependency) {
    return !!cache[dependency];
}
<commit_msg>Add logging when sending email<commit_after>require('newrelic');

var github = require('./github');
var npm = require('./npm');
var db = require('./db');
var email = require('./email');

var _ = require('underscore');

var cache = {};

var yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);

npm.getLatestPackages(yesterday, function(error, packages) {
	if (error) {
		return console.error(error);
	}

	cache = packages;
    console.info('There are ' + cache.length + ' package updates.');

	db.readSubscriptions(function(error, subscriptions) {
		if (error) {
			return console.error(error);
		}

        _.each(subscriptions, function(subscription) {
            var user = github.getUserFromUrl(subscription.repourl);
            var repo = github.getRepoFromUrl(subscription.repourl);
            github.getPackageJson(user, repo, processPackageJson(subscription));
        });
	});
});

function processPackageJson(subscription) {
	return function(error, json) {
		if (error) {
			return console.error(error);
		}

        var packages = _.filter(_.extend(json.dependencies || {}, json.devDependencies || {}), isPackageInCache);

        _.each(packages, function(packageName) {
            var cached = cache[packageName];
            var versionRange = packages[packageName];

            console.info('Sending email about ' + packageName);
            email.send(subscription.email, subscription.repourl, packageName, versionRange, cached.version);
		});
	};
}

function isPackageInCache(dependency) {
    return !!cache[dependency];
}
<|endoftext|>


<commit_before>'use strict';
require('include-node');
var express = require('express');
require('./libs/log')('acaleph');
var app = express();
var _ = require('underscore');
{
    global.MySQL = Include('/libs/mysql');
    global.ErrorCode = Include('/libs/errorCode');
}

// 获取联系人
var messager = require('./api/messager');
// 加载RPC
let proto = Include('/proto/proto')();

let offsetIndex = 0;
let cache = {};
MySQL.Load().then(
    ()=>{
        MySQL.EventQueue.sync();

        function DoFetch(offset)
        {
            //获取事件进行处理
            MySQL.EventQueue.findAll({
                limit: 50,
                order: 'timestamp ASC',
                id:{$gt: offset}
            }).then(
                data=>{
                    if(!data || data.length === 0){
                        return Retry(offset);
                    }
                    else{
                        //
                        ProcessEvents(offset, data);
                    }
                },
                err=>{
                    log.error(err);
                }
            );
        }

        function Retry(offset)
        {
            setTimeout(function(){
                setTimeout(function(){
                    //
                    DoFetch(offset);
                }, 1000);
            }, 0);
        }

        function ProcessEvents (offset, events){
            let removeIDs = [];

            _.each(events, function(event){
                event = event.toJSON();
                if(cache[event.id]){
                    log.warn('events dumplicate: ', event);
                    return;
                }

                cache[event.id] = true;
                if(event.id <= offsetIndex){
                    log.warn('events dumplicate: ', event);
                }
                else{
                    log.info('events processing: ', event);
                }
                removeIDs.push(event.id);
                offsetIndex = event.id;

                // 发送数据或者销毁
                messager
                    .resolve(event)
                    .then((data) => {
                        messager.send(data.target, data.msg, data.setting);
                    }, messager.discard);
            });

            MySQL.EventQueue.destroy({where:{id:{$in: removeIDs}}}).then(
                ()=>{
                    cache = {};
                    DoFetch(offsetIndex);
                },err=>{
                    cache = {};
                    log.error(err, removeIDs);
                    DoFetch(offsetIndex);
                }
            );
        }

        Retry(0);
    }
);

// var server = app.listen(config.port, function(){
//     log.info('listening at %s', server.address().port);
// });
<commit_msg>移除已发送判断<commit_after>'use strict';
require('include-node');
var express = require('express');
require('./libs/log')('acaleph');
var app = express();
var _ = require('underscore');
{
    global.MySQL = Include('/libs/mysql');
    global.ErrorCode = Include('/libs/errorCode');
}

// 获取联系人
var messager = require('./api/messager');
// 加载RPC
let proto = Include('/proto/proto')();

// let offsetIndex = 0;
let cache = {};
MySQL.Load().then(
    ()=>{
        MySQL.EventQueue.sync();

        function DoFetch(offset)
        {
            //获取事件进行处理
            MySQL.EventQueue.findAll({
                limit: 50,
                order: 'timestamp ASC',
                id:{$gt: offset}
            }).then(
                data=>{
                    if(!data || data.length === 0){
                        return Retry(offset);
                    }
                    else{
                        //
                        ProcessEvents(offset, data);
                    }
                },
                err=>{
                    log.error(err);
                }
            );
        }

        function Retry(offset)
        {
            setTimeout(function(){
                setTimeout(function(){
                    //
                    DoFetch(offset);
                }, 1000);
            }, 0);
        }

        function ProcessEvents (offset, events){
            let removeIDs = [];

            let offsetIndex = 0;
            _.each(events, function(event){
                event = event.toJSON();
                // if(cache[event.id]){
                //     log.warn('events dumplicate: ', event);
                //     return;
                // }

                // cache[event.id] = true;
                if(event.id <= offsetIndex){
                    log.warn('events dumplicate: ', event);
                }
                else{
                    log.info('events processing: ', event);
                }
                removeIDs.push(event.id);
                offsetIndex = event.id;

                // 发送数据或者销毁
                messager
                    .resolve(event)
                    .then((data) => {
                        messager.send(data.target, data.msg, data.setting);
                    }, messager.discard);
            });

            MySQL.EventQueue.destroy({where:{id:{$in: removeIDs}}}).then(
                ()=>{
                    // cache = {};
                    DoFetch(offsetIndex);
                },err=>{
                    // cache = {};
                    log.error(err, removeIDs);
                    DoFetch(offsetIndex);
                }
            );
        }

        Retry(0);
    }
);

// var server = app.listen(config.port, function(){
//     log.info('listening at %s', server.address().port);
// });
<|endoftext|>


<commit_before>var util = require("util");
var path = require("path");
var Q = require("q");
var _ = require("lodash");

var nunjucks = require("nunjucks");
var AutoEscapeExtension = require("nunjucks-autoescape");
var FilterExtension = require("nunjucks-filter");
var I18nExtension = require("nunjucks-i18n");

var fs = require("../utils/fs");
var BaseGenerator = require("../generator");
var links = require("../utils/links");
var pageUtil = require("../utils/page");

var pkg = require("../../package.json");

var Generator = function() {
    BaseGenerator.apply(this, arguments);

    // revision
    this.revision = new Date();

    // Style to integrates in the output
    this.styles = ["website"];

    // Templates
    this.templates = {};
};
util.inherits(Generator, BaseGenerator);

// Prepare the genertor
Generator.prototype.prepare = function() {
    return BaseGenerator.prototype.prepare.apply(this)
    .then(this.prepareStyles)
    .then(this.prepareTemplates)
    .then(this.prepareTemplateEngine);
};

// Prepare all styles
Generator.prototype.prepareStyles = function() {
    var that = this;

    this.styles = _.chain(this.styles)
        .map(function(style) {
            var stylePath = that.options.styles[style];
            if (fs.existsSync(path.resolve(that.book.root, stylePath))) {
                return stylePath;
            }
            return null;
        })
        .compact()
        .value();

    return Q();
};

// Prepare templates
Generator.prototype.prepareTemplates = function() {
	this.templates["page"] = this.plugins.template("site:page") || path.resolve(this.options.theme, 'templates/website/page.html');
    this.templates["langs"] = this.plugins.template("site:langs") || path.resolve(this.options.theme, 'templates/website/langs.html');
    this.templates["glossary"] = this.plugins.template("site:glossary") || path.resolve(this.options.theme, 'templates/website/glossary.html');

	return Q();
};

// Prepare template engine
Generator.prototype.prepareTemplateEngine = function() {
    var that = this;

    return fs.readdir(path.resolve(__dirname, "../../theme/i18n"))
    .then(function(locales) {
        locales = _.chain(locales)
            .map(function(local) {
                local = path.basename(local, ".json");
                return [local, require("../../theme/i18n/"+local)];
            })
            .object()
            .value();

        if (!_.contains(_.keys(locales), that.options.language)) {
            that.book.logWarn("Language '"+that.options.language+"' is not available as a layout locales ("+_.keys(locales).join(", ")+")");
        }

        var folders = _.chain(that.templates)
            .values()
            .map(path.dirname)
            .uniq()
            .value();

        that.env = new nunjucks.Environment(
            new nunjucks.FileSystemLoader(folders),
            {
                autoescape: true
            }
        );

        // Add filter
        that.env.addFilter("contentLink", that.book.contentLink.bind(that.book));
        that.env.addFilter('lvl', function(lvl) {
            return lvl.split(".").length;
        });

        // Add extension
        that.env.addExtension('AutoEscapeExtension', new AutoEscapeExtension(that.env));
        that.env.addExtension('FilterExtension', new FilterExtension(that.env));
        that.env.addExtension('I18nExtension', new I18nExtension({
            env: that.env,
            translations: locales
        }));
    });
};

// Finis generation
Generator.prototype.finish = function() {
    return this.copyAssets()
    .then(this.copyCover)
    .then(this.writeGlossary)
    .then(this.writeSearchIndex);
};

// Convert an input file
Generator.prototype.writeParsedFile = function(page) {
    var that = this;

    var relativeOutput = this.book.contentLink(page.path);
    var output = path.join(that.options.output, relativeOutput);

    var basePath = path.relative(path.dirname(output), this.options.output) || ".";
    if (process.platform === 'win32') basePath = basePath.replace(/\\/g, '/');

    that.book.logInfo("write parsed file", page.path, "to", relativeOutput);
    return that.normalizePage(page)
    .then(function() {
        return that._writeTemplate(that.templates["page"], {
            progress: page.progress,

            _input: page.path,
            content: page.sections,

            basePath: basePath,
            staticBase: links.join(basePath, "gitbook")
        }, output);
    });
};

// Write the index for langs
Generator.prototype.langsIndex = function(langs) {
    var that = this;

    return this._writeTemplate(this.templates["langs"], {
        langs: langs
    }, path.join(this.options.output, "index.html"));
};

// Write glossary
Generator.prototype.writeGlossary = function() {
    var that = this;

    // No glossary
    if (this.book.glossary.length == 0) return Q();

    return this._writeTemplate(this.templates["glossary"], {}, path.join(this.options.output, "GLOSSARY.html"));
};

// Write the search index
Generator.prototype.writeSearchIndex = function() {
    var that = this;

    return fs.writeFile(
        path.join(this.options.output, "search_index.json"),
        JSON.stringify(this.book.searchIndex)
    );
};

// Convert a page into a normalized data set
Generator.prototype.normalizePage  = function(page) {
    var that = this;

    var _callHook = function(name) {
        return that.callHook(name, page)
        .then(function(_page) {
            page = _page;
            return page;
        });
    };

    return Q()
    .then(function() {
        return _callHook("page");
    })
    .then(function() {
        return page;
    });
};

// Generate a template
Generator.prototype._writeTemplate = function(tpl, options, output, interpolate) {
    var that = this;

    interpolate = interpolate || _.identity;
    return Q()
    .then(function(sections) {
    	return that.env.render(
    		tpl,
    		_.extend({
                gitbook: {
                    version: pkg.version
                },

	            styles: that.styles,

	            revision: that.revision,

	            title: that.options.title,
	            description: that.options.description,

	            glossary: that.book.glossary,

	            summary: that.book.summary,
	            allNavigation: that.book.navigation,

	            plugins: that.plugins,
	            pluginsConfig: JSON.stringify(that.options.pluginsConfig),
	            htmlSnippet: _.partialRight(that.plugins.html, that, options),

	            options: that.options,

                basePath: ".",
                staticBase: path.join(".", "gitbook"),
	        }, options)
	    );
    })
    .then(interpolate)
    .then(function(html) {
        return fs.writeFile(
            output,
            html
        );
    });
};

// Copy assets
Generator.prototype.copyAssets = function() {
    var that = this;

    // Copy gitbook assets
    return fs.copy(
        path.join(that.options.theme, "assets"),
        path.join(that.options.output, "gitbook")
    )

    // Copy plugins assets
    .then(function() {
        return Q.all(
            _.map(that.plugins.list, function(plugin) {
                var pluginAssets = path.join(that.options.output, "gitbook/plugins/", plugin.name);
                return plugin.copyAssets(pluginAssets, {
                    base: that.pluginAssetsBase
                });
            })
        );
    });
};

module.exports = Generator;
<commit_msg>Set translation to use in templates<commit_after>var util = require("util");
var path = require("path");
var Q = require("q");
var _ = require("lodash");

var nunjucks = require("nunjucks");
var AutoEscapeExtension = require("nunjucks-autoescape");
var FilterExtension = require("nunjucks-filter");
var I18nExtension = require("nunjucks-i18n");

var fs = require("../utils/fs");
var BaseGenerator = require("../generator");
var links = require("../utils/links");
var pageUtil = require("../utils/page");

var pkg = require("../../package.json");

var Generator = function() {
    BaseGenerator.apply(this, arguments);

    // revision
    this.revision = new Date();

    // Style to integrates in the output
    this.styles = ["website"];

    // Templates
    this.templates = {};
};
util.inherits(Generator, BaseGenerator);

// Prepare the genertor
Generator.prototype.prepare = function() {
    return BaseGenerator.prototype.prepare.apply(this)
    .then(this.prepareStyles)
    .then(this.prepareTemplates)
    .then(this.prepareTemplateEngine);
};

// Prepare all styles
Generator.prototype.prepareStyles = function() {
    var that = this;

    this.styles = _.chain(this.styles)
        .map(function(style) {
            var stylePath = that.options.styles[style];
            if (fs.existsSync(path.resolve(that.book.root, stylePath))) {
                return stylePath;
            }
            return null;
        })
        .compact()
        .value();

    return Q();
};

// Prepare templates
Generator.prototype.prepareTemplates = function() {
	this.templates["page"] = this.plugins.template("site:page") || path.resolve(this.options.theme, 'templates/website/page.html');
    this.templates["langs"] = this.plugins.template("site:langs") || path.resolve(this.options.theme, 'templates/website/langs.html');
    this.templates["glossary"] = this.plugins.template("site:glossary") || path.resolve(this.options.theme, 'templates/website/glossary.html');

	return Q();
};

// Prepare template engine
Generator.prototype.prepareTemplateEngine = function() {
    var that = this;

    return fs.readdir(path.resolve(__dirname, "../../theme/i18n"))
    .then(function(locales) {
        locales = _.chain(locales)
            .map(function(local) {
                local = path.basename(local, ".json");
                return [local, require("../../theme/i18n/"+local)];
            })
            .object()
            .value();

        if (!_.contains(_.keys(locales), that.options.language)) {
            that.book.logWarn("Language '"+that.options.language+"' is not available as a layout locales ("+_.keys(locales).join(", ")+")");
        }

        var folders = _.chain(that.templates)
            .values()
            .map(path.dirname)
            .uniq()
            .value();

        that.env = new nunjucks.Environment(
            new nunjucks.FileSystemLoader(folders),
            {
                autoescape: true
            }
        );

        // Add filter
        that.env.addFilter("contentLink", that.book.contentLink.bind(that.book));
        that.env.addFilter('lvl', function(lvl) {
            return lvl.split(".").length;
        });

        // Add extension
        that.env.addExtension('AutoEscapeExtension', new AutoEscapeExtension(that.env));
        that.env.addExtension('FilterExtension', new FilterExtension(that.env));
        that.env.addExtension('I18nExtension', new I18nExtension({
            env: that.env,
            translations: locales,
            locale: "language"
        }));
    });
};

// Finis generation
Generator.prototype.finish = function() {
    return this.copyAssets()
    .then(this.copyCover)
    .then(this.writeGlossary)
    .then(this.writeSearchIndex);
};

// Convert an input file
Generator.prototype.writeParsedFile = function(page) {
    var that = this;

    var relativeOutput = this.book.contentLink(page.path);
    var output = path.join(that.options.output, relativeOutput);

    var basePath = path.relative(path.dirname(output), this.options.output) || ".";
    if (process.platform === 'win32') basePath = basePath.replace(/\\/g, '/');

    that.book.logInfo("write parsed file", page.path, "to", relativeOutput);
    return that.normalizePage(page)
    .then(function() {
        return that._writeTemplate(that.templates["page"], {
            progress: page.progress,

            _input: page.path,
            content: page.sections,

            basePath: basePath,
            staticBase: links.join(basePath, "gitbook")
        }, output);
    });
};

// Write the index for langs
Generator.prototype.langsIndex = function(langs) {
    var that = this;

    return this._writeTemplate(this.templates["langs"], {
        langs: langs
    }, path.join(this.options.output, "index.html"));
};

// Write glossary
Generator.prototype.writeGlossary = function() {
    var that = this;

    // No glossary
    if (this.book.glossary.length == 0) return Q();

    return this._writeTemplate(this.templates["glossary"], {}, path.join(this.options.output, "GLOSSARY.html"));
};

// Write the search index
Generator.prototype.writeSearchIndex = function() {
    var that = this;

    return fs.writeFile(
        path.join(this.options.output, "search_index.json"),
        JSON.stringify(this.book.searchIndex)
    );
};

// Convert a page into a normalized data set
Generator.prototype.normalizePage  = function(page) {
    var that = this;

    var _callHook = function(name) {
        return that.callHook(name, page)
        .then(function(_page) {
            page = _page;
            return page;
        });
    };

    return Q()
    .then(function() {
        return _callHook("page");
    })
    .then(function() {
        return page;
    });
};

// Generate a template
Generator.prototype._writeTemplate = function(tpl, options, output, interpolate) {
    var that = this;

    interpolate = interpolate || _.identity;
    return Q()
    .then(function(sections) {
    	return that.env.render(
    		tpl,
    		_.extend({
                gitbook: {
                    version: pkg.version
                },

	            styles: that.styles,

	            revision: that.revision,

	            title: that.options.title,
	            description: that.options.description,
                language: that.options.language,

	            glossary: that.book.glossary,

	            summary: that.book.summary,
	            allNavigation: that.book.navigation,

	            plugins: that.plugins,
	            pluginsConfig: JSON.stringify(that.options.pluginsConfig),
	            htmlSnippet: _.partialRight(that.plugins.html, that, options),

	            options: that.options,

                basePath: ".",
                staticBase: path.join(".", "gitbook"),
	        }, options)
	    );
    })
    .then(interpolate)
    .then(function(html) {
        return fs.writeFile(
            output,
            html
        );
    });
};

// Copy assets
Generator.prototype.copyAssets = function() {
    var that = this;

    // Copy gitbook assets
    return fs.copy(
        path.join(that.options.theme, "assets"),
        path.join(that.options.output, "gitbook")
    )

    // Copy plugins assets
    .then(function() {
        return Q.all(
            _.map(that.plugins.list, function(plugin) {
                var pluginAssets = path.join(that.options.output, "gitbook/plugins/", plugin.name);
                return plugin.copyAssets(pluginAssets, {
                    base: that.pluginAssetsBase
                });
            })
        );
    });
};

module.exports = Generator;
<|endoftext|>


<commit_before>var epsg4326 = new OpenLayers.Projection("EPSG:4326");
var map;
var markers;
var popup;

var nonamekeys = {
   'openstreetmap.org': '2f59745a6b525b4ebdb100891d5b6711',
   'www.openstreetmap.org': 'fd093e52f0965d46bb1c6c6281022199',
   'openstreetmap.com': '4c60e7f5f31c576a9bb8da71c8d61152',
   'www.openstreetmap.com': '142f25a0770a51a9a400b3513834a199',
   'openstreetmap.net': '687c58fd1d715596bfc94abe653d8ac0',
   'www.openstreetmap.net': '0bd1654141c85d30b9c2ccdb5302f2e4'
};

OpenLayers._getScriptLocation = function () {
  // Should really have this file as an erb, so that this can return
  // the real rails root
   return "/openlayers/";
}

function createMap(divName, options) {
   options = options || {};

   map = new OpenLayers.Map(divName, {
      controls: options.controls || [
         new OpenLayers.Control.ArgParser(),
         new OpenLayers.Control.Attribution(),
         new OpenLayers.Control.LayerSwitcher(),
         new OpenLayers.Control.Navigation(),
         new OpenLayers.Control.PanZoomBar(),
         new OpenLayers.Control.ScaleLine()
      ],
      units: "m",
      maxResolution: 156543.0339,
      numZoomLevels: 20,
      displayProjection: new OpenLayers.Projection("EPSG:4326")
   });

   var mapnik = new OpenLayers.Layer.OSM.Mapnik("Mapnik", {
      displayOutsideMaxExtent: true,
      wrapDateLine: true
   });
   map.addLayer(mapnik);

   var osmarender = new OpenLayers.Layer.OSM.Osmarender("Osmarender", {
      displayOutsideMaxExtent: true,
      wrapDateLine: true
   });
   map.addLayer(osmarender);

   var cyclemap = new OpenLayers.Layer.OSM.CycleMap("Cycle Map", {
      displayOutsideMaxExtent: true,
      wrapDateLine: true
   });
   map.addLayer(cyclemap);

   var nonamekey = nonamekeys[document.domain];
   var noname = new OpenLayers.Layer.OSM("NoName", [
      "http://a.tile.cloudmade.com/" + nonamekey + "/3/256/",
      "http://b.tile.cloudmade.com/" + nonamekey + "/3/256/",
      "http://c.tile.cloudmade.com/" + nonamekey + "/3/256/"
   ], {
      displayOutsideMaxExtent: true,
      wrapDateLine: true,
      numZoomLevels: 19
   });
   map.addLayer(noname);

   var maplint = new OpenLayers.Layer.OSM.Maplint("Maplint", {
      displayOutsideMaxExtent: true,
      wrapDateLine: true
   });
   map.addLayer(maplint);

   var numZoomLevels = Math.max(mapnik.numZoomLevels, osmarender.numZoomLevels);
   markers = new OpenLayers.Layer.Markers("Markers", {
      displayInLayerSwitcher: false,
      numZoomLevels: numZoomLevels,
      maxExtent: new OpenLayers.Bounds(-20037508,-20037508,20037508,20037508),
      maxResolution: 156543,
      units: "m",
      projection: "EPSG:900913"
   });
   map.addLayer(markers);

   return map;
}

function getArrowIcon() {
   var size = new OpenLayers.Size(25, 22);
   var offset = new OpenLayers.Pixel(-30, -27);
   var icon = new OpenLayers.Icon("/images/arrow.png", size, offset);

   return icon;
}

function addMarkerToMap(position, icon, description) {
   var marker = new OpenLayers.Marker(position.clone().transform(epsg4326, map.getProjectionObject()), icon);

   markers.addMarker(marker);

   if (description) {
      marker.events.register("click", marker, function() { openMapPopup(marker, description) });
   }

   return marker;
}

function openMapPopup(marker, description) {
   closeMapPopup();

   popup = new OpenLayers.Popup.AnchoredBubble("popup", marker.lonlat, null,
                                               description, marker.icon, true);
   popup.setBackgroundColor("#E3FFC5");
   popup.autoSize = true;
   map.addPopup(popup);

   return popup;
}

function closeMapPopup() {
   if (popup) {
      map.removePopup(popup);
      delete popup;
   }
}

function removeMarkerFromMap(marker){
   markers.removeMarker(marker);
}

function getMapCenter(center, zoom) {
   return map.getCenter().clone().transform(map.getProjectionObject(), epsg4326);
}

function setMapCenter(center, zoom) {
   var numzoom = map.getNumZoomLevels();
   if (zoom >= numzoom) zoom = numzoom - 1;
   map.setCenter(center.clone().transform(epsg4326, map.getProjectionObject()), zoom);
}

function setMapExtent(extent) {
   map.zoomToExtent(extent.clone().transform(epsg4326, map.getProjectionObject()));
}

function getMapExtent(extent) {
   return map.getExtent().clone().transform(map.getProjectionObject(), epsg4326);
}

function getEventPosition(event) {
   return map.getLonLatFromViewPortPx(event.xy).clone().transform(map.getProjectionObject(), epsg4326);
}

function getMapLayers() {
   var layerConfig = "";

   for (var layers = map.getLayersBy("isBaseLayer", true), i = 0; i < layers.length; i++) {
      layerConfig += layers[i] == map.baseLayer ? "B" : "0";
   }

   for (var layers = map.getLayersBy("isBaseLayer", false), i = 0; i < layers.length; i++) {
      layerConfig += layers[i].getVisibility() ? "T" : "F";
   }

   return layerConfig;
}

function setMapLayers(layerConfig) {
   var l = 0;

   for (var layers = map.getLayersBy("isBaseLayer", true), i = 0; i < layers.length; i++) {
      var c = layerConfig.charAt(l++);

      if (c == "B") {
         map.setBaseLayer(layers[i]);
      }
   }

   while (layerConfig.charAt(l) == "B" || layerConfig.charAt(l) == "0") {
      l++;
   }

   for (var layers = map.getLayersBy("isBaseLayer", false), i = 0; i < layers.length; i++) {
      var c = layerConfig.charAt(l++);

      if (c == "T") {
         layers[i].setVisibility(true);
      } else if(c == "F") {
         layers[i].setVisibility(false);
      }
   }
}

function scaleToZoom(scale) {
   return Math.log(360.0/(scale * 512.0)) / Math.log(2.0);
}
<commit_msg>Copying across fix for #1547 from trunk<commit_after>var epsg4326 = new OpenLayers.Projection("EPSG:4326");
var map;
var markers;
var popup;

var nonamekeys = {
   'openstreetmap.org': '2f59745a6b525b4ebdb100891d5b6711',
   'www.openstreetmap.org': 'fd093e52f0965d46bb1c6c6281022199',
   'openstreetmap.com': '4c60e7f5f31c576a9bb8da71c8d61152',
   'www.openstreetmap.com': '142f25a0770a51a9a400b3513834a199',
   'openstreetmap.net': '687c58fd1d715596bfc94abe653d8ac0',
   'www.openstreetmap.net': '0bd1654141c85d30b9c2ccdb5302f2e4'
};

OpenLayers._getScriptLocation = function () {
  // Should really have this file as an erb, so that this can return
  // the real rails root
   return "/openlayers/";
}

function createMap(divName, options) {
   options = options || {};

   map = new OpenLayers.Map(divName, {
      controls: options.controls || [
         new OpenLayers.Control.ArgParser(),
         new OpenLayers.Control.Attribution(),
         new OpenLayers.Control.LayerSwitcher(),
         new OpenLayers.Control.Navigation(),
         new OpenLayers.Control.PanZoomBar(),
         new OpenLayers.Control.ScaleLine()
      ],
      units: "m",
      maxResolution: 156543.0339,
      numZoomLevels: 20,
      displayProjection: new OpenLayers.Projection("EPSG:4326")
   });

   var mapnik = new OpenLayers.Layer.OSM.Mapnik("Mapnik", {
      displayOutsideMaxExtent: true,
      wrapDateLine: true
   });
   map.addLayer(mapnik);

   var osmarender = new OpenLayers.Layer.OSM.Osmarender("Osmarender", {
      displayOutsideMaxExtent: true,
      wrapDateLine: true
   });
   map.addLayer(osmarender);

   var cyclemap = new OpenLayers.Layer.OSM.CycleMap("Cycle Map", {
      displayOutsideMaxExtent: true,
      wrapDateLine: true
   });
   map.addLayer(cyclemap);

   var nonamekey = nonamekeys[document.domain];
   var noname = new OpenLayers.Layer.OSM("NoName", [
      "http://a.tile.cloudmade.com/" + nonamekey + "/3/256/",
      "http://b.tile.cloudmade.com/" + nonamekey + "/3/256/",
      "http://c.tile.cloudmade.com/" + nonamekey + "/3/256/"
   ], {
      displayOutsideMaxExtent: true,
      wrapDateLine: true,
      numZoomLevels: 19
   });
   map.addLayer(noname);

   var maplint = new OpenLayers.Layer.OSM.Maplint("Maplint", {
      displayOutsideMaxExtent: true,
      wrapDateLine: true
   });
   map.addLayer(maplint);

   var numZoomLevels = Math.max(mapnik.numZoomLevels, osmarender.numZoomLevels);
   markers = new OpenLayers.Layer.Markers("Markers", {
      displayInLayerSwitcher: false,
      numZoomLevels: numZoomLevels,
      maxExtent: new OpenLayers.Bounds(-20037508,-20037508,20037508,20037508),
      maxResolution: 156543,
      units: "m",
      projection: "EPSG:900913"
   });
   map.addLayer(markers);

   return map;
}

function getArrowIcon() {
   var size = new OpenLayers.Size(25, 22);
   var offset = new OpenLayers.Pixel(-30, -27);
   var icon = new OpenLayers.Icon("/images/arrow.png", size, offset);

   return icon;
}

function addMarkerToMap(position, icon, description) {
   var marker = new OpenLayers.Marker(position.clone().transform(epsg4326, map.getProjectionObject()), icon);

   markers.addMarker(marker);

   if (description) {
      marker.events.register("click", marker, function() { openMapPopup(marker, description) });
   }

   return marker;
}

function openMapPopup(marker, description) {
   closeMapPopup();

   popup = new OpenLayers.Popup.AnchoredBubble("popup", marker.lonlat, null,
                                               description, marker.icon, true);
   popup.setBackgroundColor("#E3FFC5");
   popup.autoSize = true;
   map.addPopup(popup);

   return popup;
}

function closeMapPopup() {
   if (popup) {
      map.removePopup(popup);
      delete popup;
   }
}

function removeMarkerFromMap(marker){
   markers.removeMarker(marker);
}

function getMapCenter(center, zoom) {
   return map.getCenter().clone().transform(map.getProjectionObject(), epsg4326);
}

function setMapCenter(center, zoom) {
   zoom = parseInt(zoom);
   var numzoom = map.getNumZoomLevels();
   if (zoom >= numzoom) zoom = numzoom - 1;
   map.setCenter(center.clone().transform(epsg4326, map.getProjectionObject()), zoom);
}

function setMapExtent(extent) {
   map.zoomToExtent(extent.clone().transform(epsg4326, map.getProjectionObject()));
}

function getMapExtent(extent) {
   return map.getExtent().clone().transform(map.getProjectionObject(), epsg4326);
}

function getEventPosition(event) {
   return map.getLonLatFromViewPortPx(event.xy).clone().transform(map.getProjectionObject(), epsg4326);
}

function getMapLayers() {
   var layerConfig = "";

   for (var layers = map.getLayersBy("isBaseLayer", true), i = 0; i < layers.length; i++) {
      layerConfig += layers[i] == map.baseLayer ? "B" : "0";
   }

   for (var layers = map.getLayersBy("isBaseLayer", false), i = 0; i < layers.length; i++) {
      layerConfig += layers[i].getVisibility() ? "T" : "F";
   }

   return layerConfig;
}

function setMapLayers(layerConfig) {
   var l = 0;

   for (var layers = map.getLayersBy("isBaseLayer", true), i = 0; i < layers.length; i++) {
      var c = layerConfig.charAt(l++);

      if (c == "B") {
         map.setBaseLayer(layers[i]);
      }
   }

   while (layerConfig.charAt(l) == "B" || layerConfig.charAt(l) == "0") {
      l++;
   }

   for (var layers = map.getLayersBy("isBaseLayer", false), i = 0; i < layers.length; i++) {
      var c = layerConfig.charAt(l++);

      if (c == "T") {
         layers[i].setVisibility(true);
      } else if(c == "F") {
         layers[i].setVisibility(false);
      }
   }
}

function scaleToZoom(scale) {
   return Math.log(360.0/(scale * 512.0)) / Math.log(2.0);
}
<|endoftext|>


<commit_before>/**
 *
 * @providesModule SMXLoadingImage
 * @flow
 */
'use strict';

var React = require('react-native');
var { StyleSheet, View, requireNativeComponent, Animated, Easing } = React;

var shimAssert = require('./shim-assert');

var ICON_REF = 'icon';

var TIMES = 400;

var SMXLoadingImage = React.createClass({
  propTypes: {
    name: React.PropTypes.string,
    size: React.PropTypes.number,
    color: React.PropTypes.string,

    /**
     * accessible - Whether this element should be revealed as an accessible
     * element.
     */
    accessible: React.PropTypes.bool,
    /**
     * accessibilityLabel - Custom string to display for accessibility.
     */
    accessibilityLabel: React.PropTypes.string,

    /**
     * testID - A unique identifier for this element to be used in UI Automation
     * testing scripts.
     */
    testID: React.PropTypes.string,
    icon: React.PropTypes.object
  },

  getInitialState: function () {
    return {
      theta: new Animated.Value(45),
      rotate: new Animated.Value('0deg'),
      enter: new Animated.Value(0),
      angle: new Animated.Value(0)
    };
  },

  setNativeProps(props) {
    console.warn('setNativeProps');
    console.warn(props);
    this.refs[ICON_REF].setNativeProps(props);
  },

  _animate: function () {
    this.state.angle.setValue(0);
    this._anim = Animated.timing(this.state.angle, {
      toValue: 360 * TIMES,
      duration: 1200 * TIMES,
      easing: Easing.linear
    }).start(this._animate);
  },

  componentDidMount: function () {
    this._animate();
  },

  _animateEntrance: function () {
    Animated.spring(
      this.state.enter,
      {toValue: 1, friction: 8}
    ).start();
  },

  render: function () {
    var transformStyle = {
      transform: [
        {
          rotate: this.state.angle.interpolate({
            inputRange: [0, 360],
            outputRange: ['0deg', '360deg']
          })
        }
      ]
    };

    var style = [styles.base, this.props.style];
    console.log(style);

    shimAssert.basic(style, 'style must be initialized');

    var name = this.props.name;
    shimAssert.basic(name, 'name must be initialized');

    var size = this.props.size;
    shimAssert.basic(size, 'size must be initialized');

    var color = this.props.color;

    var nativeProps = Object.assign({},this.props);
    nativeProps.icon = {
      name: name,
      size: size,
      color: color
    };

    return <Animated.View style={[styles.base, style, transformStyle]}>
      <SMXLoadingImageView style={{backgroundColor: 'transparent'}} {...nativeProps} />
    </Animated.View>;
  }
});

var styles = StyleSheet.create({
  base: {
    overflow: 'hidden'
  }
});
var SMXLoadingImageView = requireNativeComponent('FAKIconImage', SMXLoadingImage);

module.exports = SMXLoadingImage;
<commit_msg>Fixing issue with loading spinner<commit_after>/**
 *
 * @providesModule SMXLoadingImage
 * @flow
 */
'use strict';

var React = require('react-native');
var { StyleSheet, View, requireNativeComponent, Animated, Easing } = React;

var shimAssert = require('./shim-assert');

var ICON_REF = 'icon';

var SMXLoadingImage = React.createClass({
  propTypes: {
    name: React.PropTypes.string,
    size: React.PropTypes.number,
    color: React.PropTypes.string,

    /**
     * accessible - Whether this element should be revealed as an accessible
     * element.
     */
    accessible: React.PropTypes.bool,
    /**
     * accessibilityLabel - Custom string to display for accessibility.
     */
    accessibilityLabel: React.PropTypes.string,

    /**
     * testID - A unique identifier for this element to be used in UI Automation
     * testing scripts.
     */
    testID: React.PropTypes.string,
    icon: React.PropTypes.object
  },

  getInitialState: function () {
    return {
      angle: new Animated.Value(0)
    };
  },

  setNativeProps(props) {
    this.refs[ICON_REF].setNativeProps(props);
  },

  _animate: function () {
    this.state.angle.setValue(0);
    this._anim = Animated.timing(this.state.angle, {
      toValue: 360,
      duration: 1200,
      easing: Easing.linear
    }).start(this._animate);
  },

  componentDidMount: function () {
    this._animate();
  },

  render: function () {
    var transformStyle = {
      transform: [
        {
          rotate: this.state.angle.interpolate({
            inputRange: [0, 360],
            outputRange: ['0deg', '360deg']
          })
        }
      ]
    };

    var style = [styles.base, this.props.style];

    shimAssert.basic(style, 'style must be initialized');

    var name = this.props.name;
    shimAssert.basic(name, 'name must be initialized');

    var size = this.props.size;
    shimAssert.basic(size, 'size must be initialized');

    var color = this.props.color;

    var nativeProps = Object.assign({},this.props);
    nativeProps.icon = {
      name: name,
      size: size,
      color: color
    };

    return <Animated.View style={[styles.base, style, transformStyle]}>
      <SMXLoadingImageView style={{backgroundColor: 'transparent'}} {...nativeProps} />
    </Animated.View>;
  }
});

var styles = StyleSheet.create({
  base: {
    overflow: 'hidden'
  }
});
var SMXLoadingImageView = requireNativeComponent('FAKIconImage', SMXLoadingImage);

module.exports = SMXLoadingImage;
<|endoftext|>


<commit_before>var Map = {
  markers: [],
  cities: [],
  zoomSwitch: 10,

  show: function() {
    var mapDiv = $('map')
    if (mapDiv && GBrowserIsCompatible()) {
      Map.map = new GMap2(document.getElementById("map"));
      Map.map.setCenter(new GLatLng(42.77309, -86.101754), 12);
      Map.map.enableScrollWheelZoom();
      Map.map.addControl(new GLargeMapControl());
      Map.map.addControl(new GMapTypeControl());
      Map.map.addControl(new GScaleControl());
      Map.map.addControl(new GOverviewMapControl());

      // listen for clicks
      GEvent.addListener(Map.map, 'click', function(overlay, point) {
        if (overlay) {
          // we now need a check here in case the overlay is the info window
          // only our icons will have a .html property
          if (overlay.html) {
            overlay.openInfoWindowHtml(overlay.html);
          }
        } else if (point) {
          //whatever you want to happen if you don't click on an overlay.
        }
      });

      GEvent.addListener(Map.map, "moveend", Map.refreshMarkers);
      GEvent.addListener(Map.map, "zoomend", Map.refreshMarkers);

      Map.mgr = new MarkerManager(Map.map);
      Map.refreshMarkers();
      Event.observe(window, "unload", GUnload);
    }
  },

  refreshMarkers: function() {
    var bounds = Map.map.getBounds();

    if (Map.map.getZoom() > Map.zoomSwitch) {
      new Ajax.Request('/locations.json', {method: 'get',
        parameters: {callback: 'Map.callback',
          northeast: bounds.getNorthEast().toUrlValue(),
          southwest: bounds.getSouthWest().toUrlValue()}} );
    } else {
      Map.getCities(bounds);
		}
  },

	getCities: function(bounds, callback) {
		var parameters = {callback: callback || 'Map.mapCities'};
		if (bounds) {
			parameters.northeast = bounds.getNorthEast().toUrlValue();
			parameters.southwest = bounds.getSouthWest().toUrlValue();
		}
		new Ajax.Request('/cities.json', {method: 'get', parameters: parameters });
	},

	mapCitiesAndZoom: function(cities) {
		Map.mapCities(cities);
		var bounds = new GLatLngBounds;
		Map.cities.compact().each(function(city) {
			bounds.extend(city.getLatLng());
		});
		Map.map.setZoom(Map.map.getBoundsZoomLevel(bounds));
    Map.map.setCenter(bounds.getCenter());
	},

  mapCities: function(cities) {
    cities.each(function(city){
      if (!Map.cities[city.location.id]) {
        var point = new GLatLng(city.location.geocoding.geocode.latitude, city.location.geocoding.geocode.longitude);
        Map.cities[city.location.id] = new GMarker(point, {icon:Map.icon(city.location.city_info.signs)});
        Map.cities[city.location.id].html = ''+city.location.city+', '+city.location.state+''+city.location.city_info.count+' Yards
Leans '+city.location.city_info.signs+'
Zoom In';
        Map.mgr.addMarker(Map.cities[city.location.id], 0, Map.zoomSwitch);
      }
    });
  },

  callback: function(data) {
    if(!Map.errors(data)) {
      if(data.locations) data.locations.each(Map.mapLocation);
      if(data.location)     Map.mapLocationAndFocus(data);
    }
  },

  mapLocation: function(data) {
    if (!Map.markers[data.location.id]) {
      var point = new GLatLng(data.location.geocoding.geocode.latitude, data.location.geocoding.geocode.longitude);
      Map.markers[data.location.id] = new GMarker(point, {icon:Map.icon(data.location.signs)});
      Map.markers[data.location.id].html = ''+data.location.street+''+data.location.city+', '+data.location.state+' '+data.location.zip+'
Reported '+Date.parseISO8601(data.location.created_at).strftime('%B %d, %i:%M %p')+'
Edit | Remove';
      Map.mgr.addMarker(Map.markers[data.location.id], Map.zoomSwitch+1);
      return point;
    }
  },

  mapLocationAndFocus: function(data) {
    Map.map.setCenter(Map.mapLocation(data), 14);
    $('map').scrollTo();
    Map.showOverlay.delay(0.5, data.location);
  },

  showOverlay: function(location) {
    Map.markers[location.id].openInfoWindowHtml(Map.markers[location.id].html);
  },

  findLocation: function(location_path) {
    var id = location_path.match(/\d+$/)[0];
    if (Map.markers[id]) {
      Map.showOverlay({id: id});
      $('map').scrollTo();
    } else {
      new Ajax.Request(location_path+'.json', {method: 'get',
        parameters: {callback: 'Map.callback'}} );
    }
  },

  errors: function(data) {
    $$('form fieldset.address ol li.error').invoke('remove');
    if (data.errors) {
      var list = $$('form fieldset.address ol').first();
      data.errors.each(function(error) {
        var message = '';
        if (error[0] != 'base') {
          message = message + error[0] + ' ';
        }
        list.insert({top: '
'+message.capitalize()+error[1]+'
'});
      });
    }
    return data.errors && !data.errors.empty();
  },

  icons: {},

  icon: function(color) {
    if (!Map.icons[color]) {
      Map.icons[color] = new GIcon(G_DEFAULT_ICON);
      Map.icons[color].image = 'http://labs.google.com/ridefinder/images/mm_20_' + color.toLowerCase() + '.png';
      Map.icons[color].shadow = 'http://labs.google.com/ridefinder/images/mm_20_shadow.png';
      Map.icons[color].iconSize = new GSize(12, 20);
      Map.icons[color].shadowSize = new GSize(22, 20);
      Map.icons[color].iconAnchor = new GPoint(6, 20);
      Map.icons[color].infoWindowAnchor = new GPoint(5, 1);
    }
    return Map.icons[color];
  }
}

// Dunno why IE doesn't like dom:loaded.
if (Prototype.Browser.IE) {
  Event.observe(window, "load", Map.show);
} else {
  Event.observe(window, "dom:loaded", Map.show);
}
<commit_msg>Fixing state link, and cleaning up.<commit_after>var Map = {
  markers: [],
  cities: [],
  zoomSwitch: 10,

  show: function() {
    var mapDiv = $('map')
    if (mapDiv && GBrowserIsCompatible()) {
      Map.map = new GMap2(document.getElementById("map"));
      Map.map.setCenter(new GLatLng(42.77309, -86.101754), 12);
      Map.map.enableScrollWheelZoom();
      Map.map.addControl(new GLargeMapControl());
      Map.map.addControl(new GMapTypeControl());
      Map.map.addControl(new GScaleControl());
      Map.map.addControl(new GOverviewMapControl());

      // listen for clicks
      GEvent.addListener(Map.map, 'click', function(overlay, point) {
        if (overlay) {
          // we now need a check here in case the overlay is the info window
          // only our icons will have a .html property
          if (overlay.html) {
            overlay.openInfoWindowHtml(overlay.html);
          }
        } else if (point) {
          //whatever you want to happen if you don't click on an overlay.
        }
      });

      GEvent.addListener(Map.map, "moveend", Map.refreshMarkers);
      GEvent.addListener(Map.map, "zoomend", Map.refreshMarkers);

      Map.mgr = new MarkerManager(Map.map);
      Map.refreshMarkers();
      Event.observe(window, "unload", GUnload);
    }
  },

  refreshMarkers: function() {
    var bounds = Map.map.getBounds();

    if (Map.map.getZoom() > Map.zoomSwitch) {
      new Ajax.Request('/locations.json', {method: 'get',
        parameters: {callback: 'Map.callback',
          northeast: bounds.getNorthEast().toUrlValue(),
          southwest: bounds.getSouthWest().toUrlValue()}} );
    } else {
      Map.getCities(bounds);
		}
  },

	getCities: function(bounds, callback) {
		var parameters = {callback: callback || 'Map.mapCities'};
		if (bounds) {
			parameters.northeast = bounds.getNorthEast().toUrlValue();
			parameters.southwest = bounds.getSouthWest().toUrlValue();
		}
		new Ajax.Request('/cities.json', {method: 'get', parameters: parameters });
	},

	mapCitiesAndZoom: function(cities) {
		var bounds = new GLatLngBounds;
		Map.mapCities(cities).each(function(city) {
			bounds.extend(city.getLatLng());
		});
		Map.map.setZoom(Map.map.getBoundsZoomLevel(bounds));
    Map.map.setCenter(bounds.getCenter());
	},

  mapCities: function(cities) {
    return cities.collect(Map.mapCity, this);
    // });
  },

  mapCity: function(city) {
    if (!Map.cities[city.location.id]) {
      var point = new GLatLng(city.location.geocoding.geocode.latitude, city.location.geocoding.geocode.longitude);
      Map.cities[city.location.id] = new GMarker(point, {icon:Map.icon(city.location.city_info.signs)});
      Map.cities[city.location.id].html = ''+city.location.city+', '+city.location.state+''+city.location.city_info.count+' Yards
Leans '+city.location.city_info.signs+'
Zoom In';
      Map.mgr.addMarker(Map.cities[city.location.id], 0, Map.zoomSwitch);
    }
    return Map.cities[city.location.id];
  },

  callback: function(data) {
    if(!Map.errors(data)) {
      if(data.locations) data.locations.each(Map.mapLocation);
      if(data.location)     Map.mapLocationAndFocus(data);
    }
  },

  mapLocation: function(data) {
    if (!Map.markers[data.location.id]) {
      var point = new GLatLng(data.location.geocoding.geocode.latitude, data.location.geocoding.geocode.longitude);
      Map.markers[data.location.id] = new GMarker(point, {icon:Map.icon(data.location.signs)});
      Map.markers[data.location.id].html = ''+data.location.street+''+data.location.city+', '+data.location.state+' '+data.location.zip+'
Reported '+Date.parseISO8601(data.location.created_at).strftime('%B %d, %i:%M %p')+'
Edit | Remove';
      Map.mgr.addMarker(Map.markers[data.location.id], Map.zoomSwitch+1);
      return point;
    }
  },

  mapLocationAndFocus: function(data) {
    Map.map.setCenter(Map.mapLocation(data), 14);
    $('map').scrollTo();
    Map.showOverlay.delay(0.5, data.location);
  },

  showOverlay: function(location) {
    Map.markers[location.id].openInfoWindowHtml(Map.markers[location.id].html);
  },

  findLocation: function(location_path) {
    var id = location_path.match(/\d+$/)[0];
    if (Map.markers[id]) {
      Map.showOverlay({id: id});
      $('map').scrollTo();
    } else {
      new Ajax.Request(location_path+'.json', {method: 'get',
        parameters: {callback: 'Map.callback'}} );
    }
  },

  errors: function(data) {
    $$('form fieldset.address ol li.error').invoke('remove');
    if (data.errors) {
      var list = $$('form fieldset.address ol').first();
      data.errors.each(function(error) {
        var message = '';
        if (error[0] != 'base') {
          message = message + error[0] + ' ';
        }
        list.insert({top: '
'+message.capitalize()+error[1]+'
'});
      });
    }
    return data.errors && !data.errors.empty();
  },

  icons: {},

  icon: function(color) {
    if (!Map.icons[color]) {
      Map.icons[color] = new GIcon(G_DEFAULT_ICON);
      Map.icons[color].image = 'http://labs.google.com/ridefinder/images/mm_20_' + color.toLowerCase() + '.png';
      Map.icons[color].shadow = 'http://labs.google.com/ridefinder/images/mm_20_shadow.png';
      Map.icons[color].iconSize = new GSize(12, 20);
      Map.icons[color].shadowSize = new GSize(22, 20);
      Map.icons[color].iconAnchor = new GPoint(6, 20);
      Map.icons[color].infoWindowAnchor = new GPoint(5, 1);
    }
    return Map.icons[color];
  }
}

// Dunno why IE doesn't like dom:loaded.
if (Prototype.Browser.IE) {
  Event.observe(window, "load", Map.show);
} else {
  Event.observe(window, "dom:loaded", Map.show);
}
<|endoftext|>


<commit_before>/*
var od = 1000*60*60*24;

var dateToStr = function (d) {
  var y = d.getFullYear().toString(),
    m = '0' + (d.getMonth() +1).toString(),
    s = '0' + d.getDate().toString();
    return y + '-' + m.substring(m.length - 2) + '-' + s.substring(s.length - 2);
};
*/

function showRunChart(s,c,b) {
  var a = c.asOfDate.value.split('-').map(Number),
    selectedDate = new Date(a[0], a[1] - 1, a[2]);

  function clearPlot() {
    d3.selectAll("circle").remove();
    d3.selectAll("svg").remove();
    d3.selectAll(".vtitle").remove();
    d3.selectAll("hr").remove();
    d3.selectAll("h3").remove();
    d3.select("#runchart").remove();

    d3.select("#ctitle")
      .append("h3")
      .attr("align", "center")
      .text(selectedDate.toDateString())
      .on("click", toggleChart);

    d3.select("body")
      .append("div")
      .attr("id", "runchart")
      .attr("style", "display: none");
  }

  function plotData(o,b,c) {
    var w = 800,
      h = 175,
      p = 30,
      xb = b['seriesMin']['x'],
      xt = b['seriesMax']['x'],

      ylb = b['seriesMin']['yLeft'],
      ylt = b['seriesMax']['yLeft'],

      yrb = b['seriesMin']['yRight'],
      yrt = b['seriesMax']['yRight'],

      xl = c['xLabels']['value'].split(','),

      xs = d3.scale.linear().domain([xb, xt]).range([0, w]),
      yls = d3.scale.linear().domain([ylb, ylt]).range([h, 0]),
      yrs = d3.scale.linear().domain([yrb, yrt]).range([h, 0]),

      xls = d3.scale.ordinal().domain(xl).rangePoints([0, w]),

      t = o['seriesName'].replace(/"/g,''),
      sa = 0,

      data = o.data.filter(function(e) { return (e.xTime.split(' ')[0] == dateToStr(selectedDate)); });

    var title = d3.select("#runchart")
      .attr("class", "vtitle")
      .append("hr")
      .append("h3")
      .text("")
      .attr("align", "center");

    var vis = d3.select("#runchart")
      .attr("class", "vis")
      .data([data])
      .append("svg:svg")
      .attr("width", w + p * 4)
      .attr("height", h + p * 2)
      .append("svg:g")
      .attr("transform", "translate(" + p + "," + p + ")");

    vis.append("svg:path")
      .attr("fill","none")
      .attr("stroke","red")
      .attr("stroke-width","2px")
      .attr("d", d3.svg.line()
      .x(function(d) { return xs(d.x); })
      .y(function(d) { return yls(d.yLeft_1); }));

    vis.append("svg:path")
      .attr("fill","none")
      .attr("stroke","blue")
      .attr("stroke-width","2px")
      .attr("d", d3.svg.line()
      .x(function(d) { return xs(d.x); })
      .y(function(d) { return yls(d.yLeft_2); }));

    vis.selectAll("circle.line")
      .data(data)
      .enter().append("svg:circle")
      .attr("stroke","gray")
      .attr("fill","none")
      .attr("cx", function(d) { return xs(d.x); })
      .attr("cy", function(d) { sa = sa + d.yRight_2; return yrs(d.yRight_1); })
      .attr("r", 1.5);

    title.text(t + "  -  " + sa + " patients seen");

  //vertical rules
    var vrules = vis.selectAll("g.vrule")
      .data(xl)
      .enter().append("svg:g")
      .attr("class", "rule");

    vrules.append("svg:line")
      .attr("x1", xls)
      .attr("x2", xls)
      .attr("y1", 0)
      .attr("y2", h - 1);

    vrules.append("svg:text")
      .attr("x", xls)
      .attr("y", h + 3)
      .attr("dy", "1.71em")
      .attr("text-anchor", "start")
      .text(function(d,i) { return d;});

    //horizontal lines
    var hlrules = vis.selectAll("g.hlrule")
      .data(yls.ticks(10))
      .enter().append("svg:g")
      .attr("class", "hlrule");

    hlrules.append("svg:line")
      //.attr("class", function(d) { return d ? null : "axis"; })
      .attr("y1", yls)
      .attr("y2", yls)
      .attr("x1", 0)
      .attr("x2", w + 1);

    hlrules.append("svg:text")
      .attr("y", yls)
      .attr("x", -3)
      .attr("dy", ".35em")
      .attr("stroke", "purple")
      .attr("text-anchor", "end")
      .text(yls.tickFormat(10));

    var hrrules = vis.selectAll("g.hrrule")
      .data(yrs.ticks(5))
      .enter().append("svg:g")
      .attr("class", "hrrule");

    hrrules.append("svg:line")
      //.attr("class", function(d) { return d ? null : "axis"; })
      .attr("y1", yrs)
      .attr("y2", yrs)
      .attr("x1", 0)
      .attr("x2", w + 1);

    hrrules.append("svg:text")
      .attr("y", yrs)
      .attr("x", w + 9)
      .attr("dy", ".35em")
      .attr("stroke", "gray")
      .attr("text-anchor", "start")
      .text(yrs.tickFormat(10));

    d3.select("#runchart").append("p").append("p");

  };

  clearPlot();
  for (var o in s) {
    plotData(s[o],b,c);
  }

}
<commit_msg>collapsable runcharts to toggle<commit_after>/*
var od = 1000*60*60*24;

var dateToStr = function (d) {
  var y = d.getFullYear().toString(),
    m = '0' + (d.getMonth() +1).toString(),
    s = '0' + d.getDate().toString();
    return y + '-' + m.substring(m.length - 2) + '-' + s.substring(s.length - 2);
};
*/

function showRunChart(s,c,b) {
  var a = c.asOfDate.value.split('-').map(Number),
    selectedDate = new Date(a[0], a[1] - 1, a[2]);

  function clearPlot() {
    d3.selectAll("circle").remove();
    d3.selectAll("svg").remove();
    d3.selectAll(".vtitle").remove();
    d3.selectAll("hr").remove();
    d3.selectAll("h3").remove();
    d3.select("#runchart").remove();

    d3.select("#ctitle")
      .append("h3")
      .attr("align", "center")
      .text(selectedDate.toDateString())
      .on("click", toggleChart);

    d3.select("body")
      .append("div")
      .attr("id", "runchart")
      .attr("style", "display: none");
  }

  function plotData(o,b,c) {
    var w = 800,
      h = 175,
      p = 30,
      xb = b['seriesMin']['x'],
      xt = b['seriesMax']['x'],

      ylb = b['seriesMin']['yLeft'],
      ylt = b['seriesMax']['yLeft'],

      yrb = b['seriesMin']['yRight'],
      yrt = b['seriesMax']['yRight'],

      xl = c['xLabels']['value'].split(','),

      xs = d3.scale.linear().domain([xb, xt]).range([0, w]),
      yls = d3.scale.linear().domain([ylb, ylt]).range([h, 0]),
      yrs = d3.scale.linear().domain([yrb, yrt]).range([h, 0]),

      xls = d3.scale.ordinal().domain(xl).rangePoints([0, w]),

      t = o['seriesName'].replace(/"/g,''),
      k = o['seriesKey'],
      sa = 0,

      data = o.data.filter(function(e) { return (e.xTime.split(' ')[0] == dateToStr(selectedDate)); });

    var title = d3.select("#runchart")
      .attr("class", "vtitle")
      .append("h3")
      .text("")
      .attr("align", "center")
      .on("click", function(){ toggleRunChart(k); })
      .append("hr");

    var vis = d3.select("#runchart")
      .data([data])
      .append("svg:svg")
      .attr("id", "rc" + k)
      .attr("width", w + p * 4)
      .attr("height", h + p * 2)
      .attr("style", function() {
        var rv = "display: none";
        if (hiddenRunCharts.indexOf(k) == -1) {
          rv = "display: block";
        }
        return rv;
      })
      .append("svg:g")
      .attr("transform", "translate(" + p + "," + p + ")");

    vis.append("svg:path")
      .attr("fill","none")
      .attr("stroke","red")
      .attr("stroke-width","2px")
      .attr("d", d3.svg.line()
      .x(function(d) { return xs(d.x); })
      .y(function(d) { return yls(d.yLeft_1); }));

    vis.append("svg:path")
      .attr("fill","none")
      .attr("stroke","blue")
      .attr("stroke-width","2px")
      .attr("d", d3.svg.line()
      .x(function(d) { return xs(d.x); })
      .y(function(d) { return yls(d.yLeft_2); }));

    vis.selectAll("circle.line")
      .data(data)
      .enter().append("svg:circle")
      .attr("stroke","gray")
      .attr("fill","none")
      .attr("cx", function(d) { return xs(d.x); })
      .attr("cy", function(d) { sa = sa + d.yRight_2; return yrs(d.yRight_1); })
      .attr("r", 1.5);

    title.text(t + "  -  " + sa + " patients seen");

  //vertical rules
    var vrules = vis.selectAll("g.vrule")
      .data(xl)
      .enter().append("svg:g")
      .attr("class", "rule");

    vrules.append("svg:line")
      .attr("x1", xls)
      .attr("x2", xls)
      .attr("y1", 0)
      .attr("y2", h - 1);

    vrules.append("svg:text")
      .attr("x", xls)
      .attr("y", h + 3)
      .attr("dy", "1.71em")
      .attr("text-anchor", "start")
      .text(function(d,i) { return d;});

    //horizontal lines
    var hlrules = vis.selectAll("g.hlrule")
      .data(yls.ticks(10))
      .enter().append("svg:g")
      .attr("class", "hlrule");

    hlrules.append("svg:line")
      //.attr("class", function(d) { return d ? null : "axis"; })
      .attr("y1", yls)
      .attr("y2", yls)
      .attr("x1", 0)
      .attr("x2", w + 1);

    hlrules.append("svg:text")
      .attr("y", yls)
      .attr("x", -3)
      .attr("dy", ".35em")
      .attr("stroke", "purple")
      .attr("text-anchor", "end")
      .text(yls.tickFormat(10));

    var hrrules = vis.selectAll("g.hrrule")
      .data(yrs.ticks(5))
      .enter().append("svg:g")
      .attr("class", "hrrule");

    hrrules.append("svg:line")
      //.attr("class", function(d) { return d ? null : "axis"; })
      .attr("y1", yrs)
      .attr("y2", yrs)
      .attr("x1", 0)
      .attr("x2", w + 1);

    hrrules.append("svg:text")
      .attr("y", yrs)
      .attr("x", w + 9)
      .attr("dy", ".35em")
      .attr("stroke", "gray")
      .attr("text-anchor", "start")
      .text(yrs.tickFormat(10));

    d3.select("#runchart").append("p").append("p");

  };

  clearPlot();
  for (var o in s) {
    plotData(s[o],b,c);
  }

}

var hiddenRunCharts = [];

function toggleRunChart(k) {
  var ci = hiddenRunCharts.indexOf(k);
  // if k is not in the hiddenRunCharts array,
  // add it and set display to none
  if (ci == -1) {
    hiddenRunCharts.push(k);
    d3.select("#rc" + k)
      .attr("style", "display: none");
  // otherwise, remove it and set display to block
  } else {
    hiddenRunCharts.splice(ci,1);
    d3.select("#rc" + k)
      .attr("style", "display: block");
  }
}
<|endoftext|>


<commit_before>$("select").on('change', function(e){
	if($("#project-budget option:selected").val() == "custom"){
		$("#min_budget_group").show(1000);
		$("#max_budget_group").show(1000);
	}

	if($("#project-category option:selected").val() == "-1")
		$("#project-sub-category").show(500);
	else
		$("#project-sub-category").hide(500);

});

$('input:radio[name="budget-type"]').change(function(){
    if($("#budget-hourly").is(":checked")) {
    	$("#project-duration-select-step").show(500);
    	$("#project-duration-hours-step").show(500);
    } else {
    	$("#project-duration-select-step").hide(500);
    	$("#project-duration-hours-step").hide(500);
    }
});

var objectO = {
	"project" : [],
	"skill"   : [],
	"budget"  : []
}

function postProject(){
	fillProject();
	fillBudget();
	fillSkills();
	doPost();
}

function fillProject(){

	if($("#project-category option:selected").val() == "-1")
		type = $("#project-sub-category").val();
	else
		type = $("#project-category option:selected").html();

	name = $("#project-name").val();
	description = $("#project-description").val();

	objectO.project.push({
		"type" : type,
		"name" : name,
		"description" : description
	});
}

function fillBudget(){
	if($("#budget-hourly").is(":checked"))
		budget_type = "hourly";
	else
		budget_type = "fixed";

	duration = $("project-duration option:selected").html();

	var opt_min = {188 : 10, 5 : 30, 1 : 250, 2 : 750, 3 : 1500, 4 : 3000, 6 : 5000};
	var opt_max = {188 : 30, 5 : 250, 1 : 750, 2 : 1500, 3 : 3000, 4 : 5000, 6 : 10000}

	if($("#project-budget option:selected").val() == "custom"){
		min_budget = ("#project-custom-min-budget").val();
		max_budget = ("#project-custom-max-budget").val();
	} else {
		min_budget = opt_min[$("#project-budget option:selected").val()];
		max_budget = opt_max[$("#project-budget option:selected").val()];
	}

	commitment = $("#project-commitment").val();
	commitment_type = $("#project-commitment-type option:selected").html();

	objectO.budget.push({
		"budget_type"     : budget_type,
		"duration"        : duration,
		"min_budget"  	  : min_budget,
		"max_budget"      : max_budget,
		"commitment"      : commitment,
		"commitment_type" : commitment_type
	});
}

function fillSkills() {
	skills = $("#project-skills").val();
	objectO.skill = skills;
}

function doPost() {
	$.ajax({
		type: "POST",
		url: "../project/post",
		data: JSON.stringify(objectO),
		success: function( data, textStatus, jQxhr ){
			alert("Success");
		},
		error: function( jqXhr, textStatus, errorThrown ){
			alert( errorThrown );
		}
	});
}<commit_msg>modifications to persistence units<commit_after>$("select").on('change', function(e){
	if($("#project-budget option:selected").val() == "custom"){
		$("#min_budget_group").show(1000);
		$("#max_budget_group").show(1000);
	}

	if($("#project-category option:selected").val() == "-1")
		$("#project-sub-category").show(500);
	else
		$("#project-sub-category").hide(500);

});

$('input:radio[name="budget-type"]').change(function(){
    if($("#budget-hourly").is(":checked")) {
    	$("#project-duration-select-step").show(500);
    	$("#project-duration-hours-step").show(500);
    } else {
    	$("#project-duration-select-step").hide(500);
    	$("#project-duration-hours-step").hide(500);
    }
});

var objectO = {
	"project" : [],
	"skill"   : [],
	"budget"  : []
}

function postProject(){
	fillProject();
	fillBudget();
	fillSkills();
	doPost();
}

function fillProject(){

	if($("#project-category option:selected").val() == "-1")
		type = $("#project-sub-category").val();
	else
		type = $("#project-category option:selected").html();

	name = $("#project-name").val();
	description = $("#project-description").val();

	objectO.project.push({
		"type" : type,
		"name" : name,
		"description" : description
	});
}

function fillBudget(){
	if($("#budget-hourly").is(":checked"))
		budget_type = "hourly";
	else
		budget_type = "fixed";

	duration = $("project-duration option:selected").html();

	var opt_min = {188 : 10, 5 : 30, 1 : 250, 2 : 750, 3 : 1500, 4 : 3000, 6 : 5000};
	var opt_max = {188 : 30, 5 : 250, 1 : 750, 2 : 1500, 3 : 3000, 4 : 5000, 6 : 10000}

	if($("#project-budget option:selected").val() == "custom"){
		min_budget = ("#project-custom-min-budget").val();
		max_budget = ("#project-custom-max-budget").val();
	} else {
		min_budget = opt_min[$("#project-budget option:selected").val()];
		max_budget = opt_max[$("#project-budget option:selected").val()];
	}

	commitment = $("#project-commitment").val();
	commitment_type = $("#project-commitment-type option:selected").html();

	currency = $("#project-currency option:selected").html();

	objectO.budget.push({
		"currency"		  : currency,
		"budget_type"     : budget_type,
		"duration"        : duration,
		"min_budget"  	  : min_budget,
		"max_budget"      : max_budget,
		"commitment"      : commitment,
		"commitment_type" : commitment_type
	});
}

function fillSkills() {
	skills = $("#project-skills").val();
	objectO.skill = skills;
}

function doPost() {
	$.ajax({
		type: "POST",
		url: "../project/post",
		data: JSON.stringify(objectO),
		success: function( data, textStatus, jQxhr ){
			alert("Success");
		},
		error: function( jqXhr, textStatus, errorThrown ){
			alert( errorThrown );
		}
	});
}<|endoftext|>


<commit_before>/*jshint esversion: 5, browser: true, varstmt: false, jquery: true */
/*global log*/
/*exported registerAccessInputs*/
//deals with UI for input of token and access codes

//handles code and token input and registers the event handlers for the given fields
/*pass function to check for other validation things as additionalValidation in inputOpts
  return true when either validation is ok or nothing to validate
  return false if the user should be hindered from using the access button
  thefirst argument passed is a function that
    adds/removes invalid and valid classes for input fields
  set an empty string as the presetToken if no token needs to be passed
  the action field of the form is automatically set and doesn't need to have a specific value
*/
function registerAccessInputs(submitOptions, formSelector, inputOpts) {
  //get form element
  var form = $(formSelector);

  //form must be present
  if ($(formSelector).length !== 1) {
    //wrong
    //console.log("accessInput registration error: selectors faulty"); TODO: proper logging
    return;
  }

  //make array if not already
  if (! (submitOptions instanceof Array)) {
    submitOptions = [submitOptions];
  }

  //get elements for submit selectors
  submitOptions.forEach(function(opt) {
    //get element from selector
    opt.element = $(opt.selector);
  });

  //make submitSelector that selects all submit elements and find the elements
  var submitElem = $(submitOptions.map(function(opt) { return opt.selector; }).join(","));

  //states of the two fields
  var fieldStates = {
    token: {
      valid: false, //field validation states
      checkedValues: [] //array of already queried values
    },
    code: {
      valid: "onlyToken",
      checkedValues: []
    }
  };

  //check for selector of code input field or given code for which a hidden field will be created
  var codeFieldElem;
  if (inputOpts.codeFieldSelector) {
    //get selector from ops and find element
    codeFieldElem = $(inputOpts.codeFieldSelector);
  } else if ("presetCode" in inputOpts) {
    //make hidden field above submit button, code is expected to be valid
    submitElem.before(
      "<input type='hidden' class='hidden-code-input not-editor' name='code' value='" +
      inputOpts.presetCode + "'>");

    //is given and ok
    fieldStates.code.valid = "onlyToken";
  } else {
    //wrong
    log("accessInput registration error: missing code data");
    return;
  }

  //check for selector of token input or token will be used as-is
  var presetToken, tokenFieldElem;
  if (inputOpts.tokenFieldSelector) {
    //get field element
    tokenFieldElem = $(inputOpts.tokenFieldSelector);
  } else if ("presetToken" in inputOpts) {
    //get token
    presetToken = inputOpts.presetToken;

    //expect valid token and signify that in validation states
    fieldStates.token.valid = true;
  } else {
    //wrong
    log("accessInput registration error: missing token data");
    return;
  }

  //use empties if elements not found
  codeFieldElem = codeFieldElem || $();
  tokenFieldElem = tokenFieldElem || $();

  //both field elements
  var fieldElem = codeFieldElem.add(tokenFieldElem);

  //true if all fields are valid
  var allOk = false;

  //get the url given the element that the event came ffrom
  function getElementUrl(elem) {
    elem = $(elem);

    //find opt with that selector and return its specified url
    return submitOptions.find(function(opt) { return elem.is(opt.selector); }).url;
  }

  //adds or removes the invalid flag
  function setInputValidState(element, isValid, id) {
    //register state
    if (id) {
      fieldStates[id].valid = isValid;
    }

    //add or remove class
    element[isValid ? "removeClass" : "addClass"]("invalid")
      [isValid ? "addClass" : "removeClass"]("valid");
  }

  //updates the button state after checking the validation state of both fields
  function updateButtonState() {
    //check all validation states
    allOk = fieldStates.token.valid && (fieldStates.code.valid &&
      (fieldStates.code.valid === true || typeof presetToken === "undefined")) &&
      //check with additional validation callback if given
      (typeof inputOpts.additionalValidation === "function" ?
       inputOpts.additionalValidation(setInputValidState) : true);

    //apply to button state
    submitElem[allOk ? "removeClass" : "addClass"]("disabled");
  }

  //check button state also when change happens on additional inputs
  if (typeof inputOpts.additionalInputsSelectors === "string") {
    $(inputOpts.additionalInputsSelectors).on("keyup paste", function() {
      updateButtonState();
    });
  }

  //handles a submit even (pressig a submit button or pressing enter in one of the input fields)
  function handleSubmitEvent(e) {
    //check if still valid
    updateButtonState();

    //do click action if everything valid
    if (allOk) {
      //make url path
      var buttonUrl = getElementUrl(this) + (typeof presetToken === "undefined" ?
        tokenFieldElem.val() : presetToken);

      //send combined get and post request with token and code (if there is a code)
      //use only get request if no code given
      if (fieldStates.code.valid === "onlyToken") { //only token
        //if a click event given
        if (e.type === "click") {
          //change href and allow link click follow
          submitElem.attr("href", buttonUrl);
        } else {
          //change location to url
          window.location.href = buttonUrl;

          //and don't do whatever this event does as an action
          e.preventDefault();
        }
      } else { //token and code
        //populate action url
        form.attr("action", buttonUrl);

        //submit form to send request and follow
        form.submit();

        //stop normal link following behavior
        e.preventDefault();
      }
    } else {
      //don't do anything if not ok and still pressed
      e.preventDefault();
    }
  }

  //token and code input validation
  fieldElem.on("keyup paste checkValidation", function(e) {
    var elem = $(this);

    //get value of current input field and remove any whitespace, make capitalized
    var value = elem.val().replace(/\s/g, "").toUpperCase();
    elem.val(value);

    //check if it's the token or the code field
    var isTokenField = elem.is(tokenFieldElem);
    var fieldId = isTokenField ? "token" : "code";

    //proceed checking only if there is anything filled in
    if (value.length) {
      //add @ or ! if missing one char and not already present
      if (value.length === 8 && ! (value[0] === "@" || value[0] === "!")) {
        //add prefix
        value = (isTokenField ? "@" : "!") + value;
      }

      //must be 8 plus prefix = 9 long and first char must be @ or !
      if (value.length === 9 && (value[0] === "@" || value[0] === "!")) {
        //correct prefix to @ or ! according to field type
        value = (isTokenField ? "@" : "!") + value.substring(1);
        elem.val(value);

        //get checked values for fieldId
        var checkedValues = fieldStates[fieldId].checkedValues;

        //check if we've already checked this value
        if (checkedValues.hasOwnProperty(value)) {
          //if it's null, then we're in the process of asking the server
          if (checkedValues[value] === null) {
            //just wait
            return;
          } else {
            //apply state
            setInputValidState(elem, checkedValues[value], fieldId);
          }
        } else { //ask server
          //make non displaying but invalid because we're waiting for a response
          elem.removeClass("valid invalid");
          fieldStates[fieldId].valid = false;

          //register as present but unknown so we don't ask the server twice
          checkedValues[value] = null;

          //console.log("checked", fieldId, value, e.type);
          //query server for validation
          $.get("/resolution/checkinput/" + value, function(responseData) {
            //set to ok or not
            var valid = responseData.substring(0, 2) === "ok";
            setInputValidState(elem, valid, fieldId);

            //set in check register
            checkedValues[value] = valid;
          })
          .fail(function() {
            //not ok
            setInputValidState(elem, false, fieldId);

            //set in check register
            checkedValues[value] = false;
          })
          .always(function() {
            //update again, (we're in a future callback)
            updateButtonState();
          });
        }
      } else {
        //flag as invalid, is too short
        setInputValidState(elem, false, fieldId);
      }
    } else {
      //ok being empty if in code field, because it's optional
      if (isTokenField) {
        setInputValidState(elem, false, fieldId);
      } else {
        fieldStates.code.valid = "onlyToken"; //onlyToken means ok and empty

        //remove any other valid or invalid classes because the field doesn't matter
        elem.removeClass("valid invalid");
      }
    }

    //update button state with current validation state
    updateButtonState();

    //if the key was an enter key press
    if (e.keyCode === 13) {
      //call submit event (by default the first one, in index it's to the editor)
      handleSubmitEvent.call(submitElem[0], e);
    }
  });

  //on keydown event for enter press in form
  codeFieldElem.on("keydown", function(e) {
    //when enter key was pressed
    if (e.keyCode === 13) {
      //handle a submit event
      handleSubmitEvent.call(submitElem[0], e);
    }
  });

  //submit button click
  submitElem.on("click", handleSubmitEvent)

  //hover over button updates it's state
  .on("mouseover", function() {
    //call validation again
    fieldElem.trigger("checkValidation");
  });

  //initial checks
  fieldElem.trigger("checkValidation");
}

<commit_msg>array find polyfill<commit_after>/*jshint esversion: 5, browser: true, varstmt: false, jquery: true */
/*global log*/
/*exported registerAccessInputs*/
//install Array find polyfill
// https://tc39.github.io/ecma262/#sec-array.prototype.find
if (!Array.prototype.find) {
  Object.defineProperty(Array.prototype, 'find', {
    value: function(predicate) {
     // 1. Let O be ? ToObject(this value).
      if (this == null) {
        throw new TypeError('"this" is null or not defined');
      }

      var o = Object(this);

      // 2. Let len be ? ToLength(? Get(O, "length")).
      var len = o.length >>> 0;

      // 3. If IsCallable(predicate) is false, throw a TypeError exception.
      if (typeof predicate !== 'function') {
        throw new TypeError('predicate must be a function');
      }

      // 4. If thisArg was supplied, let T be thisArg; else let T be undefined.
      var thisArg = arguments[1];

      // 5. Let k be 0.
      var k = 0;

      // 6. Repeat, while k < len
      while (k < len) {
        // a. Let Pk be ! ToString(k).
        // b. Let kValue be ? Get(O, Pk).
        // c. Let testResult be ToBoolean(? Call(predicate, T, « kValue, k, O »)).
        // d. If testResult is true, return kValue.
        var kValue = o[k];
        if (predicate.call(thisArg, kValue, k, o)) {
          return kValue;
        }
        // e. Increase k by 1.
        k++;
      }

      // 7. Return undefined.
      return undefined;
    },
    configurable: true,
    writable: true
  });
}

//deals with UI for input of token and access codes
//handles code and token input and registers the event handlers for the given fields
/*pass function to check for other validation things as additionalValidation in inputOpts
  return true when either validation is ok or nothing to validate
  return false if the user should be hindered from using the access button
  thefirst argument passed is a function that
    adds/removes invalid and valid classes for input fields
  set an empty string as the presetToken if no token needs to be passed
  the action field of the form is automatically set and doesn't need to have a specific value
*/
function registerAccessInputs(submitOptions, formSelector, inputOpts) {
  //get form element
  var form = $(formSelector);

  //form must be present
  if ($(formSelector).length !== 1) {
    //wrong
    //console.log("accessInput registration error: selectors faulty"); TODO: proper logging
    return;
  }

  //make array if not already
  if (! (submitOptions instanceof Array)) {
    submitOptions = [submitOptions];
  }

  //get elements for submit selectors
  submitOptions.forEach(function(opt) {
    //get element from selector
    opt.element = $(opt.selector);
  });

  //make submitSelector that selects all submit elements and find the elements
  var submitElem = $(submitOptions.map(function(opt) { return opt.selector; }).join(","));

  //states of the two fields
  var fieldStates = {
    token: {
      valid: false, //field validation states
      checkedValues: [] //array of already queried values
    },
    code: {
      valid: "onlyToken",
      checkedValues: []
    }
  };

  //check for selector of code input field or given code for which a hidden field will be created
  var codeFieldElem;
  if (inputOpts.codeFieldSelector) {
    //get selector from ops and find element
    codeFieldElem = $(inputOpts.codeFieldSelector);
  } else if ("presetCode" in inputOpts) {
    //make hidden field above submit button, code is expected to be valid
    submitElem.before(
      "<input type='hidden' class='hidden-code-input not-editor' name='code' value='" +
      inputOpts.presetCode + "'>");

    //is given and ok
    fieldStates.code.valid = "onlyToken";
  } else {
    //wrong
    log("accessInput registration error: missing code data");
    return;
  }

  //check for selector of token input or token will be used as-is
  var presetToken, tokenFieldElem;
  if (inputOpts.tokenFieldSelector) {
    //get field element
    tokenFieldElem = $(inputOpts.tokenFieldSelector);
  } else if ("presetToken" in inputOpts) {
    //get token
    presetToken = inputOpts.presetToken;

    //expect valid token and signify that in validation states
    fieldStates.token.valid = true;
  } else {
    //wrong
    log("accessInput registration error: missing token data");
    return;
  }

  //use empties if elements not found
  codeFieldElem = codeFieldElem || $();
  tokenFieldElem = tokenFieldElem || $();

  //both field elements
  var fieldElem = codeFieldElem.add(tokenFieldElem);

  //true if all fields are valid
  var allOk = false;

  //get the url given the element that the event came ffrom
  function getElementUrl(elem) {
    elem = $(elem);

    //find opt with that selector and return its specified url
    return submitOptions.find(function(opt) { return elem.is(opt.selector); }).url;
  }

  //adds or removes the invalid flag
  function setInputValidState(element, isValid, id) {
    //register state
    if (id) {
      fieldStates[id].valid = isValid;
    }

    //add or remove class
    element[isValid ? "removeClass" : "addClass"]("invalid")
      [isValid ? "addClass" : "removeClass"]("valid");
  }

  //updates the button state after checking the validation state of both fields
  function updateButtonState() {
    //check all validation states
    allOk = fieldStates.token.valid && (fieldStates.code.valid &&
      (fieldStates.code.valid === true || typeof presetToken === "undefined")) &&
      //check with additional validation callback if given
      (typeof inputOpts.additionalValidation === "function" ?
       inputOpts.additionalValidation(setInputValidState) : true);

    //apply to button state
    submitElem[allOk ? "removeClass" : "addClass"]("disabled");
  }

  //check button state also when change happens on additional inputs
  if (typeof inputOpts.additionalInputsSelectors === "string") {
    $(inputOpts.additionalInputsSelectors).on("keyup paste", function() {
      updateButtonState();
    });
  }

  //handles a submit even (pressig a submit button or pressing enter in one of the input fields)
  function handleSubmitEvent(e) {
    //check if still valid
    updateButtonState();

    //do click action if everything valid
    if (allOk) {
      //make url path
      var buttonUrl = getElementUrl(this) + (typeof presetToken === "undefined" ?
        tokenFieldElem.val() : presetToken);

      //send combined get and post request with token and code (if there is a code)
      //use only get request if no code given
      if (fieldStates.code.valid === "onlyToken") { //only token
        //if a click event given
        if (e.type === "click") {
          //change href and allow link click follow
          submitElem.attr("href", buttonUrl);
        } else {
          //change location to url
          window.location.href = buttonUrl;

          //and don't do whatever this event does as an action
          e.preventDefault();
        }
      } else { //token and code
        //populate action url
        form.attr("action", buttonUrl);

        //submit form to send request and follow
        form.submit();

        //stop normal link following behavior
        e.preventDefault();
      }
    } else {
      //don't do anything if not ok and still pressed
      e.preventDefault();
    }
  }

  //token and code input validation
  fieldElem.on("keyup paste checkValidation", function(e) {
    var elem = $(this);

    //get value of current input field and remove any whitespace, make capitalized
    var value = elem.val().replace(/\s/g, "").toUpperCase();
    elem.val(value);

    //check if it's the token or the code field
    var isTokenField = elem.is(tokenFieldElem);
    var fieldId = isTokenField ? "token" : "code";

    //proceed checking only if there is anything filled in
    if (value.length) {
      //add @ or ! if missing one char and not already present
      if (value.length === 8 && ! (value[0] === "@" || value[0] === "!")) {
        //add prefix
        value = (isTokenField ? "@" : "!") + value;
      }

      //must be 8 plus prefix = 9 long and first char must be @ or !
      if (value.length === 9 && (value[0] === "@" || value[0] === "!")) {
        //correct prefix to @ or ! according to field type
        value = (isTokenField ? "@" : "!") + value.substring(1);
        elem.val(value);

        //get checked values for fieldId
        var checkedValues = fieldStates[fieldId].checkedValues;

        //check if we've already checked this value
        if (checkedValues.hasOwnProperty(value)) {
          //if it's null, then we're in the process of asking the server
          if (checkedValues[value] === null) {
            //just wait
            return;
          } else {
            //apply state
            setInputValidState(elem, checkedValues[value], fieldId);
          }
        } else { //ask server
          //make non displaying but invalid because we're waiting for a response
          elem.removeClass("valid invalid");
          fieldStates[fieldId].valid = false;

          //register as present but unknown so we don't ask the server twice
          checkedValues[value] = null;

          //console.log("checked", fieldId, value, e.type);
          //query server for validation
          $.get("/resolution/checkinput/" + value, function(responseData) {
            //set to ok or not
            var valid = responseData.substring(0, 2) === "ok";
            setInputValidState(elem, valid, fieldId);

            //set in check register
            checkedValues[value] = valid;
          })
          .fail(function() {
            //not ok
            setInputValidState(elem, false, fieldId);

            //set in check register
            checkedValues[value] = false;
          })
          .always(function() {
            //update again, (we're in a future callback)
            updateButtonState();
          });
        }
      } else {
        //flag as invalid, is too short
        setInputValidState(elem, false, fieldId);
      }
    } else {
      //ok being empty if in code field, because it's optional
      if (isTokenField) {
        setInputValidState(elem, false, fieldId);
      } else {
        fieldStates.code.valid = "onlyToken"; //onlyToken means ok and empty

        //remove any other valid or invalid classes because the field doesn't matter
        elem.removeClass("valid invalid");
      }
    }

    //update button state with current validation state
    updateButtonState();

    //if the key was an enter key press
    if (e.keyCode === 13) {
      //call submit event (by default the first one, in index it's to the editor)
      handleSubmitEvent.call(submitElem[0], e);
    }
  });

  //on keydown event for enter press in form
  codeFieldElem.on("keydown", function(e) {
    //when enter key was pressed
    if (e.keyCode === 13) {
      //handle a submit event
      handleSubmitEvent.call(submitElem[0], e);
    }
  });

  //submit button click
  submitElem.on("click", handleSubmitEvent)

  //hover over button updates it's state
  .on("mouseover", function() {
    //call validation again
    fieldElem.trigger("checkValidation");
  });

  //initial checks
  fieldElem.trigger("checkValidation");
}

<|endoftext|>


<commit_before>// GET /eventos/:eventId/calendar

var calendar = [
	{
		"title" : "Inauguracion",
		"allDay" : false,
		"start" : "2015-11-04T12:00:00",
		"end": "2015-11-04T16:00:00"
	},
	{
		"title" : "Cena",
		"allDay" : false,
		"start" : "2015-11-04T19:00:00",
		"end": "2015-11-04T22:00:00"
	}
];

function gotoStartDate(){
	var ev_start = calendar.events[0].start;

	var ev_end = calendar.events[0];

	for (var i = 1; i < calendar.events.length; i++) {
		ev_end = (calendar.events[i] > ev_end) ? calendar.events[i]:ev_end;
	};

	var todate = new Date();
	var today = todate.toJSON();

	if(ev_start >= today){

		$('#calendar').fullCalendar('gotoDate', ev_start);

	} else if( ev_end >= today){

		$('#calendar').fullCalendar('gotoDate', today);

	} else {

		$('#calendar').fullCalendar('gotoDate', ev_start);

	}
}

$(document).ready(function() {

    // page is now ready, initialize the calendar...

    $('#calendar').fullCalendar({
				lang: 'es',

				header: {
					left: 'prev,next today',
					center: 'title',
					right: 'month,agendaWeek,agendaDay'
				},
				defaultView: 'agendaWeek',
				//events: calendar
    })

    $.get('/eventos/' + idEvento + '/calendar', function(eventos) {
    	console.log(eventos);
    	eventos.forEach(function(evento) {
    		$('#calendar').fullCalendar('renderEvent', evento);
    	});
    });

});<commit_msg>calendar start date<commit_after>// GET /eventos/:eventId/calendar

var calendar = [
	{
		"title" : "Inauguracion",
		"allDay" : false,
		"start" : "2015-11-04T12:00:00",
		"end": "2015-11-04T16:00:00"
	},
	{
		"title" : "Cena",
		"allDay" : false,
		"start" : "2015-11-04T19:00:00",
		"end": "2015-11-04T22:00:00"
	}
];

function gotoStartDate(events){
	var ev_start = events[0].start;

	var ev_end = events[0];

	for (var i = 1; i < events.length; i++) {
		ev_end = (events[i] > ev_end) ? events[i]:ev_end;
	};

	var todate = new Date();
	var today = todate.toJSON();

	if(ev_start >= today){

		$('#calendar').fullCalendar('gotoDate', ev_start);

	} else if( ev_end >= today){

		$('#calendar').fullCalendar('gotoDate', today);

	} else {

		$('#calendar').fullCalendar('gotoDate', ev_start);

	}
}

$(document).ready(function() {

    // page is now ready, initialize the ..

    $('#calendar').fullCalendar({
				lang: 'es',

				header: {
					left: 'prev,next today',
					center: 'title',
					right: 'month,agendaWeek,agendaDay'
				},
				defaultView: 'agendaWeek',
				//events: calendar
    })

    $.get('/eventos/' + idEvento + '/calendar', function(eventos) {
    	console.log(eventos);
    	eventos.forEach(function(evento) {
    		$('#calendar').fullCalendar('renderEvent', evento);
    	});
    	gotoStartDate(eventos);

    });

});<|endoftext|>


<commit_before>// A modal for committing draft changes to a live locale.

apos.define('apostrophe-workflow-commit-modal', {

  extend: 'apostrophe-modal',

  source: 'commit-modal',

  construct: function(self, options) {
    self.manager = options.manager;
    self.beforeShow = function(callback) {
      return apos.areas.saveAllIfNeeded(callback);
    };
    self.saveContent = function(callback) {
      console.log('in saveContent');
      return self.api('commit', { id: options.body.id }, function(result) {
        if (result.status !== 'ok') {
          console.log('error');
          apos.notify('An error occurred.', { type: 'error' });
          return callback(result.status);
        }
        if (result.title) {
          console.log('success');
          apos.notify('%s was committed successfully.', result.title, { type: 'success', dismiss: true });
        } else {
          apos.notify('The document was committed successfully.', { type: 'success', dismiss: true });
          console.log('success');
        }
        var commitId = result.commitId;
        return self.api('editable-locales', {
          id: options.body.id
        }, function(result) {
          console.log('editable-locales response');
          if (result.status !== 'ok') {
            return callback(result.status);
          }
          if (result.locales.length > 1) {
            console.log('passing the baton to export');
            return self.manager.export(commitId, callback);
          }
          return callback(null);
        }, function(err) {
          return callback(err);
        });
      }, function(err) {
        return callback(err);
      });
    };
    // Let the manager know we're done, so the manager can step through these modals
    // for several docs in series if needed
    self.afterHide = function() {
      return options.after();
    };
  }
});
<commit_msg>run quiet<commit_after>// A modal for committing draft changes to a live locale.

apos.define('apostrophe-workflow-commit-modal', {

  extend: 'apostrophe-modal',

  source: 'commit-modal',

  construct: function(self, options) {
    self.manager = options.manager;
    self.beforeShow = function(callback) {
      return apos.areas.saveAllIfNeeded(callback);
    };
    self.saveContent = function(callback) {
      return self.api('commit', { id: options.body.id }, function(result) {
        if (result.status !== 'ok') {
          apos.notify('An error occurred.', { type: 'error' });
          return callback(result.status);
        }
        if (result.title) {
          apos.notify('%s was committed successfully.', result.title, { type: 'success', dismiss: true });
        } else {
          apos.notify('The document was committed successfully.', { type: 'success', dismiss: true });
        }
        var commitId = result.commitId;
        return self.api('editable-locales', {
          id: options.body.id
        }, function(result) {
          if (result.status !== 'ok') {
            return callback(result.status);
          }
          if (result.locales.length > 1) {
            return self.manager.export(commitId, callback);
          }
          return callback(null);
        }, function(err) {
          return callback(err);
        });
      }, function(err) {
        return callback(err);
      });
    };
    // Let the manager know we're done, so the manager can step through these modals
    // for several docs in series if needed
    self.afterHide = function() {
      return options.after();
    };
  }
});
<|endoftext|>


<commit_before>// @flow
import React from 'react'

type FormatProps<V, FormatOptions> = {
  value: V,
  format?: FormatOptions,
  i18n: {
    language: string
  }
}

function
createFormat<V, FormatOptions, P: FormatProps<V, FormatOptions>>
(formatFunction: (language: string, format?: FormatOptions) => (value: V) => string): Class<React$Component<void, P, void>> {
  return class extends React.Component {
    props: P

    render () {
      const { value, format, i18n } = this.props
      const formatter = formatFunction(i18n.language, format)
      return {formatter(value)}
    }
  }
}

export default createFormat
<commit_msg>feat(formats): Add deprecation warning about moved import<commit_after>// @flow
import React from 'react'

type FormatProps<V, FormatOptions> = {
  value: V,
  format?: FormatOptions,
  i18n: {
    language: string
  }
}

function
createFormat<V, FormatOptions, P: FormatProps<V, FormatOptions>>
(formatFunction: (language: string, format?: FormatOptions) => (value: V) => string): Class<React$Component<void, P, void>> {
  console.warn('DEPRECATED (removal in 1.x): createFormat was moved to lingui-react package')

  return class extends React.Component {
    props: P

    render () {
      const { value, format, i18n } = this.props
      const formatter = formatFunction(i18n.language, format)
      return {formatter(value)}
    }
  }
}

export default createFormat
<|endoftext|>


<commit_before>/**
 * Copyright 2013 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

'use strict';

var assert = require('assert');
var googleapis = require('../lib/googleapis.js');
var DefaultTransporter = require('../lib/transporters');

describe('Transporters', function() {

  var defaultUserAgentRE = 'google-api-nodejs-client/\\d+\.\\d+\.\\d+';
  var transporter = new DefaultTransporter();

  it('should set default client user agent if none is set', function() {
    var opts = transporter.configure({});
    var re = new RegExp(defaultUserAgentRE);
    assert(re.test(opts.headers['User-Agent']));
  });

  it('should append default client user agent to the existing user agent', function() {
    var applicationName = 'MyTestApplication-1.0';
    var opts = transporter.configure({
      headers: { 'User-Agent': applicationName }
    });
    var re = new RegExp(applicationName + ' ' + defaultUserAgentRE);
    assert(re.test(opts.headers['User-Agent']));
  });

  it('should automatically add content-type', function() {
    var google = require('../lib/googleapis');
    var datastore = google.datastore({ version: 'v1beta2' });
    var req = datastore.datasets.beginTransaction({ datasetId: 'test' });
    assert.equal(req.headers['content-type'], 'application/json');
  });
});
<commit_msg>Fix test to depend on drive<commit_after>/**
 * Copyright 2013 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

'use strict';

var assert = require('assert');
var googleapis = require('../lib/googleapis.js');
var DefaultTransporter = require('../lib/transporters');

describe('Transporters', function() {

  var defaultUserAgentRE = 'google-api-nodejs-client/\\d+\.\\d+\.\\d+';
  var transporter = new DefaultTransporter();

  it('should set default client user agent if none is set', function() {
    var opts = transporter.configure({});
    var re = new RegExp(defaultUserAgentRE);
    assert(re.test(opts.headers['User-Agent']));
  });

  it('should append default client user agent to the existing user agent', function() {
    var applicationName = 'MyTestApplication-1.0';
    var opts = transporter.configure({
      headers: { 'User-Agent': applicationName }
    });
    var re = new RegExp(applicationName + ' ' + defaultUserAgentRE);
    assert(re.test(opts.headers['User-Agent']));
  });

  it('should automatically add content-type', function() {
    var google = require('../lib/googleapis');
    var drive = google.drive('v2');
    var req = drive.files.list();
    assert.equal(req.headers['content-type'], 'application/json');
  });
});
<|endoftext|>