<commit_before>/*
 * MelonJS Game Engine
 * Copyright (C) 2011 - 2013, Olivier BIOT
 * http://www.melonjs.org
 *
 */
(function () {
    /**
     * video functions
     * There is no constructor function for me.video
     * @namespace me.video
     * @memberOf me
     */
    me.video = (function () {
        // hold public stuff in our apig
        var api = {};

        // internal variables
        var canvas = null;

        var deferResizeId = -1;

        // max display size
        var maxWidth = Infinity;
        var maxHeight = Infinity;

        // default video settings
        var settings = {
            wrapper : undefined,
            renderer : 0, // canvas
            doubleBuffering : false,
            autoScale : false,
            scale : 1.0,
            scaleMethod : "default",
            transparent : false,
            antiAlias : false,
        };

        /**
         * Auto-detect the best renderer to use
         * @ignore
         */
        function autoDetectRenderer(c, width, height, options) {
            try {
                return new me.WebGLRenderer(c, width, height, options);
            }
            catch (e) {
                return new me.CanvasRenderer(c, width, height, options);
            }
        }

        /*
         * PUBLIC STUFF
         */

        /**
         * Base class for Video exception handling.
         * @name Error
         * @class
         * @constructor
         * @memberOf me.video
         * @param {String} msg Error message.
         */
        api.Error = me.Error.extend({
            init : function (msg) {
                this._super(me.Error, "init", [ msg ]);
                this.name = "me.video.Error";
            }
        });

        /**
         * Select the HTML5 Canvas renderer
         * @public
         * @name CANVAS
         * @memberOf me.video
         * @enum {Number}
         */
        api.CANVAS = 0;

        /**
         * Select the WebGL renderer
         * @public
         * @name WEBGL
         * @memberOf me.video
         * @enum {Number}
         */
        api.WEBGL = 1;

        /**
         * Auto-select the renderer (Attempt WebGL first, with fallback to Canvas)
         * @public
         * @name AUTO
         * @memberOf me.video
         * @enum {Number}
         */
        api.AUTO = 2;

        /**
         * init the "video" part

         * return false if initialization failed (canvas not supported)
         * @name init
         * @memberOf me.video
         * @function
         * @param {Number} width the width of the canvas viewport
         * @param {Number} height the height of the canvas viewport
         * @param {Object} [options] The optional video/renderer parameters
         * @param {String} [options.wrapper=document.body] the "div" element name to hold the canvas in the HTML file
         * @param {Number} [options.renderer=me.video.CANVAS] renderer to use.
         * @param {Boolean} [options.doubleBuffering=false] enable/disable double buffering
         * @param {Number|String} [options.scale=1.0] enable scaling of the canvas ('auto' for automatic scaling)
         * @param {Boolean} [options.scaleMethod="default"] ('default','fill','stretch') screen scaling modes
         * @param {Boolean} [options.transparent=false] whether to allow transparent pixels in the front buffer (screen)
         * @param {Boolean} [options.antiAlias=false] whether to enable or not video scaling interpolation
         * @return {Boolean}
         * @example
         * // init the video with a 640x480 canvas
         *   me.video.init(640, 480, {
         *       wrapper: "screen",
         *       renderer: me.video.CANVAS,
         *       scale: 'auto',
         *       scaleMethod: 'default',
         *       doubleBuffering: true
         *   });
         */
        //api.init = function (wrapperid, renderer, game_width, game_height, doublebuffering, scale, aspectRatio) {
        api.init = function (game_width, game_height, options) {
            // ensure melonjs has been properly initialized
            if (!me.initialized) {
                throw new api.Error("me.video.init() called before engine initialization.");
            }

            // revert to default options if not defined
            settings = Object.assign(settings, options || {});

            // sanitize potential given parameters
            settings.doubleBuffering = !!(settings.doubleBuffering);
            settings.autoScale = (settings.scale === "auto") || false;
            settings.scaleMethod = [ "fill", "stretch" ].indexOf(settings.scaleMethod) >= 0 ? settings.scaleMethod : "default";
            settings.transparent = !!(settings.transparent);

            // override renderer settings if &renderer=webgl or &webgl is defined in the URL
            if (typeof (me.game.HASH.renderer) !== "undefined") {
                settings.renderer = me.game.HASH.renderer.match(/WebGL/i) ? api.WEBGL : api.CANVAS;
            }
            if (me.game.HASH.webgl === true) {
                settings.renderer = api.WEBGL;
            }

            // normalize scale
            settings.scale = (settings.autoScale) ? 1.0 : (+settings.scale || 1.0);
            me.sys.scale = new me.Vector2d(settings.scale, settings.scale);

            // force double buffering if scaling is required
            if (settings.autoScale || (settings.scale !== 1.0)) {
                settings.doubleBuffering = true;
            }

            // default scaled size value
            var game_width_zoom = game_width * me.sys.scale.x;
            var game_height_zoom = game_height * me.sys.scale.y;
            settings.zoomX = game_width_zoom;
            settings.zoomY = game_height_zoom;

            //add a channel for the onresize/onorientationchange event
            window.addEventListener(
                "resize",
                throttle(
                    100,
                    false,
                    function (event) {
                        me.event.publish(me.event.WINDOW_ONRESIZE, [ event ]);
                    }
                ),
                false
            );
            window.addEventListener(
                "orientationchange",
                function (event) {
                    me.event.publish(me.event.WINDOW_ONORIENTATION_CHANGE, [ event ]);
                },
                false
            );

            // register to the channel
            me.event.subscribe(
                me.event.WINDOW_ONRESIZE,
                me.video.onresize.bind(me.video)
            );
            me.event.subscribe(
                me.event.WINDOW_ONORIENTATION_CHANGE,
                me.video.onresize.bind(me.video)
            );

            // create the main screen canvas
            canvas = api.createCanvas(game_width_zoom, game_height_zoom, true);

            // add our canvas
            if (options.wrapper) {
                settings.wrapper = document.getElementById(options.wrapper);
            }
            // if wrapperid is not defined (null)
            if (!settings.wrapper) {
                // add the canvas to document.body
                settings.wrapper = document.body;
            }
            settings.wrapper.appendChild(canvas);

            // stop here if not supported
            if (!canvas.getContext) {
                return false;
            }

            switch (settings.renderer) {
                case api.WEBGL:
                    this.renderer = new me.WebGLRenderer(canvas, game_width, game_height, settings);
                    break;
                case api.AUTO:
                    this.renderer = autoDetectRenderer(canvas, game_width, game_height, settings);
                    break;
                default:
                    this.renderer = new me.CanvasRenderer(canvas, game_width, game_height, settings);
                    break;
            }

            // adjust CSS style for High-DPI devices
            var ratio = me.device.getPixelRatio();
            if (ratio > 1) {
                canvas.style.width = (canvas.width / ratio) + "px";
                canvas.style.height = (canvas.height / ratio) + "px";
            }

            // set max the canvas max size if CSS values are defined
            if (window.getComputedStyle) {
                var style = window.getComputedStyle(canvas, null);
                me.video.setMaxSize(parseInt(style.maxWidth, 10), parseInt(style.maxHeight, 10));
            }

            // trigger an initial resize();
            me.video.onresize();

            me.game.init();

            return true;
        };

        /**
         * return the relative (to the page) position of the specified Canvas
         * @name getPos
         * @memberOf me.video
         * @function
         * @param {Canvas} [canvas] system one if none specified
         * @return {me.Vector2d}
         */
        api.getPos = function (c) {
            c = c || this.renderer.getScreenCanvas();
            return (
                c.getBoundingClientRect ?
                c.getBoundingClientRect() : { left : 0, top : 0 }
            );
        };

        /**
         * set the max canvas display size (when scaling)
         * @name setMaxSize
         * @memberOf me.video
         * @function
         * @param {Number} width width
         * @param {Number} height height
         */
        api.setMaxSize = function (w, h) {
            // max display size
            maxWidth = w || Infinity;
            maxHeight = h || Infinity;
        };

        /**
         * Create and return a new Canvas
         * @name createCanvas
         * @memberOf me.video
         * @function
         * @param {Number} width width
         * @param {Number} height height
         * @param {Boolean} [screencanvas=false] set to true if this canvas renders directly to the screen
         * @return {Canvas}
         */
        api.createCanvas = function (width, height, screencanvas) {
            if (width === 0 || height === 0)  {
                throw new api.Error("width or height was zero, Canvas could not be initialized !");
            }

            var _canvas = document.createElement("canvas");

            if ((screencanvas === true) && (navigator.isCocoonJS) && (me.device.android2 !== true)) {
                // enable ScreenCanvas on cocoonJS
                _canvas.screencanvas = true;
            }

            _canvas.width = width || canvas.width;
            _canvas.height = height || canvas.height;

            return _canvas;
        };

        /**
         * return a reference to the wrapper
         * @name getWrapper
         * @memberOf me.video
         * @function
         * @return {Document}
         */
        api.getWrapper = function () {
            return settings.wrapper;
        };

        /**
         * callback for window resize event
         * @ignore
         */
        api.onresize = function () {
            // default (no scaling)
            var scaleX = 1, scaleY = 1;

            // check for orientation information
            if (typeof window.orientation !== "undefined") {
                me.device.orientation = window.orientation;
            }
            else {
                // is this actually not the best option since default "portrait"
                // orientation might vary between for example an ipad and and android tab
                me.device.orientation = (
                    window.outerWidth > window.outerHeight ?
                    90 : 0
                );
            }

            if (settings.autoScale) {
                // get the parent container max size
                var parent = me.video.renderer.getScreenCanvas().parentNode;
                var _max_width = Math.min(maxWidth, parent.width || window.innerWidth);
                var _max_height = Math.min(maxHeight, parent.height || window.innerHeight);
                var designRatio = me.video.renderer.getWidth() / me.video.renderer.getHeight();
                var screenRatio = _max_width / _max_height;
                var sWidth = me.video.renderer.getHeight() * screenRatio;
                var sHeight = me.video.renderer.getWidth() * (_max_height / _max_width);

                if (settings.scaleMethod === "fill") {
                    if (screenRatio < designRatio) {
                        scaleX = scaleY = _max_width / sWidth;
                    }
                    else {
                        scaleX = scaleY = _max_height / sHeight;
                    }

                    document.documentElement.style.overflow = 'hidden';  // hide the overflow in firefox and chrome
                    document.body.scroll = "no"; // hide the overflow in IE
                }
                else if (settings.scaleMethod === "stretch") {
                    // scale the display canvas to fit with the parent container
                    scaleX = _max_width / me.video.renderer.getWidth();
                    scaleY = _max_height / me.video.renderer.getHeight();
                }
                else {
                    // default screen fitting
                     // make sure we maintain the original aspect ratio
                    if (screenRatio < designRatio) {
                        scaleX = scaleY = _max_width / me.video.renderer.getWidth();
                    }
                    else {
                        scaleX = scaleY = _max_height / me.video.renderer.getHeight();
                    }
                }

                // adjust scaling ratio based on the device pixel ratio
                scaleX *= me.device.getPixelRatio();
                scaleY *= me.device.getPixelRatio();

                // scale if required
                if (scaleX !== 1 || scaleY !== 1) {
                    if (deferResizeId >= 0) {
                        // cancel any previous pending resize
                        clearTimeout(deferResizeId);
                    }
                    deferResizeId = me.video.updateDisplaySize.defer(this, scaleX, scaleY);
                    return;
                }
            }
            // make sure we have the correct relative canvas position cached
            me.input._offset = me.video.getPos();
        };

        /**
         * Modify the "displayed" canvas size
         * @name updateDisplaySize
         * @memberOf me.video
         * @function
         * @param {Number} scaleX X scaling multiplier
         * @param {Number} scaleY Y scaling multiplier
         */
        api.updateDisplaySize = function (scaleX, scaleY) {
            // update the global scale variable
            me.sys.scale.set(scaleX, scaleY);

            // renderer resize logic
            this.renderer.resize(scaleX, scaleY);

            me.input._offset = me.video.getPos();
            // clear the timeout id
            deferResizeId = -1;
        };

        // return our api
        return api;
    })();

})();
<commit_msg>Update video.js<commit_after>/*
 * MelonJS Game Engine
 * Copyright (C) 2011 - 2013, Olivier BIOT
 * http://www.melonjs.org
 *
 */
(function () {
    /**
     * video functions
     * There is no constructor function for me.video
     * @namespace me.video
     * @memberOf me
     */
    me.video = (function () {
        // hold public stuff in our apig
        var api = {};

        // internal variables
        var canvas = null;

        var deferResizeId = -1;

        // max display size
        var maxWidth = Infinity;
        var maxHeight = Infinity;

        // default video settings
        var settings = {
            wrapper : undefined,
            renderer : 0, // canvas
            doubleBuffering : false,
            autoScale : false,
            scale : 1.0,
            scaleMethod : "default",
            transparent : false,
            antiAlias : false,
        };

        /**
         * Auto-detect the best renderer to use
         * @ignore
         */
        function autoDetectRenderer(c, width, height, options) {
            try {
                return new me.WebGLRenderer(c, width, height, options);
            }
            catch (e) {
                return new me.CanvasRenderer(c, width, height, options);
            }
        }

        /*
         * PUBLIC STUFF
         */

        /**
         * Base class for Video exception handling.
         * @name Error
         * @class
         * @constructor
         * @memberOf me.video
         * @param {String} msg Error message.
         */
        api.Error = me.Error.extend({
            init : function (msg) {
                this._super(me.Error, "init", [ msg ]);
                this.name = "me.video.Error";
            }
        });

        /**
         * Select the HTML5 Canvas renderer
         * @public
         * @name CANVAS
         * @memberOf me.video
         * @enum {Number}
         */
        api.CANVAS = 0;

        /**
         * Select the WebGL renderer
         * @public
         * @name WEBGL
         * @memberOf me.video
         * @enum {Number}
         */
        api.WEBGL = 1;

        /**
         * Auto-select the renderer (Attempt WebGL first, with fallback to Canvas)
         * @public
         * @name AUTO
         * @memberOf me.video
         * @enum {Number}
         */
        api.AUTO = 2;

        /**
         * init the "video" part

         * return false if initialization failed (canvas not supported)
         * @name init
         * @memberOf me.video
         * @function
         * @param {Number} width the width of the canvas viewport
         * @param {Number} height the height of the canvas viewport
         * @param {Object} [options] The optional video/renderer parameters
         * @param {String} [options.wrapper=document.body] the "div" element name to hold the canvas in the HTML file
         * @param {Number} [options.renderer=me.video.CANVAS] renderer to use.
         * @param {Boolean} [options.doubleBuffering=false] enable/disable double buffering
         * @param {Number|String} [options.scale=1.0] enable scaling of the canvas ('auto' for automatic scaling)
         * @param {Boolean} [options.scaleMethod="default"] ('default','fill','stretch') screen scaling modes
         * @param {Boolean} [options.transparent=false] whether to allow transparent pixels in the front buffer (screen)
         * @param {Boolean} [options.antiAlias=false] whether to enable or not video scaling interpolation
         * @return {Boolean}
         * @example
         * // init the video with a 640x480 canvas
         *   me.video.init(640, 480, {
         *       wrapper: "screen",
         *       renderer: me.video.CANVAS,
         *       scale: 'auto',
         *       scaleMethod: 'default',
         *       doubleBuffering: true
         *   });
         */
        //api.init = function (wrapperid, renderer, game_width, game_height, doublebuffering, scale, aspectRatio) {
        api.init = function (game_width, game_height, options) {
            // ensure melonjs has been properly initialized
            if (!me.initialized) {
                throw new api.Error("me.video.init() called before engine initialization.");
            }

            // revert to default options if not defined
            settings = Object.assign(settings, options || {});

            // sanitize potential given parameters
            settings.doubleBuffering = !!(settings.doubleBuffering);
            settings.autoScale = (settings.scale === "auto") || false;
            settings.scaleMethod = [ "fill", "stretch" ].indexOf(settings.scaleMethod) >= 0 ? settings.scaleMethod : "default";
            settings.transparent = !!(settings.transparent);

            // override renderer settings if &renderer=webgl or &webgl is defined in the URL
            if (typeof (me.game.HASH.renderer) !== "undefined") {
                settings.renderer = me.game.HASH.renderer.match(/WebGL/i) ? api.WEBGL : api.CANVAS;
            }
            if (me.game.HASH.webgl === true) {
                settings.renderer = api.WEBGL;
            }

            // normalize scale
            settings.scale = (settings.autoScale) ? 1.0 : (+settings.scale || 1.0);
            me.sys.scale = new me.Vector2d(settings.scale, settings.scale);

            // force double buffering if scaling is required
            if (settings.autoScale || (settings.scale !== 1.0)) {
                settings.doubleBuffering = true;
            }

            // default scaled size value
            var game_width_zoom = game_width * me.sys.scale.x;
            var game_height_zoom = game_height * me.sys.scale.y;
            settings.zoomX = game_width_zoom;
            settings.zoomY = game_height_zoom;

            //add a channel for the onresize/onorientationchange event
            window.addEventListener(
                "resize",
                throttle(
                    100,
                    false,
                    function (event) {
                        me.event.publish(me.event.WINDOW_ONRESIZE, [ event ]);
                    }
                ),
                false
            );
            window.addEventListener(
                "orientationchange",
                function (event) {
                    me.event.publish(me.event.WINDOW_ONORIENTATION_CHANGE, [ event ]);
                },
                false
            );

            // register to the channel
            me.event.subscribe(
                me.event.WINDOW_ONRESIZE,
                me.video.onresize.bind(me.video)
            );
            me.event.subscribe(
                me.event.WINDOW_ONORIENTATION_CHANGE,
                me.video.onresize.bind(me.video)
            );

            // create the main screen canvas
            canvas = api.createCanvas(game_width_zoom, game_height_zoom, true);

            // add our canvas
            if (options.wrapper) {
                settings.wrapper = document.getElementById(options.wrapper);
            }
            // if wrapperid is not defined (null)
            if (!settings.wrapper) {
                // add the canvas to document.body
                settings.wrapper = document.body;
            }
            settings.wrapper.appendChild(canvas);

            // stop here if not supported
            if (!canvas.getContext) {
                return false;
            }

            switch (settings.renderer) {
                case api.WEBGL:
                    this.renderer = new me.WebGLRenderer(canvas, game_width, game_height, settings);
                    break;
                case api.AUTO:
                    this.renderer = autoDetectRenderer(canvas, game_width, game_height, settings);
                    break;
                default:
                    this.renderer = new me.CanvasRenderer(canvas, game_width, game_height, settings);
                    break;
            }

            // adjust CSS style for High-DPI devices
            var ratio = me.device.getPixelRatio();
            if (ratio > 1) {
                canvas.style.width = (canvas.width / ratio) + "px";
                canvas.style.height = (canvas.height / ratio) + "px";
            }

            // set max the canvas max size if CSS values are defined
            if (window.getComputedStyle) {
                var style = window.getComputedStyle(canvas, null);
                me.video.setMaxSize(parseInt(style.maxWidth, 10), parseInt(style.maxHeight, 10));
            }

            // trigger an initial resize();
            me.video.onresize();

            me.game.init();

            return true;
        };

        /**
         * return the relative (to the page) position of the specified Canvas
         * @name getPos
         * @memberOf me.video
         * @function
         * @param {Canvas} [canvas] system one if none specified
         * @return {me.Vector2d}
         */
        api.getPos = function (c) {
            c = c || this.renderer.getScreenCanvas();
            return (
                c.getBoundingClientRect ?
                c.getBoundingClientRect() : { left : 0, top : 0 }
            );
        };

        /**
         * set the max canvas display size (when scaling)
         * @name setMaxSize
         * @memberOf me.video
         * @function
         * @param {Number} width width
         * @param {Number} height height
         */
        api.setMaxSize = function (w, h) {
            // max display size
            maxWidth = w || Infinity;
            maxHeight = h || Infinity;
        };

        /**
         * Create and return a new Canvas
         * @name createCanvas
         * @memberOf me.video
         * @function
         * @param {Number} width width
         * @param {Number} height height
         * @param {Boolean} [screencanvas=false] set to true if this canvas renders directly to the screen
         * @return {Canvas}
         */
        api.createCanvas = function (width, height, screencanvas) {
            if (width === 0 || height === 0)  {
                throw new api.Error("width or height was zero, Canvas could not be initialized !");
            }

            var _canvas = document.createElement("canvas");

            if ((screencanvas === true) && (navigator.isCocoonJS) && (me.device.android2 !== true)) {
                // enable ScreenCanvas on cocoonJS
                _canvas.screencanvas = true;
            }

            _canvas.width = width || canvas.width;
            _canvas.height = height || canvas.height;

            return _canvas;
        };

        /**
         * return a reference to the wrapper
         * @name getWrapper
         * @memberOf me.video
         * @function
         * @return {Document}
         */
        api.getWrapper = function () {
            return settings.wrapper;
        };

        /**
         * callback for window resize event
         * @ignore
         */
        api.onresize = function () {
            // default (no scaling)
            var scaleX = 1, scaleY = 1;

            // check for orientation information
            if (typeof window.orientation !== "undefined") {
                me.device.orientation = window.orientation;
            }
            else {
                // is this actually not the best option since default "portrait"
                // orientation might vary between for example an ipad and and android tab
                me.device.orientation = (
                    window.outerWidth > window.outerHeight ?
                    90 : 0
                );
            }

            if (settings.autoScale) {
                // get the parent container max size
                var parent = me.video.renderer.getScreenCanvas().parentNode;
                var _max_width = Math.min(maxWidth, parent.width || window.innerWidth);
                var _max_height = Math.min(maxHeight, parent.height || window.innerHeight);
                var designRatio = me.video.renderer.getWidth() / me.video.renderer.getHeight();
                var screenRatio = _max_width / _max_height;
                var sWidth = me.video.renderer.getHeight() * screenRatio;
                var sHeight = me.video.renderer.getWidth() * (_max_height / _max_width);

                if (settings.scaleMethod === "fill") {
                    if (screenRatio < designRatio) {
                        scaleX = scaleY = _max_width / sWidth;
                    }
                    else {
                        scaleX = scaleY = _max_height / sHeight;
                    }

                    document.documentElement.style.overflow = "hidden";  // hide the overflow in firefox and chrome
                    document.body.scroll = "no"; // hide the overflow in IE
                }
                else if (settings.scaleMethod === "stretch") {
                    // scale the display canvas to fit with the parent container
                    scaleX = _max_width / me.video.renderer.getWidth();
                    scaleY = _max_height / me.video.renderer.getHeight();
                }
                else {
                    // default screen fitting
                     // make sure we maintain the original aspect ratio
                    if (screenRatio < designRatio) {
                        scaleX = scaleY = _max_width / me.video.renderer.getWidth();
                    }
                    else {
                        scaleX = scaleY = _max_height / me.video.renderer.getHeight();
                    }
                }

                // adjust scaling ratio based on the device pixel ratio
                scaleX *= me.device.getPixelRatio();
                scaleY *= me.device.getPixelRatio();

                // scale if required
                if (scaleX !== 1 || scaleY !== 1) {
                    if (deferResizeId >= 0) {
                        // cancel any previous pending resize
                        clearTimeout(deferResizeId);
                    }
                    deferResizeId = me.video.updateDisplaySize.defer(this, scaleX, scaleY);
                    return;
                }
            }
            // make sure we have the correct relative canvas position cached
            me.input._offset = me.video.getPos();
        };

        /**
         * Modify the "displayed" canvas size
         * @name updateDisplaySize
         * @memberOf me.video
         * @function
         * @param {Number} scaleX X scaling multiplier
         * @param {Number} scaleY Y scaling multiplier
         */
        api.updateDisplaySize = function (scaleX, scaleY) {
            // update the global scale variable
            me.sys.scale.set(scaleX, scaleY);

            // renderer resize logic
            this.renderer.resize(scaleX, scaleY);

            me.input._offset = me.video.getPos();
            // clear the timeout id
            deferResizeId = -1;
        };

        // return our api
        return api;
    })();

})();
<|endoftext|>


<commit_before>var _ = require('underscore');
var log = require('cdb.log');

var GMAPS_BASE_LAYER_TYPES = ['roadmap', 'gray_roadmap', 'dark_roadmap', 'hybrid', 'satellite', 'terrain'];

var VizJSON = function (vizjson) {
  _.each(Object.keys(vizjson), function (property) {
    this[property] = vizjson[property];
  }, this);

  this.overlays = this.overlays || [];
  this.layers = this.layers || [];

  this._addAttributionOverlay();
};

VizJSON.OVERLAY_TYPES = {
  ZOOM: 'zoom',
  ATTRIBUTION: 'attribution',
  LOADER: 'loader',
  SEARCH: 'search',
  HEADER: 'header',
  LAYER_SELECTOR: 'layer_selector'
};

VizJSON.MAP_PROVIDER_TYPES = {
  GMAPS: 'googlemaps',
  LEAFLET: 'leaflet'
}

VizJSON.prototype.hasZoomOverlay = function () {
  return this.hasOverlay(VizJSON.OVERLAY_TYPES.ZOOM);
};

VizJSON.prototype.hasOverlay = function (overlayType) {
  return _.isObject(this.getOverlayByType(overlayType));
};

VizJSON.prototype.getOverlayByType = function (overlayType) {
  return _.find(this.overlays, function (overlay) {
    return overlay.type === overlayType;
  });
};

VizJSON.prototype.addHeaderOverlay = function (showTitle, showDescription, isShareable) {
  if (!this.hasOverlay(VizJSON.OVERLAY_TYPES.HEADER)) {
    this.overlays.unshift({
      type: VizJSON.OVERLAY_TYPES.HEADER,
      order: 1,
      shareable: isShareable,
      url: this.url,
      options: {
        extra: {
          title: this.title,
          description: this.description,
          show_title: showTitle,
          show_description: showDescription
        }
      }
    });
  }
};

VizJSON.prototype.addLayerSelectorOverlay = function () {
  if (!this.hasOverlay(VizJSON.OVERLAY_TYPES.LAYER_SELECTOR)) {
    this.overlays.push({
      type: VizJSON.OVERLAY_TYPES.LAYER_SELECTOR
    });
  }
};

VizJSON.prototype.addSearchOverlay = function () {
  if (!this.hasOverlay(VizJSON.OVERLAY_TYPES.SEARCH)) {
    this.overlays.push({
      type: VizJSON.OVERLAY_TYPES.SEARCH,
      order: 3
    });
  }
};

VizJSON.prototype.removeOverlay = function (overlayType) {
  for (var i = 0; i < this.overlays.length; ++i) {
    if (this.overlays[i].type === overlayType) {
      this.overlays.splice(i, 1);
      return;
    }
  }
};

VizJSON.prototype.removeLoaderOverlay = function () {
  this.removeOverlay(VizJSON.OVERLAY_TYPES.LOADER);
};

VizJSON.prototype.removeZoomOverlay = function () {
  this.removeOverlay(VizJSON.OVERLAY_TYPES.ZOOM);
};

VizJSON.prototype.removeSearchOverlay = function () {
  this.removeOverlay(VizJSON.OVERLAY_TYPES.SEARCH);
};

VizJSON.prototype._addAttributionOverlay = function () {
  this.overlays.push({
    type: VizJSON.OVERLAY_TYPES.ATTRIBUTION
  });
};

VizJSON.prototype.enforceGMapsBaseLayer = function (gmapsBaseType, gmapsStyle) {
  var isGmapsBaseTypeValid = _.contains(GMAPS_BASE_LAYER_TYPES, gmapsBaseType);
  if (this.map_provider === VizJSON.MAP_PROVIDER_TYPES.LEAFLET && isGmapsBaseTypeValid) {
    if (this.layers) {
      this.layers[0].options.type = 'GMapsBase';
      this.layers[0].options.base_type = gmapsBaseType;
      this.layers[0].options.name = gmapsBaseType;

      if (gmapsStyle) {
        this.layers[0].options.style = typeof gmapsStyle === 'string' ? JSON.parse(gmapsStyle) : gmapsStyle;
      }

      this.map_provider = VizJSON.MAP_PROVIDER_TYPES.GMAPS;
      this.layers[0].options.attribution = ''; // GMaps has its own attribution
    } else {
      log.error('No base map loaded. Using Leaflet.');
    }
  } else {
    log.error('GMaps base_type "' + gmapsBaseType + ' is not supported. Using leaflet.');
  }
};

VizJSON.prototype.setZoom = function (zoom) {
  this.zoom = zoom;
  this.bounds = null;
};

VizJSON.prototype.setCenter = function (center) {
  this.center = center;
  this.bounds = null;
};

VizJSON.prototype.setBounds = function (bounds) {
  this.bounds = bounds;
};

module.exports = VizJSON;
<commit_msg>Missing semicolon<commit_after>var _ = require('underscore');
var log = require('cdb.log');

var GMAPS_BASE_LAYER_TYPES = ['roadmap', 'gray_roadmap', 'dark_roadmap', 'hybrid', 'satellite', 'terrain'];

var VizJSON = function (vizjson) {
  _.each(Object.keys(vizjson), function (property) {
    this[property] = vizjson[property];
  }, this);

  this.overlays = this.overlays || [];
  this.layers = this.layers || [];

  this._addAttributionOverlay();
};

VizJSON.OVERLAY_TYPES = {
  ZOOM: 'zoom',
  ATTRIBUTION: 'attribution',
  LOADER: 'loader',
  SEARCH: 'search',
  HEADER: 'header',
  LAYER_SELECTOR: 'layer_selector'
};

VizJSON.MAP_PROVIDER_TYPES = {
  GMAPS: 'googlemaps',
  LEAFLET: 'leaflet'
};

VizJSON.prototype.hasZoomOverlay = function () {
  return this.hasOverlay(VizJSON.OVERLAY_TYPES.ZOOM);
};

VizJSON.prototype.hasOverlay = function (overlayType) {
  return _.isObject(this.getOverlayByType(overlayType));
};

VizJSON.prototype.getOverlayByType = function (overlayType) {
  return _.find(this.overlays, function (overlay) {
    return overlay.type === overlayType;
  });
};

VizJSON.prototype.addHeaderOverlay = function (showTitle, showDescription, isShareable) {
  if (!this.hasOverlay(VizJSON.OVERLAY_TYPES.HEADER)) {
    this.overlays.unshift({
      type: VizJSON.OVERLAY_TYPES.HEADER,
      order: 1,
      shareable: isShareable,
      url: this.url,
      options: {
        extra: {
          title: this.title,
          description: this.description,
          show_title: showTitle,
          show_description: showDescription
        }
      }
    });
  }
};

VizJSON.prototype.addLayerSelectorOverlay = function () {
  if (!this.hasOverlay(VizJSON.OVERLAY_TYPES.LAYER_SELECTOR)) {
    this.overlays.push({
      type: VizJSON.OVERLAY_TYPES.LAYER_SELECTOR
    });
  }
};

VizJSON.prototype.addSearchOverlay = function () {
  if (!this.hasOverlay(VizJSON.OVERLAY_TYPES.SEARCH)) {
    this.overlays.push({
      type: VizJSON.OVERLAY_TYPES.SEARCH,
      order: 3
    });
  }
};

VizJSON.prototype.removeOverlay = function (overlayType) {
  for (var i = 0; i < this.overlays.length; ++i) {
    if (this.overlays[i].type === overlayType) {
      this.overlays.splice(i, 1);
      return;
    }
  }
};

VizJSON.prototype.removeLoaderOverlay = function () {
  this.removeOverlay(VizJSON.OVERLAY_TYPES.LOADER);
};

VizJSON.prototype.removeZoomOverlay = function () {
  this.removeOverlay(VizJSON.OVERLAY_TYPES.ZOOM);
};

VizJSON.prototype.removeSearchOverlay = function () {
  this.removeOverlay(VizJSON.OVERLAY_TYPES.SEARCH);
};

VizJSON.prototype._addAttributionOverlay = function () {
  this.overlays.push({
    type: VizJSON.OVERLAY_TYPES.ATTRIBUTION
  });
};

VizJSON.prototype.enforceGMapsBaseLayer = function (gmapsBaseType, gmapsStyle) {
  var isGmapsBaseTypeValid = _.contains(GMAPS_BASE_LAYER_TYPES, gmapsBaseType);
  if (this.map_provider === VizJSON.MAP_PROVIDER_TYPES.LEAFLET && isGmapsBaseTypeValid) {
    if (this.layers) {
      this.layers[0].options.type = 'GMapsBase';
      this.layers[0].options.base_type = gmapsBaseType;
      this.layers[0].options.name = gmapsBaseType;

      if (gmapsStyle) {
        this.layers[0].options.style = typeof gmapsStyle === 'string' ? JSON.parse(gmapsStyle) : gmapsStyle;
      }

      this.map_provider = VizJSON.MAP_PROVIDER_TYPES.GMAPS;
      this.layers[0].options.attribution = ''; // GMaps has its own attribution
    } else {
      log.error('No base map loaded. Using Leaflet.');
    }
  } else {
    log.error('GMaps base_type "' + gmapsBaseType + ' is not supported. Using leaflet.');
  }
};

VizJSON.prototype.setZoom = function (zoom) {
  this.zoom = zoom;
  this.bounds = null;
};

VizJSON.prototype.setCenter = function (center) {
  this.center = center;
  this.bounds = null;
};

VizJSON.prototype.setBounds = function (bounds) {
  this.bounds = bounds;
};

module.exports = VizJSON;
<|endoftext|>


<commit_before>/**
 * VML Painter.
 *
 * @module zrender/vml/Painter
 */

define(function (require) {

    var zrLog = require('../core/log');
    var vmlCore = require('./core');

    function parseInt10(val) {
        return parseInt(val, 10);
    }

    /**
     * @alias module:zrender/vml/Painter
     */
    function VMLPainter(root, storage) {

        vmlCore.initVML();

        this.root = root;

        this.storage = storage;

        var vmlViewport = document.createElement('div');

        var vmlRoot = document.createElement('div');

        vmlViewport.style.cssText = 'display:inline-block;overflow:hidden;position:relative;width:300px;height:150px;';

        vmlRoot.style.cssText = 'position:absolute;left:0;top:0;';

        root.appendChild(vmlViewport);

        this._vmlRoot = vmlRoot;
        this._vmlViewport = vmlViewport;

        this.resize();

        // Modify storage
        var oldDelFromMap = storage.delFromMap;
        var oldAddToMap = storage.addToMap;
        storage.delFromMap = function (elId) {
            var el = storage.get(elId);

            oldDelFromMap.call(storage, elId);

            if (el) {
                el.onRemove && el.onRemove(vmlRoot);
            }
        };

        storage.addToMap = function (el) {
            // Displayable already has a vml node
            el.onAdd && el.onAdd(vmlRoot);

            oldAddToMap.call(storage, el);
        };

        this._firstPaint = true;
    }

    VMLPainter.prototype = {

        constructor: VMLPainter,

        /**
         * @return {HTMLDivElement}
         */
        getViewportRoot: function () {
            return this._vmlViewport;
        },

        /**
         * 刷新
         */
        refresh: function () {

            var list = this.storage.getDisplayList(true, true);

            this._paintList(list);
        },

        _paintList: function (list) {
            var vmlRoot = this._vmlRoot;
            for (var i = 0; i < list.length; i++) {
                var el = list[i];
                if (el.invisible || el.ignore) {
                    if (!el.__alreadyNotVisible) {
                        el.onRemove(vmlRoot);
                    }
                    // Set as already invisible
                    el.__alreadyNotVisible = true;
                }
                else {
                    if (el.__alreadyNotVisible) {
                        el.onAdd(vmlRoot);
                    }
                    el.__alreadyNotVisible = false;
                    if (el.__dirty) {
                        el.beforeBrush && el.beforeBrush();
                        (el.brushVML || el.brush)(vmlRoot);
                        el.afterBrush && el.afterBrush();
                    }
                }
                el.__dirty = false;
            }

            if (this._firstPaint) {
                // Detached from document at first time
                // to avoid page refreshing too many times

                // FIXME 如果每次都先 removeChild 可能会导致一些填充和描边的效果改变
                this._vmlViewport.appendChild(vmlRoot);
                this._firstPaint = false;
            }
        },

        resize: function () {
            var width = this._getWidth();
            var height = this._getHeight();

            if (this._width != width && this._height != height) {
                this._width = width;
                this._height = height;

                var vmlViewportStyle = this._vmlViewport.style;
                vmlViewportStyle.width = width + 'px';
                vmlViewportStyle.height = height + 'px';
            }
        },

        dispose: function () {
            this.root.innerHTML = '';

            this._vmlRoot =
            this._vmlViewport =
            this.storage = null;
        },

        getWidth: function () {
            return this._width;
        },

        getHeight: function () {
            return this._height;
        },

        _getWidth: function () {
            var root = this.root;
            var stl = root.currentStyle;

            return ((root.clientWidth || parseInt10(stl.width))
                    - parseInt10(stl.paddingLeft)
                    - parseInt10(stl.paddingRight)) | 0;
        },

        _getHeight: function () {
            var root = this.root;
            var stl = root.currentStyle;

            return ((root.clientHeight || parseInt10(stl.height))
                    - parseInt10(stl.paddingTop)
                    - parseInt10(stl.paddingBottom)) | 0;
        }
    };

    // Not supported methods
    function createMethodNotSupport(method) {
        return function () {
            zrLog('In IE8.0 VML mode painter not support method "' + method + '"');
        };
    }

    var notSupportedMethods = [
        'getLayer', 'insertLayer', 'eachLayer', 'eachBuildinLayer', 'eachOtherLayer', 'getLayers',
        'modLayer', 'delLayer', 'clearLayer', 'toDataURL', 'pathToImage'
    ];

    for (var i = 0; i < notSupportedMethods.length; i++) {
        var name = notSupportedMethods[i];
        VMLPainter.prototype[name] = createMethodNotSupport(name);
    }

    return VMLPainter;
});<commit_msg>VML Painter fix<commit_after>/**
 * VML Painter.
 *
 * @module zrender/vml/Painter
 */

define(function (require) {

    var zrLog = require('../core/log');
    var vmlCore = require('./core');

    function parseInt10(val) {
        return parseInt(val, 10);
    }

    /**
     * @alias module:zrender/vml/Painter
     */
    function VMLPainter(root, storage) {

        vmlCore.initVML();

        this.root = root;

        this.storage = storage;

        var vmlViewport = document.createElement('div');

        var vmlRoot = document.createElement('div');

        vmlViewport.style.cssText = 'display:inline-block;overflow:hidden;position:relative;width:300px;height:150px;';

        vmlRoot.style.cssText = 'position:absolute;left:0;top:0;';

        root.appendChild(vmlViewport);

        this._vmlRoot = vmlRoot;
        this._vmlViewport = vmlViewport;

        this.resize();

        // Modify storage
        var oldDelFromMap = storage.delFromMap;
        var oldAddToMap = storage.addToMap;
        storage.delFromMap = function (elId) {
            var el = storage.get(elId);

            oldDelFromMap.call(storage, elId);

            if (el) {
                el.onRemove && el.onRemove(vmlRoot);
            }
        };

        storage.addToMap = function (el) {
            // Displayable already has a vml node
            el.onAdd && el.onAdd(vmlRoot);

            oldAddToMap.call(storage, el);
        };

        this._firstPaint = true;
    }

    VMLPainter.prototype = {

        constructor: VMLPainter,

        /**
         * @return {HTMLDivElement}
         */
        getViewportRoot: function () {
            return this._vmlViewport;
        },

        /**
         * 刷新
         */
        refresh: function () {

            var list = this.storage.getDisplayList(true, true);

            this._paintList(list);
        },

        _paintList: function (list) {
            var vmlRoot = this._vmlRoot;
            for (var i = 0; i < list.length; i++) {
                var el = list[i];
                if (el.invisible || el.ignore) {
                    if (!el.__alreadyNotVisible) {
                        el.onRemove(vmlRoot);
                    }
                    // Set as already invisible
                    el.__alreadyNotVisible = true;
                }
                else {
                    if (el.__alreadyNotVisible) {
                        el.onAdd(vmlRoot);
                    }
                    el.__alreadyNotVisible = false;
                    if (el.__dirty) {
                        el.beforeBrush && el.beforeBrush();
                        (el.brushVML || el.brush).call(el, vmlRoot);
                        el.afterBrush && el.afterBrush();
                    }
                }
                el.__dirty = false;
            }

            if (this._firstPaint) {
                // Detached from document at first time
                // to avoid page refreshing too many times

                // FIXME 如果每次都先 removeChild 可能会导致一些填充和描边的效果改变
                this._vmlViewport.appendChild(vmlRoot);
                this._firstPaint = false;
            }
        },

        resize: function () {
            var width = this._getWidth();
            var height = this._getHeight();

            if (this._width != width && this._height != height) {
                this._width = width;
                this._height = height;

                var vmlViewportStyle = this._vmlViewport.style;
                vmlViewportStyle.width = width + 'px';
                vmlViewportStyle.height = height + 'px';
            }
        },

        dispose: function () {
            this.root.innerHTML = '';

            this._vmlRoot =
            this._vmlViewport =
            this.storage = null;
        },

        getWidth: function () {
            return this._width;
        },

        getHeight: function () {
            return this._height;
        },

        _getWidth: function () {
            var root = this.root;
            var stl = root.currentStyle;

            return ((root.clientWidth || parseInt10(stl.width))
                    - parseInt10(stl.paddingLeft)
                    - parseInt10(stl.paddingRight)) | 0;
        },

        _getHeight: function () {
            var root = this.root;
            var stl = root.currentStyle;

            return ((root.clientHeight || parseInt10(stl.height))
                    - parseInt10(stl.paddingTop)
                    - parseInt10(stl.paddingBottom)) | 0;
        }
    };

    // Not supported methods
    function createMethodNotSupport(method) {
        return function () {
            zrLog('In IE8.0 VML mode painter not support method "' + method + '"');
        };
    }

    var notSupportedMethods = [
        'getLayer', 'insertLayer', 'eachLayer', 'eachBuildinLayer', 'eachOtherLayer', 'getLayers',
        'modLayer', 'delLayer', 'clearLayer', 'toDataURL', 'pathToImage'
    ];

    for (var i = 0; i < notSupportedMethods.length; i++) {
        var name = notSupportedMethods[i];
        VMLPainter.prototype[name] = createMethodNotSupport(name);
    }

    return VMLPainter;
});<|endoftext|>


<commit_before>let mix = require('laravel-mix');

/*
 |--------------------------------------------------------------------------
 | Mix Asset Management
 |--------------------------------------------------------------------------
 |
 | Mix provides a clean, fluent API for defining some Webpack build steps
 | for your Laravel application. By default, we are compiling the Sass
 | file for the application as well as bundling up all the JS files.
 |
 */

mix
	// cms
	.sass('resources/assets/sass/cms.scss', 'public/assets/cms/css/cms.css')

    // frontend
    .sass('resources/assets/sass/frontend.scss', 'public/assets/frontend/css/frontend.css')

    // wysiwyg
    .sass('resources/assets/sass/wysiwyg.scss', 'public/assets/cms/css/wysiwyg.css')

    .scripts([
        'node_modules/jquery/dist/jquery.min.js',
        'node_modules/jqueryui/jquery-ui.min.js',
        'node_modules/bootstrap-sass/assets/javascripts/bootstrap.min.js',
        'node_modules/moment/min/moment.min.js',
        'node_modules/eonasdan-bootstrap-datetimepicker/build/js/bootstrap-datetimepicker.min.js',
        'node_modules/q/q.js',
        'node_modules/cropper/dist/cropper.min.js',
        'node_modules/dropzone/dist/min/dropzone.min.js',
        'node_modules/nestedSortable/jquery.mjs.nestedSortable.js',
        'resources/assets/js/gateway.js',
        'resources/assets/js/model.js',
        'resources/assets/js/menu.js',
        'resources/assets/js/input/multi-checkbox.js',
        'resources/assets/js/input/aspect-ratio.js',
        'resources/assets/js/input/labeled-multi-checkbox.js',
        'resources/assets/js/input/gallery.js',
        'resources/assets/js/input/cropper.js',
        'resources/assets/js/input/image.js',
        'resources/assets/js/cms.js',
    ], 'public/assets/cms/js/cms.js')

    // auth
    .scripts([
        'node_modules/jquery/dist/jquery.min.js',
        'node_modules/bootstrap-sass/assets/javascripts/bootstrap.min.js',
        'resources/assets/js/auth.js',
    ], 'public/assets/cms/js/auth.js');<commit_msg>updated config for mix<commit_after>let mix = require('laravel-mix');

/*
 |--------------------------------------------------------------------------
 | Mix Asset Management
 |--------------------------------------------------------------------------
 |
 | Mix provides a clean, fluent API for defining some Webpack build steps
 | for your Laravel application. By default, we are compiling the Sass
 | file for the application as well as bundling up all the JS files.
 |
 */

mix
    // cms
    .sass('resources/assets/sass/cms.scss', 'public/assets/cms/css/cms.css')

    // frontend
    .sass('resources/assets/sass/frontend.scss', 'public/assets/frontend/css/frontend.css')

    // wysiwyg
    .sass('resources/assets/sass/wysiwyg.scss', 'public/assets/cms/css/wysiwyg.css')

    .scripts([
        'node_modules/jquery/dist/jquery.min.js',
        'node_modules/jqueryui/jquery-ui.min.js',
        'node_modules/bootstrap-sass/assets/javascripts/bootstrap.min.js',
        'node_modules/moment/min/moment.min.js',
        'node_modules/eonasdan-bootstrap-datetimepicker/build/js/bootstrap-datetimepicker.min.js',
        'node_modules/q/q.js',
        'node_modules/cropper/dist/cropper.min.js',
        'node_modules/dropzone/dist/min/dropzone.min.js',
        'node_modules/nestedSortable/jquery.mjs.nestedSortable.js',
        'resources/assets/js/gateway.js',
        'resources/assets/js/model.js',
        'resources/assets/js/menu.js',
        'resources/assets/js/input/multi-checkbox.js',
        'resources/assets/js/input/aspect-ratio.js',
        'resources/assets/js/input/labeled-multi-checkbox.js',
        'resources/assets/js/input/gallery.js',
        'resources/assets/js/input/cropper.js',
        'resources/assets/js/input/image.js',
        'resources/assets/js/cms.js',
    ], 'public/assets/cms/js/cms.js')

    // auth
    .scripts([
        'node_modules/jquery/dist/jquery.min.js',
        'node_modules/bootstrap-sass/assets/javascripts/bootstrap.min.js',
        'resources/assets/js/auth.js',
    ], 'public/assets/cms/js/auth.js');<|endoftext|>


<commit_before>/*

transitd web UI main js file

@license The MIT License (MIT)
@author Alex <alex@maximum.guru>
@author Serg <sklassen410@gmail.com>
@copyright 2016 Alex
@copyright 2016 Serg

*/

var service = new rpc.ServiceProxy("/jsonrpc", {methods: ['nodeInfo','connectTo','disconnect','listGateways','pollCallStatus','listSessions','startScan','getGraphSince','status']});

function logAppendMessage(type, msg)
{
	if($("#log div").length >= 5)
		$("#log").children().first().remove();
	var div = $("
×
");
	div.find(".logmsg").text(msg);
	div.fadeIn(500).delay(10000).fadeOut(1000);
	$("#log").append(div);
}

function nonBlockingCallWrapper(result, callback)
{
	if(result.callId)
	{
		showSpinner();
		var id = result.callId;
		setTimeout(function(){
			service.pollCallStatus({
				params: [id],
				onSuccess: function(result) {
					hideSpinner();
					nonBlockingCallWrapper(result, callback);
				},
				onException: function(e) {
					hideSpinner();
					logAppendMessage('danger', e);
					return true;
				}
			});
		},1000);
	}
	else
		callback(result);
}

function bootstrap()
{
	if($("#gateways").length>0)
		reloadGateways();
	if($("#sessions").length>0)
		reloadSessions();
	if($("#status").length>0)
		reloadStatus();
	if($(".startScan").length>0)
		$(".startScan").click(startScan);
	if($("#network").length>0)
		startNetworkGraph();
}

var nodeInfo;
$(document).ready(function(){
	$("#gateways").hide();
	$("#sessions").hide();

	$(".navbar li.title").click(function(event) {
		event.preventDefault();
		$("#pageone-about").hide();
		$("#pageone-home").show();
		$(".navbar li.active").removeClass("active");
		$(".navbar li.home").addClass("active");
	});

	$(".navbar li.home").click(function(event) {
		event.preventDefault();
		$("#pageone-about").hide();
		$("#pageone-home").show();
		$(".navbar li.active").removeClass("active");
		$(".navbar li.home").addClass("active");
	});

	$(".navbar li.about").click(function(event) {
		event.preventDefault();
		$("#pageone-home").hide();
		$("#pageone-about").show();
		$(".navbar li.active").removeClass("active");
		$(".navbar li.about").addClass("active");
	});

	service.nodeInfo({
		params: [],
		onSuccess: function(result) {
			nonBlockingCallWrapper(result, function(result) {
				if(result.success==true)
				{
					nodeInfo = result;

					$(document).prop('title', nodeInfo.name);
					$('.navbar-brand').text(nodeInfo.name);

					if(nodeInfo.gateway)
					{
						$('.gateway-hidden').addClass('hidden');
						$('.subscriber-hidden').removeClass('hidden');
					}
					else
					{
						$('.subscriber-hidden').addClass('hidden');
						$('.gateway-hidden').removeClass('hidden');
					}

					if(nodeInfo.authorized)
					{
						$('.authorized-hidden').addClass('hidden');
						$('.unauthorized-hidden').removeClass('hidden');
					}
					else
					{
						$('.unauthorized-hidden').addClass('hidden');
						$('.authorized-hidden').removeClass('hidden');
					}

					if(nodeInfo.gateway || !nodeInfo.authorized)
					{
						$("#gateways").remove();
					}
					else
					{
						$("#gateways").show();
					}

					if(nodeInfo.authorized)
					{
						$("#sessions").show();
					}
					else
					{
						$("#sessions").remove();
					}

					bootstrap();
				}
				else
				{
					logAppendMessage('danger', result.errorMsg);
				}
			});
		},
		onException: function(e) {
			logAppendMessage('danger', e);
			return true;
		}
	});
});

var spinnerCount = 0;
function showSpinner()
{
	if(spinnerCount==0)
		$("#spinner").show();
	spinnerCount++;
}
function hideSpinner()
{
	spinnerCount--;
	if(spinnerCount==0)
		$("#spinner").hide();
}
<commit_msg>Improved web UI spinner indicator<commit_after>/*

transitd web UI main js file

@license The MIT License (MIT)
@author Alex <alex@maximum.guru>
@author Serg <sklassen410@gmail.com>
@copyright 2016 Alex
@copyright 2016 Serg

*/

var serviceProxy = new rpc.ServiceProxy("/jsonrpc", {methods: ['nodeInfo','connectTo','disconnect','listGateways','pollCallStatus','listSessions','startScan','getGraphSince','status']});

// proxy that wraps calls with showSpinner/hideSpinner pair
var service = new Proxy(serviceProxy, {
	get: function(target, name) {
		return function() {

			// manage spinner
			showSpinner();
			if(arguments[0])
			{
				var onSuccess = arguments[0].onSuccess;
				var onException = arguments[0].onException;
				arguments[0].onSuccess = function(a) { var retval; if(onSuccess) retval = onSuccess(a); hideSpinner(); return retval; }
				arguments[0].onException = function(a) { var retval; if(onException) retval = onException(a); hideSpinner(); return retval; }
			}

			// run service proxy function
			var retval = target[name].apply(this, arguments);
			return retval;
		}
	}
});

function logAppendMessage(type, msg)
{
	if($("#log div").length >= 5)
		$("#log").children().first().remove();
	var div = $("
×
");
	div.find(".logmsg").text(msg);
	div.fadeIn(500).delay(10000).fadeOut(1000);
	$("#log").append(div);
}

function nonBlockingCallWrapper(result, callback)
{
	if(result.callId)
	{
		showSpinner();
		var id = result.callId;
		setTimeout(function(){
			service.pollCallStatus({
				params: [id],
				onSuccess: function(result) {
					hideSpinner();
					nonBlockingCallWrapper(result, callback);
				},
				onException: function(e) {
					hideSpinner();
					logAppendMessage('danger', e);
					return true;
				}
			});
		},1000);
	}
	else
		callback(result);
}

function bootstrap()
{
	if($("#gateways").length>0)
		reloadGateways();
	if($("#sessions").length>0)
		reloadSessions();
	if($("#status").length>0)
		reloadStatus();
	if($(".startScan").length>0)
		$(".startScan").click(startScan);
	if($("#network").length>0)
		startNetworkGraph();
}

var nodeInfo;
$(document).ready(function(){
	$("#gateways").hide();
	$("#sessions").hide();

	$(".navbar li.title").click(function(event) {
		event.preventDefault();
		$("#pageone-about").hide();
		$("#pageone-home").show();
		$(".navbar li.active").removeClass("active");
		$(".navbar li.home").addClass("active");
	});

	$(".navbar li.home").click(function(event) {
		event.preventDefault();
		$("#pageone-about").hide();
		$("#pageone-home").show();
		$(".navbar li.active").removeClass("active");
		$(".navbar li.home").addClass("active");
	});

	$(".navbar li.about").click(function(event) {
		event.preventDefault();
		$("#pageone-home").hide();
		$("#pageone-about").show();
		$(".navbar li.active").removeClass("active");
		$(".navbar li.about").addClass("active");
	});

	service.nodeInfo({
		params: [],
		onSuccess: function(result) {
			nonBlockingCallWrapper(result, function(result) {
				if(result.success==true)
				{
					nodeInfo = result;

					$(document).prop('title', nodeInfo.name);
					$('.navbar-brand').text(nodeInfo.name);

					if(nodeInfo.gateway)
					{
						$('.gateway-hidden').addClass('hidden');
						$('.subscriber-hidden').removeClass('hidden');
					}
					else
					{
						$('.subscriber-hidden').addClass('hidden');
						$('.gateway-hidden').removeClass('hidden');
					}

					if(nodeInfo.authorized)
					{
						$('.authorized-hidden').addClass('hidden');
						$('.unauthorized-hidden').removeClass('hidden');
					}
					else
					{
						$('.unauthorized-hidden').addClass('hidden');
						$('.authorized-hidden').removeClass('hidden');
					}

					if(nodeInfo.gateway || !nodeInfo.authorized)
					{
						$("#gateways").remove();
					}
					else
					{
						$("#gateways").show();
					}

					if(nodeInfo.authorized)
					{
						$("#sessions").show();
					}
					else
					{
						$("#sessions").remove();
					}

					bootstrap();
				}
				else
				{
					logAppendMessage('danger', result.errorMsg);
				}
			});
		},
		onException: function(e) {
			logAppendMessage('danger', e);
			return true;
		}
	});
});

var spinnerCount = 0;
function showSpinner()
{
	if(spinnerCount>=0)
		$("#spinner").show();
	spinnerCount++;
}
function hideSpinner()
{
	spinnerCount--;
	if(spinnerCount<=0)
		$("#spinner").hide();
}
<|endoftext|>


<commit_before>/**
 * Created by chief on 16/7/26.
 */

define('index',[],function(){
    var init = function (container){
        var template =  require('html!../../static/page/default.html');

        // 给body添加滚动条优化
        // $("body").mCustomScrollbar({theme:"minimal-dark"});

        $(".nav-toggle").on("click",function(){
            $(".nav-menu").toggleClass("toggle-show");
        })
        var i = 0;
        $(container).html(template);

        var layoutBox = $(container).find('.layoutBox');

        $(container).on('mouseover',function(event){
            var target = $(event.target);
            $(container).find('.widget-menubar').hide();
            var parent = target.closest('.u-drag')||target.closest('.widgetBox');

            if(parent.length>0){
                parent.find('>.widget-menubar').eq(0).show();
            }
            else {
                $(container).find('.widget-menubar').hide();
            }
        }).on('mouseleave',function(event){
            $(container).find('.widget-menubar').hide();
        }).on('click',function(e){
            var target = $(e.target);

            if(target.hasClass('icon-cancel02')){
                target.closest('.widget-menubar').parent().remove();
            }
            if(target.hasClass('uf-pencil')){

                //$(e.target).attr("count",function(){
                //    var i = $(e.target).attr("count");
                //    i++;
                //    return i;
                //});
                //if($(e.target).attr("count") > 1){
                //    return;
                //}
                //layout
                if(target.closest('.u-drag').hasClass('u-row')){
                    if($(target).closest('.u-drag').find('.drag-overlay').length>0){
                        return false;
                    }
                    var layout =  require('html!../page/panel/layout.html');
                    var panelBox =  require('html!../page/panel/panel.html');
                    var container = $(target).closest('.u-drag');
                    container.append(panelBox);
                    container.find('.edit-panel-body').html(layout);

                    container.find(".edit-panel").draggable({containment:"#container-content"});

                    var layout =  require('./panel/layout');

                    layout.init(container);
                    return false;
                }
                //widget
                //if($(target).closest('.u-drag').find('.u-widget').length>0){
                //
                //    return false;
                //}
                if(typeof  panel=='undefined'){
                    return false;
                }
                var panel = $(e.target).parents(".u-widget").attr("panelname");
                var panelTemplate =  require('html!../page/panel/'+panel+'-panel.html');
                var panelBox =  require('html!../page/panel/panel.html');

                var container = $(target).closest('.u-drag');

                container.append(panelBox);
                container.find('.edit-panel-body').html(panelTemplate);

                container.find(".edit-panel").draggable({containment:"#container-content"});

                // 滚动条优化
                $(".edit-panel-body").mCustomScrollbar({theme:"minimal-dark"});

                var widgetViewModel = require('./viewModel/'+panel+'Model.js');

                // console.log( $(e.target).parents(".widget-menubar").closest(".drag-overlay"));
                var editPanel = $(e.target).parents(".widget-menubar").siblings(".drag-overlay").find(".edit-panel")[0];
                // var editPanel = $(".edit-panel")[0];

                ko.applyBindings(widgetViewModel,editPanel);

            }
            if($(target).hasClass("uf-removesymbol")){
                $(e.target).parents(".drag-overlay").siblings(".widget-menubar").find(".uf-pencil").attr("count","0");
                $(target).closest('.drag-overlay').remove();
            }
        });

        require.ensure(['./../trd/jquery-ui/jquery-ui'],function(ui){
            var ui = require('./../trd/jquery-ui/jquery-ui');

            function sortable(elements,p) {

                p = typeof p!="undefined"?p:'.layoutBox .widgetBox';

                $(elements).sortable({
                    placeholder: "ui-portlet-placeholder",
                    connectWith: p,
                    forcePlaceholderSize: true,
                    start:function(i,ui){

                    },
                    stop: function (i,ui) {
                        var target = $(ui.item);

                        if(target.hasClass('u-widget')){
                            //sortable(target.find('.widgetBox'),'.layoutBox .widgetBox');
                        }
                        else {
                            sortable(target.find('.widgetBox'),'.widgetBox');
                        }
                    },
                    over: function () {

                    }
                }).disableSelection();
            };

            sortable(layoutBox);

            $('#downLoad').on('click',function(){
                var html = $('#container-content').html()||$('.layoutBox').html();
                $('.files').val(html);
                $('.downLoadFiles').submit();
                //$.ajax({
                //    url:'/download',
                //    type:'post',
                //    dataType:'json',
                //    data:{
                //        content:$('.layoutBox').html()
                //    },
                //    success:function(res){
                //        console.log(res);
                //    }
                //});
            });

            //$(elements).sortable({
            //    placeholder: "ui-portlet-placeholder",
            //    connectWith: '.widgetBox',
            //    forcePlaceholderSize: true,
            //    start:function(i,ui){
            //        $(this).find('.widget-menubar').hide();
            //    },
            //    stop: function (i,ui) {
            //        var target = $(ui.item);
            //        target.find('.widgetBox').sortable({
            //            placeholder: "ui-portlet-placeholder",
            //            connectWith:  '.widgetBox',
            //            forcePlaceholderSize: true,
            //            start:function(i,ui){
            //                $(this).find('.widget-menubar').hide();
            //            },
            //            stop: function (i,ui) {
            //                var target = $(ui.item);
            //                target.find('.widgetBox').sortable({
            //                    placeholder: "ui-portlet-placeholder",
            //                    connectWith:  '.widgetBox',
            //                    forcePlaceholderSize: true,
            //                    start:function(i,ui){
            //                        $(this).find('.widget-menubar').hide();
            //                    },
            //                    stop: function (i,ui) {
            //                        //console.log(i);
            //                    },
            //                    over: function () {
            //
            //                    }
            //                }).disableSelection();
            //            },
            //            over: function () {
            //
            //            }
            //        }).disableSelection();
            //    },
            //    over: function () {
            //
            //    }
            //}).disableSelection();
        });
    };

    return {
        init:init
    }
});
<commit_msg>fixed:bug<commit_after>/**
 * Created by chief on 16/7/26.
 */

define('index',[],function(){
    var init = function (container){
        var template =  require('html!../../static/page/default.html');

        // 给body添加滚动条优化
        // $("body").mCustomScrollbar({theme:"minimal-dark"});

        $(".nav-toggle").on("click",function(){
            $(".nav-menu").toggleClass("toggle-show");
        })
        var i = 0;
        $(container).html(template);

        var layoutBox = $(container).find('.layoutBox');

        $(container).on('mouseover',function(event){
            var target = $(event.target);
            $(container).find('.widget-menubar').hide();
            var parent = target.closest('.u-drag')||target.closest('.widgetBox');

            if(parent.length>0){
                parent.find('>.widget-menubar').eq(0).show();
            }
            else {
                $(container).find('.widget-menubar').hide();
            }
        }).on('mouseleave',function(event){
            $(container).find('.widget-menubar').hide();
        }).on('click',function(e){
            var target = $(e.target);

            if(target.hasClass('icon-cancel02')){
                target.closest('.widget-menubar').parent().remove();
            }
            if(target.hasClass('uf-pencil')){

                //$(e.target).attr("count",function(){
                //    var i = $(e.target).attr("count");
                //    i++;
                //    return i;
                //});
                //if($(e.target).attr("count") > 1){
                //    return;
                //}
                //layout
                if(target.closest('.u-drag').hasClass('u-row')){
                    if($(target).closest('.u-drag').find('.drag-overlay').length>0){
                        return false;
                    }
                    var layout =  require('html!../page/panel/layout.html');
                    var panelBox =  require('html!../page/panel/panel.html');
                    var container = $(target).closest('.u-drag');
                    container.append(panelBox);
                    container.find('.edit-panel-body').html(layout);

                    container.find(".edit-panel").draggable({containment:"#container-content"});

                    var layout =  require('./panel/layout');

                    layout.init(container);
                    return false;
                }
                //widget
                if($(target).closest('.u-drag').find('.u-widget').length>0){

                    return false;
                }

                var panel = $(e.target).parents(".u-widget").attr("panelname");

                if(typeof  panel=='undefined'){
                    return false;
                }
                var panelTemplate =  require('html!../page/panel/'+panel+'-panel.html');
                var panelBox =  require('html!../page/panel/panel.html');

                var container = $(target).closest('.u-drag');

                container.append(panelBox);
                container.find('.edit-panel-body').html(panelTemplate);

                container.find(".edit-panel").draggable({containment:"#container-content"});

                // 滚动条优化
                $(".edit-panel-body").mCustomScrollbar({theme:"minimal-dark"});

                var widgetViewModel = require('./viewModel/'+panel+'Model.js');

                // console.log( $(e.target).parents(".widget-menubar").closest(".drag-overlay"));
                var editPanel = $(e.target).parents(".widget-menubar").siblings(".drag-overlay").find(".edit-panel")[0];
                // var editPanel = $(".edit-panel")[0];

                ko.applyBindings(widgetViewModel,editPanel);

            }
            if($(target).hasClass("uf-removesymbol")){
                $(e.target).parents(".drag-overlay").siblings(".widget-menubar").find(".uf-pencil").attr("count","0");
                $(target).closest('.drag-overlay').remove();
            }
        });

        require.ensure(['./../trd/jquery-ui/jquery-ui'],function(ui){
            var ui = require('./../trd/jquery-ui/jquery-ui');

            function sortable(elements,p) {

                p = typeof p!="undefined"?p:'.layoutBox .widgetBox';

                $(elements).sortable({
                    placeholder: "ui-portlet-placeholder",
                    connectWith: p,
                    forcePlaceholderSize: true,
                    start:function(i,ui){

                    },
                    stop: function (i,ui) {
                        var target = $(ui.item);

                        if(target.hasClass('u-widget')){
                            //sortable(target.find('.widgetBox'),'.layoutBox .widgetBox');
                        }
                        else {
                            sortable(target.find('.widgetBox'),'.widgetBox');
                        }
                    },
                    over: function () {

                    }
                }).disableSelection();
            };

            sortable(layoutBox);

            $('#downLoad').on('click',function(){
                var html = $('#container-content').html()||$('.layoutBox').html();
                $('.files').val(html);
                $('.downLoadFiles').submit();
                //$.ajax({
                //    url:'/download',
                //    type:'post',
                //    dataType:'json',
                //    data:{
                //        content:$('.layoutBox').html()
                //    },
                //    success:function(res){
                //        console.log(res);
                //    }
                //});
            });

            //$(elements).sortable({
            //    placeholder: "ui-portlet-placeholder",
            //    connectWith: '.widgetBox',
            //    forcePlaceholderSize: true,
            //    start:function(i,ui){
            //        $(this).find('.widget-menubar').hide();
            //    },
            //    stop: function (i,ui) {
            //        var target = $(ui.item);
            //        target.find('.widgetBox').sortable({
            //            placeholder: "ui-portlet-placeholder",
            //            connectWith:  '.widgetBox',
            //            forcePlaceholderSize: true,
            //            start:function(i,ui){
            //                $(this).find('.widget-menubar').hide();
            //            },
            //            stop: function (i,ui) {
            //                var target = $(ui.item);
            //                target.find('.widgetBox').sortable({
            //                    placeholder: "ui-portlet-placeholder",
            //                    connectWith:  '.widgetBox',
            //                    forcePlaceholderSize: true,
            //                    start:function(i,ui){
            //                        $(this).find('.widget-menubar').hide();
            //                    },
            //                    stop: function (i,ui) {
            //                        //console.log(i);
            //                    },
            //                    over: function () {
            //
            //                    }
            //                }).disableSelection();
            //            },
            //            over: function () {
            //
            //            }
            //        }).disableSelection();
            //    },
            //    over: function () {
            //
            //    }
            //}).disableSelection();
        });
    };

    return {
        init:init
    }
});
<|endoftext|>


<commit_before>/*global jQuery, window, document, console, google, MarkerClusterer */

var Codeweek = window.Codeweek || {};

(function ($, Codeweek) {

	'use strict';

	var i,
		map,
		markers = {},
		place,
		placeinfowindow = null,
		overlapSpiderifier = null;

	function createMap(events, lat, lng, zoomVal) {
		var markerClusterOptions = {gridSize: 30, maxZoom: 10},
			map = new google.maps.Map(document.getElementById('events-map'), {
				scrollwheel: false,
				zoom: zoomVal,
				center: new google.maps.LatLng(lat, lng),
				mapTypeControl: false,
				panControl: false,
				zoomControl: true,
				zoomControlOptions: {
					style: google.maps.ZoomControlStyle.LARGE,
					position: google.maps.ControlPosition.RIGHT_BOTTOM
				},
				scaleControl: true,
				streetViewControl: false,
				streetViewControlOptions: {
					position: google.maps.ControlPosition.RIGHT_BOTTOM
				}
			});
		overlapSpiderifier = new OverlappingMarkerSpiderfier(map,
			{markersWontMove: true, markersWontHide: true, keepSpiderfied: true, circleSpiralSwitchover: 5});
		placeinfowindow = new google.maps.InfoWindow({
			content: "loading..."
		});

		overlapSpiderifier.addListener('click', function(marker) {
			placeinfowindow.close();

			var infoWindowContent = '',
				buble_content = '',
				image = '',
				description = '';

			if (marker.image !== "") {
				image += '';
			}

			if (marker.description.length > 150) {
				description = marker.description.substring(0, 150) + '... ';
			} else {
				description = marker.description;
			}

			buble_content = '

' + marker.title + '

' +
							  image +
							  '
' + description +
							  ' More...
';

			placeinfowindow.setContent(buble_content);
			placeinfowindow.open(map, marker);
		});

		for (i = 0; i <= events.length; i = i + 1) {
			if (events[i] && typeof events[i] === 'object') {

				var markTitle = events[i].title,
					map_position = events[i].geoposition.split(","),
					markLat = map_position[0],
					markLng = map_position[1],
					map_event_id = events[i].id,
					map_event_slug = events[i].slug,
					markUrl = "/view/" + map_event_id + "/" + map_event_slug,
					markDesc = events[i].description,
					markImg = events[i].picture;

				markers[map_event_id] = createMarker(markTitle, markLat, markLng, markUrl, markDesc, markImg);
			}
		}

		google.maps.event.addListener(map, 'zoom_changed', function () {
			if (map.getZoom() > 15) {
				map.setZoom(15);
			} else if (map.getZoom() < 3) {
				map.setZoom(3);
			}
		});

		// Bounds for Europe
		var allowedBounds = new google.maps.LatLngBounds(
			new google.maps.LatLng(34.54, -24.58),
			new google.maps.LatLng(71.32, 34.68));

		google.maps.event.addListener(map, 'dragend', function() {
			if (allowedBounds.contains(map.getCenter())) return;

			var c = map.getCenter(),
				x = c.lng(),
				y = c.lat(),
				maxX = allowedBounds.getNorthEast().lng(),
				maxY = allowedBounds.getNorthEast().lat(),
				minX = allowedBounds.getSouthWest().lng(),
				minY = allowedBounds.getSouthWest().lat();

			if (x < minX) x = minX;
			if (x > maxX) x = maxX;
			if (y < minY) y = minY;
			if (y > maxY) y = maxY;

			map.setCenter(new google.maps.LatLng(y, x));
		});

		return new MarkerClusterer(map, markers, markerClusterOptions);
	}

	function createMarker(markTitle, markLat, markLng, markUrl, markDesc, markImg) {
		var myLatLng = new google.maps.LatLng(parseFloat(markLat), parseFloat(markLng)),
			marker = new google.maps.Marker({
				position: myLatLng,
				map: map,
				title: markTitle,
				description: markDesc,
				image: markImg,
				url: markUrl
			});
		overlapSpiderifier.addMarker(marker);

		return marker;
	}

	function setAutocomplete() {

		var input = /** @type {HTMLInputElement} */(
				document.getElementById('search-input')
				),
			options = {
				types: ['(regions)'],
				bounds: new google.maps.Circle({
					center: new google.maps.LatLng(54.977614, 13.292969),
					radius: 2700
				}).getBounds()
			},
			event_list_container = /** @type {HTMLInputElement} */(
				document.getElementById('search-events-link')
				),
			autocomplete = new google.maps.places.Autocomplete(input, options),
			infowindow = new google.maps.InfoWindow();

		autocomplete.bindTo('bounds', map);

		google.maps.event.addListener(autocomplete, 'place_changed', function () {
			infowindow.close();
			place = autocomplete.getPlace();
			if (!place.geometry) {
				return;
			}
			// If the place has a geometry, then present it on a map.
			if (place.geometry.viewport) {
				map.map.fitBounds(place.geometry.viewport);
			} else {
				map.map.setCenter(place.geometry.location);
				map.map.setZoom(17);  // Why 17? Because it looks good.
			}

			var country_code = '',
				country_name = '';
			if (place.address_components) {
				var address = place.address_components;
				for (var j = 0; j <= address.length; j++) {
					if (address[j] && address[j].types[0] === 'country') {
						country_code = address[j].short_name;
						country_name = address[j].long_name;
					}
				}

			}
			infowindow.open(map.map);
			infowindow.close();

		});
	}

	function zoomCountry(country_name) {
		var zoomgeocoder = new google.maps.Geocoder();
		zoomgeocoder.geocode({'address': country_name}, function (results, status) {
			if (status === google.maps.GeocoderStatus.OK) {
				map.map.fitBounds(results[0].geometry.viewport);
				map.map.setCenter(results[0].geometry.location);
				if (map.map.getZoom() < 3) {
					map.map.setZoom(3);
				}
			}
		});
	}

	function setSearchParams(country_code, country_name) {
		var search_button = $('#search-events-link').find('a'),
			search_button_location = search_button.attr('href'),
			new_location = search_button_location.replace(/=[A-Z]{0,2}/, "=" + country_code);

			search_button.attr('href', new_location);
			$('#country').html(country_name);
	}

	function initialize(events, lon, lan) {
		map = createMap(events, lon, lan, 3);
		//setAutocomplete();
		if (location.hash !== '') {
			var country_code = location.hash.replace('#', '').replace('!', '');
			var country = $('#' + country_code);
			if (country.length) {
				var country_name = country[0].innerText;

				zoomCountry(country_name);
				setSearchParams(country_code, country_name);
			}
		} else if (location.pathname !== "/") {
			var current_country = document.getElementById('country').innerHTML;
			zoomCountry(current_country);
		}
	}

	var init = function (past, lon, lan) {

		$(function () {
			// Initialize map on front page
			google.maps.event.addDomListener(window, 'load', function () {
				var ajaxURL = "/api/event/list/?format=json";
				if (past == "yes")
					ajaxURL = ajaxURL + "&past=yes"

				$.ajax({
					type: "GET",
					url: ajaxURL,
					error: function(jqXHR, textStatus, errorThrown) {
						// TODO: Add some error handling for real
						$('#events-map').html('

A dog broke our API. Catz will fix it soon. Always blame the dog!

');
					},
					success: function(data, textStatus, jqXHR) {
						initialize(data, lon, lan);
					}
				});
			});

			$(".country-link").click(function (event) {
				event.preventDefault();
				var that = this,
					country_code = $(that).attr('id'),
					country_name = $(that).attr('data-name');

				zoomCountry(country_name);
				setSearchParams(country_code, country_name);
				document.location.hash = "!" + country_code;
			});

			$("#past-link").click(function (event) {
				var newUrl = $(this).attr('href') + document.location.hash;
				$(this).attr('href', newUrl);
			});

			$("#zoomEU").click(function (event) {
				event.preventDefault();

				zoomCountry('Europe');
				setSearchParams('', 'Europe');
				document.location.hash = '';
			});
		});
	};

	Codeweek.Index = {};
	Codeweek.Index.init = init;

}(jQuery, Codeweek));

<commit_msg>Removed scroll limits on map so users can scroll to the french colonies<commit_after>/*global jQuery, window, document, console, google, MarkerClusterer */

var Codeweek = window.Codeweek || {};

(function ($, Codeweek) {

	'use strict';

	var i,
		map,
		markers = {},
		place,
		placeinfowindow = null,
		overlapSpiderifier = null;

	function createMap(events, lat, lng, zoomVal) {
		var markerClusterOptions = {gridSize: 30, maxZoom: 10},
			map = new google.maps.Map(document.getElementById('events-map'), {
				scrollwheel: false,
				zoom: zoomVal,
				center: new google.maps.LatLng(lat, lng),
				mapTypeControl: false,
				panControl: false,
				zoomControl: true,
				zoomControlOptions: {
					style: google.maps.ZoomControlStyle.LARGE,
					position: google.maps.ControlPosition.RIGHT_BOTTOM
				},
				scaleControl: true,
				streetViewControl: false,
				streetViewControlOptions: {
					position: google.maps.ControlPosition.RIGHT_BOTTOM
				}
			});
		overlapSpiderifier = new OverlappingMarkerSpiderfier(map,
			{markersWontMove: true, markersWontHide: true, keepSpiderfied: true, circleSpiralSwitchover: 5});
		placeinfowindow = new google.maps.InfoWindow({
			content: "loading..."
		});

		overlapSpiderifier.addListener('click', function(marker) {
			placeinfowindow.close();

			var infoWindowContent = '',
				buble_content = '',
				image = '',
				description = '';

			if (marker.image !== "") {
				image += '';
			}

			if (marker.description.length > 150) {
				description = marker.description.substring(0, 150) + '... ';
			} else {
				description = marker.description;
			}

			buble_content = '

' + marker.title + '

' +
							  image +
							  '
' + description +
							  ' More...
';

			placeinfowindow.setContent(buble_content);
			placeinfowindow.open(map, marker);
		});

		for (i = 0; i <= events.length; i = i + 1) {
			if (events[i] && typeof events[i] === 'object') {

				var markTitle = events[i].title,
					map_position = events[i].geoposition.split(","),
					markLat = map_position[0],
					markLng = map_position[1],
					map_event_id = events[i].id,
					map_event_slug = events[i].slug,
					markUrl = "/view/" + map_event_id + "/" + map_event_slug,
					markDesc = events[i].description,
					markImg = events[i].picture;

				markers[map_event_id] = createMarker(markTitle, markLat, markLng, markUrl, markDesc, markImg);
			}
		}

		google.maps.event.addListener(map, 'zoom_changed', function () {
			if (map.getZoom() > 15) {
				map.setZoom(15);
			} else if (map.getZoom() < 3) {
				map.setZoom(3);
			}
		});

		return new MarkerClusterer(map, markers, markerClusterOptions);
	}

	function createMarker(markTitle, markLat, markLng, markUrl, markDesc, markImg) {
		var myLatLng = new google.maps.LatLng(parseFloat(markLat), parseFloat(markLng)),
			marker = new google.maps.Marker({
				position: myLatLng,
				map: map,
				title: markTitle,
				description: markDesc,
				image: markImg,
				url: markUrl
			});
		overlapSpiderifier.addMarker(marker);

		return marker;
	}

	function setAutocomplete() {

		var input = /** @type {HTMLInputElement} */(
				document.getElementById('search-input')
				),
			options = {
				types: ['(regions)'],
				bounds: new google.maps.Circle({
					center: new google.maps.LatLng(54.977614, 13.292969),
					radius: 2700
				}).getBounds()
			},
			event_list_container = /** @type {HTMLInputElement} */(
				document.getElementById('search-events-link')
				),
			autocomplete = new google.maps.places.Autocomplete(input, options),
			infowindow = new google.maps.InfoWindow();

		autocomplete.bindTo('bounds', map);

		google.maps.event.addListener(autocomplete, 'place_changed', function () {
			infowindow.close();
			place = autocomplete.getPlace();
			if (!place.geometry) {
				return;
			}
			// If the place has a geometry, then present it on a map.
			if (place.geometry.viewport) {
				map.map.fitBounds(place.geometry.viewport);
			} else {
				map.map.setCenter(place.geometry.location);
				map.map.setZoom(17);  // Why 17? Because it looks good.
			}

			var country_code = '',
				country_name = '';
			if (place.address_components) {
				var address = place.address_components;
				for (var j = 0; j <= address.length; j++) {
					if (address[j] && address[j].types[0] === 'country') {
						country_code = address[j].short_name;
						country_name = address[j].long_name;
					}
				}

			}
			infowindow.open(map.map);
			infowindow.close();

		});
	}

	function zoomCountry(country_name) {
		var zoomgeocoder = new google.maps.Geocoder();
		zoomgeocoder.geocode({'address': country_name}, function (results, status) {
			if (status === google.maps.GeocoderStatus.OK) {
				map.map.fitBounds(results[0].geometry.viewport);
				map.map.setCenter(results[0].geometry.location);
				if (map.map.getZoom() < 3) {
					map.map.setZoom(3);
				}
			}
		});
	}

	function setSearchParams(country_code, country_name) {
		var search_button = $('#search-events-link').find('a'),
			search_button_location = search_button.attr('href'),
			new_location = search_button_location.replace(/=[A-Z]{0,2}/, "=" + country_code);

			search_button.attr('href', new_location);
			$('#country').html(country_name);
	}

	function initialize(events, lon, lan) {
		map = createMap(events, lon, lan, 3);
		//setAutocomplete();
		if (location.hash !== '') {
			var country_code = location.hash.replace('#', '').replace('!', '');
			var country = $('#' + country_code);
			if (country.length) {
				var country_name = country[0].innerText;

				zoomCountry(country_name);
				setSearchParams(country_code, country_name);
			}
		} else if (location.pathname !== "/") {
			var current_country = document.getElementById('country').innerHTML;
			zoomCountry(current_country);
		}
	}

	var init = function (past, lon, lan) {

		$(function () {
			// Initialize map on front page
			google.maps.event.addDomListener(window, 'load', function () {
				var ajaxURL = "/api/event/list/?format=json";
				if (past == "yes")
					ajaxURL = ajaxURL + "&past=yes"

				$.ajax({
					type: "GET",
					url: ajaxURL,
					error: function(jqXHR, textStatus, errorThrown) {
						// TODO: Add some error handling for real
						$('#events-map').html('

A dog broke our API. Catz will fix it soon. Always blame the dog!

');
					},
					success: function(data, textStatus, jqXHR) {
						initialize(data, lon, lan);
					}
				});
			});

			$(".country-link").click(function (event) {
				event.preventDefault();
				var that = this,
					country_code = $(that).attr('id'),
					country_name = $(that).attr('data-name');

				zoomCountry(country_name);
				setSearchParams(country_code, country_name);
				document.location.hash = "!" + country_code;
			});

			$("#past-link").click(function (event) {
				var newUrl = $(this).attr('href') + document.location.hash;
				$(this).attr('href', newUrl);
			});

			$("#zoomEU").click(function (event) {
				event.preventDefault();

				zoomCountry('Europe');
				setSearchParams('', 'Europe');
				document.location.hash = '';
			});
		});
	};

	Codeweek.Index = {};
	Codeweek.Index.init = init;

}(jQuery, Codeweek));

<|endoftext|>


<commit_before>(function($, eucalyptus) {
  eucalyptus.login = function(args) {
  // select the login form
    var $login = $('html body').find('.templates #login').clone();
    $login.removeClass('templates inactive').addClass('templates active');
    $login.appendTo('html body');

    var $form = $login.find('form');
    // set the login event handler
    $form.find('input[type=submit]').click(function() {
      var param = { username:$form.find('input[name=username]').val(),
		    password:$form.find('input[name=password]').val()
      };
      args.doLogin({ param: param,
        onSuccess: function(args){
          $login.remove();
          eucalyptus.main($.eucaData);
   	},
        onError: function(args){
    	     alert("login failed: "+args);
        }
      });
      return false;
    });
  }
})(jQuery,
   window.eucalyptus ? window.eucalyptus : window.eucalyptus = {});

<commit_msg>set initial focus to username (for now)<commit_after>(function($, eucalyptus) {
  eucalyptus.login = function(args) {
  // select the login form
    var $login = $('html body').find('.templates #login').clone();
    $login.removeClass('templates inactive').addClass('templates active');
    $login.appendTo('html body');

    var $form = $login.find('form');
    // set the login event handler
    $form.find('input[name=username]').focus();
    $form.find('input[type=submit]').click(function() {
      var param = { username:$form.find('input[name=username]').val(),
		    password:$form.find('input[name=password]').val()
      };
      args.doLogin({ param: param,
        onSuccess: function(args){
          $login.remove();
          eucalyptus.main($.eucaData);
   	},
        onError: function(args){
    	     alert("login failed: "+args);
        }
      });
      return false;
    });
  }
})(jQuery,
   window.eucalyptus ? window.eucalyptus : window.eucalyptus = {});

<|endoftext|>


<commit_before>/* Main */

reset();

positionBottom();

$(window).resize(function() {
	positionBottom();
	scrollToBottom();
});

$("#input").focus();

$("#input").keydown(function(e) {
	if (e.which == 13) {  // enter
		e.preventDefault();
	}
	else if (e.which == 32 || e.which == 190) {  // space or period
		val = $(this).val();
		if (val.length) feed(val);

		if (e.which == 190) {  // period
			reset();
		}

		$(this).val("");
		e.preventDefault();

		positionBottom();
		scrollToBottom();
	}
});

/* API functions */

function feed(term) {
	var row = buildHistoryRow(term);
	$("#history").append(row);

	var url = "/_models/" + window.MODEL_ID + "/feed/" + term;
	$.postq("api", url, function(data) {
		updateHistoryRow(row, data);
	});
}

function reset() {
	row = buildHistoryRowEmpty();
	$("#history").append(row);

	var url = "/_models/" + window.MODEL_ID + "/reset";
	$.postq("api", url, function(data) {});
}

/* DOM functions */

function updateHistoryRow(row, prediction) {
	row.children(".prediction").text(prediction);
}

function positionBottom() {
	mainContent = $("#main-content");

	position = mainContent.parent().height() -
	           mainContent.height() -
	           20;  // padding
	position = Math.max(0, position);

	mainContent.offset({"top": position});
}

function scrollToBottom() {
	mainWindow = $("#main-window");
	mainWindow.scrollTop(mainWindow.prop("scrollHeight"));
}

/* Utility functions */

function buildHistoryRow(term) {
	return $("
" +
	          "
" + term + "
" +
	          "
" +
	          "" +
	          "
" +
	          "
");
}

function buildHistoryRowEmpty() {
	return $("
");
}
<commit_msg>Stripping invalid characters<commit_after>/* Main */

reset();

positionBottom();

$(window).resize(function() {
	positionBottom();
	scrollToBottom();
});

$("#input").focus();

$("#input").keydown(function(e) {
	if (e.which == 13) {  // enter
		e.preventDefault();
	}
	else if (e.which == 32 || e.which == 190) {  // space or period
		val = $(this).val();
		if (val.length) feed(val);

		if (e.which == 190) {  // period
			reset();
		}

		$(this).val("");
		e.preventDefault();

		positionBottom();
		scrollToBottom();
	}
});

/* API functions */

function feed(term) {
	// Strip invalid characters
	term = term.replace(/[^\w\s]|_/g, "").replace(/\s+/g, " ");

	var row = buildHistoryRow(term);
	$("#history").append(row);

	var url = "/_models/" + window.MODEL_ID + "/feed/" + term;
	$.postq("api", url, function(data) {
		updateHistoryRow(row, data);
	});
}

function reset() {
	row = buildHistoryRowEmpty();
	$("#history").append(row);

	var url = "/_models/" + window.MODEL_ID + "/reset";
	$.postq("api", url, function(data) {});
}

/* DOM functions */

function updateHistoryRow(row, prediction) {
	row.children(".prediction").text(prediction);
}

function positionBottom() {
	mainContent = $("#main-content");

	position = mainContent.parent().height() -
	           mainContent.height() -
	           20;  // padding
	position = Math.max(0, position);

	mainContent.offset({"top": position});
}

function scrollToBottom() {
	mainWindow = $("#main-window");
	mainWindow.scrollTop(mainWindow.prop("scrollHeight"));
}

/* Utility functions */

function buildHistoryRow(term) {
	return $("
" +
	          "
" + term + "
" +
	          "
" +
	          "" +
	          "
" +
	          "
");
}

function buildHistoryRowEmpty() {
	return $("
");
}
<|endoftext|>