<commit_before>// Copyright (c) 2016 Gamaiel Zavala. All rights reserved. Copyrights licensed under the MIT License.
// See the accompanying LICENSE file for terms.

(function(){

var util = SimpleUtil;

AdventureItem = function(path, opts, cb)
{
    var self = this;

    self.opts = opts || {};
    if (self.opts.render === false) {
        util.set(self.opts, 'attrs.parentNode', null);
    }

    self.listeners = {};

    /*
    // create wrapper and pass to sprite constructor in opts
    self.wrapper = self.opts.parentNode = util.create('div', {
        parentNode: document.body,
        className: 'adv-item'
    });
    */

    AdventureItem.parent.constructor.apply(self, [path, self.opts, function(err, asset)
    {
        if (util.isFunc(cb)) {
            cb(err, self);
        }
    }]);
}

util.extend(AdventureItem, AdventureSprite,
{
    name: '', // set by Adventure.create
    listeners: null,
    dialogIndices: {},

    on: function(eventName, fn, args)
    {
        var self = this;
        if (!self.listeners[eventName]) {
            self.listeners[eventName] = [];
        }
        self.listeners[eventName].push({fn:fn, args:args});
    },

    fire: function(eventName, payload)
    {
        var self = this,
            result = true,
            inv = self.getInventory(),
            selectedItem = inv.getSelectedItem(),
            listeners = util.get(self, 'listeners.' + eventName),
            method;

        payload = payload || {};
        payload.type = eventName;

        switch (eventName) {
            case 'use':
                payload.target = payload.target || (selectedItem !== self ? selectedItem : null);
            break;
        }

        if (eventName == 'use' && selectedItem)
        {
            // run before use
            result = selectedItem.fire('beforeuse',
                util.merge(payload, {target: self}, {clone: true, shallow: true})
            );

            // return early if beforeUse returned false
            if (result === false) {
                return result;
            }
            // otherwise reset result to true
            else {
                result = true;
            }
        }

        if(listeners)
        {
            for(var l=0, ll=listeners.length; l<ll; l++)
            {
                payload.args = listeners[l].args;
                result = result && listeners[l].fn(payload);
            }
        }

        if (result === true)
        {
            method = self.getActionMethod(eventName);
            if (util.isFunc(self[method])) {
                result = self[method](payload);
            }
            if (result === true) {
                self.handleDefault(payload);
            }
        }

        return result;
    },

    handleDefault: function(e)
    {
        var self = this,
            opts = self.opts,
            player = self.getPlayer(),
            eventName = e.type;

        switch(eventName)
        {
            case 'walkto':
                player.walkTo(self);
            break;
            case 'lookat':
                var desc = self.cycleDialog(self.get("description"));
                if (desc) {
                    player.say(util.isFunc(desc) ? desc() : desc);
                }
            break;
            case 'pickup':
                if(opts.pocketable)
                {
                    if(self.isNot("pocketed"))
                    {
                        // pick up the obj if the player is already in place
                        if (player.isAt(self)) {
                            self.addToInventory();
                        }
                        // otherwise walk to the place and set objective
                        else {
                            player.walkTo(self, {action: eventName, target: self});
                        }
                    }
                    else {
                        player.say(
                            "I'll use "
                            + (self.name.substr(self.name.length-1) == "s" ? "these " : "this ")
                            + self.getTitle()
                            + "."
                        );
                        self.setActive();
                    }
                }
                else
                {
                    player.say("I can't pick that up.");
                }
            break;
            case 'use':
                var target = e.target,
                    //inv = self.getInventory(),
                    //numItems = inv.count(),
                    msg;

                if (true/*numItems*/) {
                    if (target) {
                        if (target.name == self.name) {
                            msg = "I can't use it on itself.";
                        } else if (!e.alt) {
                            e.target = self;
                            e.alt = true;
                            target.fire(eventName, e);
                        } else {
                            msg = player.cycleDialog(["That doesn't work.", "Not so much.",
                                "Umm. No.", "What's the point.", "I don't get it.", "Come again?"], "nouse");
                        }
                    } else {
                        //msg = "Select something to use first.";
                    }
                } else {
                    msg =  "I have nothing to use.";
                }

                if (msg) {
                    player.say(msg);
                }
            break;
            case 'apply':
                player.say("Nothing happened.");
            break;
            case 'talkto':
                player.say(player.cycleDialog(["I can't talk to that.", "What would I say?", "Umm... hello?"], "talk"));
            break;
        }
    },

    getWalkTo: function()
    {
        var self = this,
            opts = self.opts,
            walkTo = opts.walkTo || [-5, parseInt(self.getHeight()/2, 10)],
            coords = self.getXY(),
            x = coords[0] + walkTo[0],
            y = coords[1] + walkTo[1];

        return [x, y];
    },

    cycleDialog: function(d, name, loop)
    {
        var self = this;
        if(util.isArray(d)){
            var n = name || self.name,
                dIndex = self.dialogIndices[n] || 0,
                dLen = d.length;

            d = d[dIndex];

            if(++dIndex === dLen) {
                dIndex = loop !== false ? 0 : dIndex - 1;
            }
            self.dialogIndices[n] = dIndex;
        }

        return d;
    },

    setDesc: function(d)
    {
        this.set("description", d);
    },

    getDesc: function()
    {
        var self = this;
        return self.get("description", self.opts.description);
    },

    getTitle: function()
    {
        var self = this;
        return self.attrs.title || self.opts.title || self.name;
    },

    setTitle: function(t)
    {
        var self = this;
        if (t && t !== self.attrs.title) {
            self.attrs.title = t;
            self.updateStatus();
        }
        return t;
    },

    // TODO addSetter('pocketed', bind(addToInventory))
    setPocketed: function(pocketed)
    {
        var self = this;
        if (self.isNot("pocketed")) {
            self.attrs.pocketed = true;
            return self.addToInventory();
        }
        return pocketed;
    },

    // supplemented by Adventure
    getInventory: function()
    {
    },

    addToInventory: function()
    {
    },

    getTileSize: function()
    {
    },

    setActive: function()
    {
    },

    getPlayer: function()
    {
    },

    updateStatus: function()
    {
    }
});

}());
<commit_msg>Add init method<commit_after>// Copyright (c) 2016 Gamaiel Zavala. All rights reserved. Copyrights licensed under the MIT License.
// See the accompanying LICENSE file for terms.

(function(){

var util = SimpleUtil;

AdventureItem = function(path, opts, cb)
{
    var self = this;

    self.opts = opts || {};
    if (self.opts.render === false) {
        util.set(self.opts, 'attrs.parentNode', null);
    }

    self.listeners = {};

    /*
    // create wrapper and pass to sprite constructor in opts
    self.wrapper = self.opts.parentNode = util.create('div', {
        parentNode: document.body,
        className: 'adv-item'
    });
    */

    AdventureItem.parent.constructor.apply(self, [path, self.opts, function(err, asset)
    {
        if (util.isFunc(cb)) {
            cb(err, self);
        }
    }]);
}

util.extend(AdventureItem, AdventureSprite,
{
    name: '', // set by Adventure.create
    listeners: {},
    dialogIndices: {},

    init: function()
    {
    },

    on: function(eventName, fn, args)
    {
        var self = this;
        if (!self.listeners[eventName]) {
            self.listeners[eventName] = [];
        }
        self.listeners[eventName].push({fn:fn, args:args});
    },

    fire: function(eventName, payload)
    {
        var self = this,
            result = true,
            inv = self.getInventory(),
            selectedItem = inv && inv.getSelectedItem(),
            listeners = self.listeners[eventName],
            method;

        payload = payload || {};
        payload.type = eventName;

        switch (eventName) {
            case 'use':
                payload.target = payload.target || (selectedItem !== self ? selectedItem : null);
            break;
        }

        if (eventName == 'use' && selectedItem)
        {
            // run before use
            result = selectedItem.fire('beforeuse',
                util.merge(payload, {target: self}, {clone: true, shallow: true})
            );

            // return early if beforeUse returned false
            if (result === false) {
                return result;
            }
            // otherwise reset result to true
            else {
                result = true;
            }
        }

        if(listeners)
        {
            for(var l=0, ll=listeners.length; l<ll; l++)
            {
                payload.args = listeners[l].args;
                result = result && listeners[l].fn(payload);
            }
        }

        if (result === true)
        {
            method = self.getActionMethod(eventName);
            if (util.isFunc(self[method])) {
                result = self[method](payload);
            }
            if (result === true) {
                self.handleDefault(payload);
            }
        }

        return result;
    },

    handleDefault: function(e)
    {
        var self = this,
            opts = self.opts,
            player = self.getPlayer(),
            eventName = e.type;

        switch(eventName)
        {
            case 'walkto':
                player.walkTo(self);
            break;
            case 'lookat':
                var desc = self.cycleDialog(self.get("description"));
                if (desc) {
                    player.say(util.isFunc(desc) ? desc() : desc);
                }
            break;
            case 'pickup':
                if(opts.pocketable)
                {
                    if(self.isNot("pocketed"))
                    {
                        // pick up the obj if the player is already in place
                        if (player.isAt(self)) {
                            self.addToInventory();
                        }
                        // otherwise walk to the place and set objective
                        else {
                            player.walkTo(self, {action: eventName, target: self});
                        }
                    }
                    else {
                        player.say(
                            "I'll use "
                            + (self.name.substr(self.name.length-1) == "s" ? "these " : "this ")
                            + self.getTitle()
                            + "."
                        );
                        self.setActive();
                    }
                }
                else
                {
                    player.say("I can't pick that up.");
                }
            break;
            case 'use':
                var target = e.target,
                    //inv = self.getInventory(),
                    //numItems = inv.count(),
                    msg;

                if (true/*numItems*/) {
                    if (target) {
                        if (target.name == self.name) {
                            msg = "I can't use it on itself.";
                        } else if (!e.alt) {
                            e.target = self;
                            e.alt = true;
                            target.fire(eventName, e);
                        } else {
                            msg = player.cycleDialog(["That doesn't work.", "Not so much.",
                                "Umm. No.", "What's the point.", "I don't get it.", "Come again?"], "nouse");
                        }
                    } else {
                        //msg = "Select something to use first.";
                    }
                } else {
                    msg =  "I have nothing to use.";
                }

                if (msg) {
                    player.say(msg);
                }
            break;
            case 'apply':
                player.say("Nothing happened.");
            break;
            case 'talkto':
                player.say(player.cycleDialog(["I can't talk to that.", "What would I say?", "Umm... hello?"], "talk"));
            break;
        }
    },

    getWalkTo: function()
    {
        var self = this,
            opts = self.opts,
            walkTo = opts.walkTo || [-5, parseInt(self.getHeight()/2, 10)],
            coords = self.getXY(),
            x = coords[0] + walkTo[0],
            y = coords[1] + walkTo[1];

        return [x, y];
    },

    cycleDialog: function(d, name, loop)
    {
        var self = this;
        if(util.isArray(d)){
            var n = name || self.name,
                dIndex = self.dialogIndices[n] || 0,
                dLen = d.length;

            d = d[dIndex];

            if(++dIndex === dLen) {
                dIndex = loop !== false ? 0 : dIndex - 1;
            }
            self.dialogIndices[n] = dIndex;
        }

        return d;
    },

    setDesc: function(d)
    {
        this.set("description", d);
    },

    getDesc: function()
    {
        var self = this;
        return self.get("description", self.opts.description);
    },

    getTitle: function()
    {
        var self = this;
        return self.attrs.title || self.opts.title || self.name;
    },

    setTitle: function(t)
    {
        var self = this;
        if (t && t !== self.attrs.title) {
            self.attrs.title = t;
            self.updateStatus();
        }
        return t;
    },

    // TODO addSetter('pocketed', bind(addToInventory))
    setPocketed: function(pocketed)
    {
        var self = this;
        if (self.isNot("pocketed")) {
            self.attrs.pocketed = true;
            return self.addToInventory();
        }
        return pocketed;
    },

    // supplemented by Adventure
    getInventory: function()
    {
    },

    addToInventory: function()
    {
    },

    getTileSize: function()
    {
    },

    setActive: function()
    {
    },

    getPlayer: function()
    {
    },

    updateStatus: function()
    {
    }
});

}());
<|endoftext|>


<commit_before>/*
 map settings
*/
var map;

var SHOW_PLAN = false;
var INITIAL_CENTER = {
    "x": 395035.9395,
    "y": 6704086.647
};

var popup; //only one popup at the time

/*
This is a helper function that returns
a OpenLayers LonLat object according
to the geometry that is given to it.

This function should bring some consistency
on where to show a popup for each feature.
*/
function get_popup_lonlat(geometry) {
    var lonlat;
    if ( geometry.id.contains("Point") ) {
        lonlat = new OpenLayers.LonLat(
                        geometry.x,
                        geometry.y);
    } else if ( geometry.id.contains("LineString") ) {
        lonlat = new OpenLayers.LonLat(
                        geometry.components[geometry.components.length - 1].x,
                        geometry.components[geometry.components.length - 1].y);
    } else if ( geometry.id.contains("Polygon") ) {
        lonlat = new OpenLayers.LonLat(
                        geometry.components[0].components[0].x,
                        geometry.components[0].components[0].y);
    }
    return lonlat;
}

/*
 popup save feature event handler
 connected to the save button in the popup form
*/
function save_handler(evt) {

    //get the form data
    var popup_values = $('form[name=popupform].active').serializeArray();

    //set the popup form as not active
    $('form[name=popupform]').removeClass('active');

    //build new attributes for the features
    var new_attributes = {};
    for(var val in popup_values) {
        new_attributes[popup_values[val]['name']] =
            popup_values[val]['value'];
    }

    evt.data[0].attributes = new_attributes;

    //save the geojson
    var gf = new OpenLayers.Format.GeoJSON();
    var geojson = gf.write(evt.data[0]);

    if (evt.data[0].fid === undefined || evt.data[0].fid === null) {

        gnt.geo.create_feature('@me', feature_group, geojson, {
            'success': function(data, textStatus, jqXHR) {
                var new_feature = null;
                // retrieve feature without fid and give it the id from the right layer
                if( data.geometry.type === 'Point') {
                    new_feature = map.getLayersByName('Point Layer')[0].getFeatureByFid(undefined);
                } else if ( data.geometry.type === 'LineString' ) {
                    new_feature = map.getLayersByName('Route Layer')[0].getFeatureByFid(undefined);
                } else if ( data.geometry.type === 'Polygon' ) {
                    new_feature = map.getLayersByName('Area Layer')[0].getFeatureByFid(undefined);
                }
                new_feature.fid = data.id;
        }
    });

    } else {
        //update the feature
        gnt.geo.update_feature(undefined,
                               feature_group,
                               geojson,
                               undefined);
    }

    //unselect feature
    map.getControlsByClass( 'OpenLayers.Control.SelectFeature' )[0].unselectAll(evt);

    //remove popup from map
    if(popup !== undefined) {
        map.removePopup(popup);
        popup = undefined;
    }
}

/*
 popup remove feature event handler,
 connected to the remove button in the popup form.
*/
function remove_handler(evt) {

    evt.data[0].layer.removeFeatures([evt.data[0]]);
    //unselect feature
    map.getControlsByClass( 'OpenLayers.Control.SelectFeature' )[0].unselectAll();

    //if fid found then delete otherwise do nothing
    var gf = new OpenLayers.Format.GeoJSON();
    var geojson = gf.write(evt.data[0]);

    if (evt.data[0].fid !== undefined && evt.data[0].fid !== null) {
        gnt.geo.delete_feature(undefined, feature_group, geojson);
    }

    if(popup !== undefined) {
        map.removePopup(popup);
        popup = undefined;
    }
}

/*
This function makes the popup and shows it for the feature given.

Expects there to be a feature.popup created
that can be called.
*/
function show_popup_for_feature(feature) {

    if ( feature.popup !== undefined ) {

        //remove old popup if existing
        if(popup !== undefined) {
            map.removePopup(popup);
            popup = undefined;
        }

        //create popup and put it on the map
        popup = feature.popup;
        map.addPopup(popup);

        //add a class to the form to recognize it as active
        $('div[id="' + feature.id + '"] form[name="popupform"]').addClass('active');

        // add values to the form the values are connected but the form element name
        // and the name value in the feature attributes
        var input_elements = $('div[id="' + feature.id + '"] form[name="popupform"] :input');
        input_elements.each(function() {
            $(this).val( feature.attributes[ $(this).attr( 'name' ) ] );
        });

        //connect the event to the infowindow buttons
        $('div[id="' + feature.id + '"] .save_feature').click([feature],
                                                      save_handler);
        $('div[id="' + feature.id + '"] .remove_feature').click([feature],
                                                        remove_handler);

        return true;

    } else {

        return false;

    }
}

/*
This function handles the on feature select
where it shows the popup with the correct
values from the feature attributes.
*/
function on_feature_select_handler(evt) {
    show_popup_for_feature(evt);
}

/*
This function handles the on feature unselect
where it closes the popup.
*/
function on_feature_unselect_handler(evt) {

    //remove popup from map
    map.removePopup(popup);
    popup = undefined;
}

/*
 confirm and save the feature

 The feature popup content and is connected
 with the name of the button that was used
 to draw it on the map. The button name is
 the same as the popup id that is supposed
 to be shown as the content in popup.
*/
function feature_added(evt) {

    //get the right lonlat for the popup position
    evt.lonlat = get_popup_lonlat(evt.geometry);

    //get the active button name = infowindow name
    var draw_button_name = $('button.ui-state-active').attr('name');
    var popupcontent = " default info content ";

    //get the right content for the popup
    if( draw_button_name !== undefined ) {
        popupcontent = $('#' + draw_button_name).html();
    }
    evt.popupClass = OpenLayers.Popup.FramedCloud;
    evt.data = {
        popupSize: null,
        popupContentHTML: popupcontent
    };

    //the createPopup function did not seem to work so here
    evt.popup = new OpenLayers.Popup.FramedCloud(
                        evt.id,
                        evt.lonlat,
                        evt.data.popupSize,
                        evt.data.popupContentHTML,
                        null,
                        false);

    show_popup_for_feature(evt);

    //deactivate the map and the drawing
    //unselect the button
    $(".drawbutton.ui-state-active")
        .drawButton( 'deactivate' );
}

/*
 page specific events and other methods
*/
// increase the default animation speed to exaggerate the effect
$.fx.speeds._default = 500;

jQuery(document).ready(function() {

    $( "#more_info" ).dialog({
        autoOpen: false,
        show: "blind",
        width: 800,
        height: 600,
        modal: true
    });
    $( ".image.dialog" ).dialog({
        autoOpen: false,
        show: "blind",
        width: 800,
        maxHeight: 600,
        resizable: false,
        modal: true
    });

    $( "#more_info_link" ).click(function() {
        $( "#more_info" ).dialog( "open" );
        return false;
    });

    $( ".carousel-inner .item" ).click(function( event ) {
        $( "." + $(event.currentTarget).attr('id') ).dialog( "open" );
        return false;
    });

    /* geonition data */
    gnt.auth.create_session();

    $(".free_comment_thanks").hide();

    $("#proposal-form").submit(function(event) {
        event.preventDefault();

        var val_array = $( this ).serializeArray();
        var value = "";
        for(var i = 0; i < val_array.length; i++) {
            if(val_array[i]['name'] === 'free_comment') {
                value = val_array[i]['value'];
                break;
            }
        }
        $("#free_comment").attr("disabled", "disabled");
        $(".submit-evaluation").attr("disabled", "disabled");
        $(".free_comment_thanks").show();
        gnt.opensocial_people.update_person('@me',
                            {'free_comment': value});
    });

    /* Openlayers */

    // set language
    OpenLayers.Lang.setCode('fi');
    var mapOptions = {
        maxExtent: new OpenLayers.Bounds(89949.504,
                                         6502687.508,
                                         502203.000,
                                         7137049.802),
        projection: "EPSG:3067",
        maxResolution: 50,
        numZoomLevels: 10,
        tileSize: new OpenLayers.Size(512, 512)
    };
    map = new OpenLayers.Map('map', mapOptions);

    var arcgisLayer = new OpenLayers.Layer.ArcGIS93Rest(
        "kartta",
        "https://pehmogis.tkk.fi/ArcGIS/rest/services/suomi/MapServer/export",
        {layers: "show:0,7,43,79,115,150,151,187,222,258,294,330",
        format: "png24"},
        {isBaseLayer: true,
        maxExtent: new OpenLayers.Bounds(
            390523.0685,
            6700070.816,
            399368.006,
            6709752.84725),
        buffer: 0}
    );

    //this is for testing modify later
    /*
    var imageLayer = new OpenLayers.Layer.Image(
        "Image layer test",
        "https://softgis.org.aalto.fi/jarvenpaa/static/images/test/test.png",
        new OpenLayers.Bounds(394738.512,
                            6709404.6945,
                            395377.5745,
                            6709881.257),
        new OpenLayers.Size(208, 334),
        {isBaseLayer: false,
        visibility: false}
    );*/

    var gf = new OpenLayers.Format.GeoJSON();
    var proposal_area_feature = gf.read(proposal_area);

    var proposalLayer = new OpenLayers.Layer.ArcGIS93Rest(
        "Ehdotus",
        "https://pehmogis.tkk.fi/ArcGIS/rest/services/Suunnittelu/MapServer/export",
        {layers: "show:0",
        format: "png24",
        transparent: true},
        {isBaseLayer: false,
        maxExtent: proposal_area_feature[0].geometry.getBounds(),
        buffer: 0}
    );

    var annotationLayer = new OpenLayers.Layer.Vector(
                "Annotations Layer",
                {
                    styleMap: new OpenLayers.StyleMap({
                        'default': {
                            strokeWidth: 2,
                            strokeColor: '#ee9900',
                            cursor: 'pointer'
                        }
                    })
                }
    );

    var pointLayer = new OpenLayers.Layer.Vector(
                "Point Layer",
                {
                    styleMap: new OpenLayers.StyleMap({
                        'default': {
                            externalGraphic: "/images/needle?color=ee9900",
                            graphicHeight: 36,
                            graphicWidth: 23,
                            graphicYOffset: -30,
                            cursor: 'pointer'
                        },
                        'temporary': {
                            externalGraphic: "/images/needle?color=ee9900",
                            graphicHeight: 36,
                            graphicWidth: 23,
                            graphicYOffset: -30
                        }
                    })
                });
    var routeLayer = new OpenLayers.Layer.Vector(
                "Route Layer",
                {
                    styleMap: new OpenLayers.StyleMap({
                        'default': {
                            strokeWidth: 2,
                            strokeColor: '#ee9900',
                            cursor: 'pointer'
                        }
                    })
                });
    var areaLayer = new OpenLayers.Layer.Vector(
                "Area Layer",
                {
                    styleMap: new OpenLayers.StyleMap({
                        'default': {
                            strokeWidth: 2,
                            strokeColor: '#ee9900',
                            cursor: 'pointer',
                            fillColor: '#ee9900',
                            fillOpacity: 0.3
                        }
                    })
                });
    //add an information layer where annotations and other
    //visual information can be set on the proposal
    var projectInformationLayer = new OpenLayers.Layer.Vector(
                "Project information",
                {
                    styleMap: new OpenLayers.StyleMap({
                        'default': {
                            strokeWidth: 3,
                            strokeColor: $('body').css('background-color'),
                            fillOpacity: 0,
                            strokeDashstyle: 'dash'
                        }
                    })
                });

    projectInformationLayer.addFeatures(proposal_area_feature);

    map.addLayers([arcgisLayer,
                   proposalLayer,
                   areaLayer,
                   routeLayer,
                   pointLayer,
                   projectInformationLayer]);

    var pointcontrol = new OpenLayers.Control.DrawFeature(pointLayer,
                                OpenLayers.Handler.Point,
                                {'id': 'pointcontrol',
                                'featureAdded': feature_added});
    var routecontrol = new OpenLayers.Control.DrawFeature(routeLayer,
                                OpenLayers.Handler.Path,
                                {'id': 'routecontrol',
                                'featureAdded': feature_added})
    var areacontrol = new OpenLayers.Control.DrawFeature(areaLayer,
                                OpenLayers.Handler.Polygon,
                                {'id': 'areacontrol',
                                'featureAdded': feature_added})

    map.addControls([pointcontrol, routecontrol, areacontrol ]);
    //map.addControl(new OpenLayers.Control.LayerSwitcher());

    //select feature control
    var select_feature_control = new OpenLayers.Control.SelectFeature(
            [pointLayer, routeLayer, areaLayer],
            {
            id: 'selectcontrol',
            onSelect: on_feature_select_handler,
            onUnselect: on_feature_unselect_handler,
            toggle: false,
            clickout: true,
            multiple: false,
            hover: false
            });
    map.addControl(select_feature_control);
    select_feature_control.activate();

    map.setCenter(proposal_area_feature[0].geometry.getBounds().getCenterLonLat(), 0);
    map.zoomToScale(492159825);

    //draw buttons to activate drawing functionality
    $( "#point_feedback").drawButton({
        drawcontrol: "pointcontrol"
    });
    $( "#route_feedback").drawButton({
        drawcontrol: "routecontrol"
    });
    $( "#area_feedback").drawButton({
        drawcontrol: "areacontrol"
    });

    //hide all popups as default
    $('.popup').hide();

    //get the users feature if any
    gnt.geo.get_features(undefined,
                         feature_group,
                         '',
        {
           'success': function(data) {
               if (data.features) {
                   var pl = map.getLayersByName('Point Layer')[0];
                   var rl = map.getLayersByName('Route Layer')[0];
                   var al = map.getLayersByName('Area Layer')[0];
                   var gf = new OpenLayers.Format.GeoJSON();
                   var popupcontent = " default content ";

                   for(var i = 0; i < data.features.length; i++) {
                       var feature = gf.parseFeature(data.features[i]);
                       feature.lonlat = get_popup_lonlat(feature.geometry);

                       if(feature.geometry.id.contains( "Point" )) {
                           pl.addFeatures(feature);
                           popupcontent = $('#place').html();
                       } else if(feature.geometry.id.contains( "LineString" )) {
                           rl.addFeatures(feature);
                           popupcontent = $('#route').html();
                       } else if(feature.geometry.id.contains( "Polygon" )) {
                           al.addFeatures(feature);
                           popupcontent = $('#area').html();
                       }

                       feature.popupClass = OpenLayers.Popup.FramedCloud;
                       feature.data = {
                           popupSize: null,
                           popupContentHTML: popupcontent
                       };

                       //the createPopup function did not seem to work so here
                       feature.popup = new OpenLayers.Popup.FramedCloud(
                                           feature.id,
                                           feature.lonlat,
                                           feature.data.popupSize,
                                           feature.data.popupContentHTML,
                                           null,
                                           false);

                   }
               }
           }
       });
});

//delete the session on unload
$(window).unload(function(event) {
    //gnt.auth.delete_session();
    });
<commit_msg>commented away the proposal area feature as it does not work properly yet<commit_after>/*
 map settings
*/
var map;

var SHOW_PLAN = false;
var INITIAL_CENTER = {
    "x": 395035.9395,
    "y": 6704086.647
};

var popup; //only one popup at the time

/*
This is a helper function that returns
a OpenLayers LonLat object according
to the geometry that is given to it.

This function should bring some consistency
on where to show a popup for each feature.
*/
function get_popup_lonlat(geometry) {
    var lonlat;
    if ( geometry.id.contains("Point") ) {
        lonlat = new OpenLayers.LonLat(
                        geometry.x,
                        geometry.y);
    } else if ( geometry.id.contains("LineString") ) {
        lonlat = new OpenLayers.LonLat(
                        geometry.components[geometry.components.length - 1].x,
                        geometry.components[geometry.components.length - 1].y);
    } else if ( geometry.id.contains("Polygon") ) {
        lonlat = new OpenLayers.LonLat(
                        geometry.components[0].components[0].x,
                        geometry.components[0].components[0].y);
    }
    return lonlat;
}

/*
 popup save feature event handler
 connected to the save button in the popup form
*/
function save_handler(evt) {

    //get the form data
    var popup_values = $('form[name=popupform].active').serializeArray();

    //set the popup form as not active
    $('form[name=popupform]').removeClass('active');

    //build new attributes for the features
    var new_attributes = {};
    for(var val in popup_values) {
        new_attributes[popup_values[val]['name']] =
            popup_values[val]['value'];
    }

    evt.data[0].attributes = new_attributes;

    //save the geojson
    var gf = new OpenLayers.Format.GeoJSON();
    var geojson = gf.write(evt.data[0]);

    if (evt.data[0].fid === undefined || evt.data[0].fid === null) {

        gnt.geo.create_feature('@me', feature_group, geojson, {
            'success': function(data, textStatus, jqXHR) {
                var new_feature = null;
                // retrieve feature without fid and give it the id from the right layer
                if( data.geometry.type === 'Point') {
                    new_feature = map.getLayersByName('Point Layer')[0].getFeatureByFid(undefined);
                } else if ( data.geometry.type === 'LineString' ) {
                    new_feature = map.getLayersByName('Route Layer')[0].getFeatureByFid(undefined);
                } else if ( data.geometry.type === 'Polygon' ) {
                    new_feature = map.getLayersByName('Area Layer')[0].getFeatureByFid(undefined);
                }
                new_feature.fid = data.id;
        }
    });

    } else {
        //update the feature
        gnt.geo.update_feature(undefined,
                               feature_group,
                               geojson,
                               undefined);
    }

    //unselect feature
    map.getControlsByClass( 'OpenLayers.Control.SelectFeature' )[0].unselectAll(evt);

    //remove popup from map
    if(popup !== undefined) {
        map.removePopup(popup);
        popup = undefined;
    }
}

/*
 popup remove feature event handler,
 connected to the remove button in the popup form.
*/
function remove_handler(evt) {

    evt.data[0].layer.removeFeatures([evt.data[0]]);
    //unselect feature
    map.getControlsByClass( 'OpenLayers.Control.SelectFeature' )[0].unselectAll();

    //if fid found then delete otherwise do nothing
    var gf = new OpenLayers.Format.GeoJSON();
    var geojson = gf.write(evt.data[0]);

    if (evt.data[0].fid !== undefined && evt.data[0].fid !== null) {
        gnt.geo.delete_feature(undefined, feature_group, geojson);
    }

    if(popup !== undefined) {
        map.removePopup(popup);
        popup = undefined;
    }
}

/*
This function makes the popup and shows it for the feature given.

Expects there to be a feature.popup created
that can be called.
*/
function show_popup_for_feature(feature) {

    if ( feature.popup !== undefined ) {

        //remove old popup if existing
        if(popup !== undefined) {
            map.removePopup(popup);
            popup = undefined;
        }

        //create popup and put it on the map
        popup = feature.popup;
        map.addPopup(popup);

        //add a class to the form to recognize it as active
        $('div[id="' + feature.id + '"] form[name="popupform"]').addClass('active');

        // add values to the form the values are connected but the form element name
        // and the name value in the feature attributes
        var input_elements = $('div[id="' + feature.id + '"] form[name="popupform"] :input');
        input_elements.each(function() {
            $(this).val( feature.attributes[ $(this).attr( 'name' ) ] );
        });

        //connect the event to the infowindow buttons
        $('div[id="' + feature.id + '"] .save_feature').click([feature],
                                                      save_handler);
        $('div[id="' + feature.id + '"] .remove_feature').click([feature],
                                                        remove_handler);

        return true;

    } else {

        return false;

    }
}

/*
This function handles the on feature select
where it shows the popup with the correct
values from the feature attributes.
*/
function on_feature_select_handler(evt) {
    show_popup_for_feature(evt);
}

/*
This function handles the on feature unselect
where it closes the popup.
*/
function on_feature_unselect_handler(evt) {

    //remove popup from map
    map.removePopup(popup);
    popup = undefined;
}

/*
 confirm and save the feature

 The feature popup content and is connected
 with the name of the button that was used
 to draw it on the map. The button name is
 the same as the popup id that is supposed
 to be shown as the content in popup.
*/
function feature_added(evt) {

    //get the right lonlat for the popup position
    evt.lonlat = get_popup_lonlat(evt.geometry);

    //get the active button name = infowindow name
    var draw_button_name = $('button.ui-state-active').attr('name');
    var popupcontent = " default info content ";

    //get the right content for the popup
    if( draw_button_name !== undefined ) {
        popupcontent = $('#' + draw_button_name).html();
    }
    evt.popupClass = OpenLayers.Popup.FramedCloud;
    evt.data = {
        popupSize: null,
        popupContentHTML: popupcontent
    };

    //the createPopup function did not seem to work so here
    evt.popup = new OpenLayers.Popup.FramedCloud(
                        evt.id,
                        evt.lonlat,
                        evt.data.popupSize,
                        evt.data.popupContentHTML,
                        null,
                        false);

    show_popup_for_feature(evt);

    //deactivate the map and the drawing
    //unselect the button
    $(".drawbutton.ui-state-active")
        .drawButton( 'deactivate' );
}

/*
 page specific events and other methods
*/
// increase the default animation speed to exaggerate the effect
$.fx.speeds._default = 500;

jQuery(document).ready(function() {

    $( "#more_info" ).dialog({
        autoOpen: false,
        show: "blind",
        width: 800,
        height: 600,
        modal: true
    });
    $( ".image.dialog" ).dialog({
        autoOpen: false,
        show: "blind",
        width: 800,
        maxHeight: 600,
        resizable: false,
        modal: true
    });

    $( "#more_info_link" ).click(function() {
        $( "#more_info" ).dialog( "open" );
        return false;
    });

    $( ".carousel-inner .item" ).click(function( event ) {
        $( "." + $(event.currentTarget).attr('id') ).dialog( "open" );
        return false;
    });

    /* geonition data */
    gnt.auth.create_session();

    $(".free_comment_thanks").hide();

    $("#proposal-form").submit(function(event) {
        event.preventDefault();

        var val_array = $( this ).serializeArray();
        var value = "";
        for(var i = 0; i < val_array.length; i++) {
            if(val_array[i]['name'] === 'free_comment') {
                value = val_array[i]['value'];
                break;
            }
        }
        $("#free_comment").attr("disabled", "disabled");
        $(".submit-evaluation").attr("disabled", "disabled");
        $(".free_comment_thanks").show();
        gnt.opensocial_people.update_person('@me',
                            {'free_comment': value});
    });

    /* Openlayers */

    // set language
    OpenLayers.Lang.setCode('fi');
    var mapOptions = {
        maxExtent: new OpenLayers.Bounds(89949.504,
                                         6502687.508,
                                         502203.000,
                                         7137049.802),
        projection: "EPSG:3067",
        maxResolution: 50,
        numZoomLevels: 10,
        tileSize: new OpenLayers.Size(512, 512)
    };
    map = new OpenLayers.Map('map', mapOptions);

    var arcgisLayer = new OpenLayers.Layer.ArcGIS93Rest(
        "kartta",
        "https://pehmogis.tkk.fi/ArcGIS/rest/services/suomi/MapServer/export",
        {layers: "show:0,7,43,79,115,150,151,187,222,258,294,330",
        format: "png24"},
        {isBaseLayer: true,
        maxExtent: new OpenLayers.Bounds(
            390523.0685,
            6700070.816,
            399368.006,
            6709752.84725),
        buffer: 0}
    );

    //this is for testing modify later
    /*
    var imageLayer = new OpenLayers.Layer.Image(
        "Image layer test",
        "https://softgis.org.aalto.fi/jarvenpaa/static/images/test/test.png",
        new OpenLayers.Bounds(394738.512,
                            6709404.6945,
                            395377.5745,
                            6709881.257),
        new OpenLayers.Size(208, 334),
        {isBaseLayer: false,
        visibility: false}
    );*/

    var gf = new OpenLayers.Format.GeoJSON();
    var proposal_area_feature = gf.read(proposal_area);

    var proposalLayer = new OpenLayers.Layer.ArcGIS93Rest(
        "Ehdotus",
        "https://pehmogis.tkk.fi/ArcGIS/rest/services/Suunnittelu/MapServer/export",
        {layers: "show:0",
        format: "png24",
        transparent: true},
        {isBaseLayer: false,
        maxExtent: proposal_area_feature[0].geometry.getBounds(),
        buffer: 0}
    );

    var annotationLayer = new OpenLayers.Layer.Vector(
                "Annotations Layer",
                {
                    styleMap: new OpenLayers.StyleMap({
                        'default': {
                            strokeWidth: 2,
                            strokeColor: '#ee9900',
                            cursor: 'pointer'
                        }
                    })
                }
    );

    var pointLayer = new OpenLayers.Layer.Vector(
                "Point Layer",
                {
                    styleMap: new OpenLayers.StyleMap({
                        'default': {
                            externalGraphic: "/images/needle?color=ee9900",
                            graphicHeight: 36,
                            graphicWidth: 23,
                            graphicYOffset: -30,
                            cursor: 'pointer'
                        },
                        'temporary': {
                            externalGraphic: "/images/needle?color=ee9900",
                            graphicHeight: 36,
                            graphicWidth: 23,
                            graphicYOffset: -30
                        }
                    })
                });
    var routeLayer = new OpenLayers.Layer.Vector(
                "Route Layer",
                {
                    styleMap: new OpenLayers.StyleMap({
                        'default': {
                            strokeWidth: 2,
                            strokeColor: '#ee9900',
                            cursor: 'pointer'
                        }
                    })
                });
    var areaLayer = new OpenLayers.Layer.Vector(
                "Area Layer",
                {
                    styleMap: new OpenLayers.StyleMap({
                        'default': {
                            strokeWidth: 2,
                            strokeColor: '#ee9900',
                            cursor: 'pointer',
                            fillColor: '#ee9900',
                            fillOpacity: 0.3
                        }
                    })
                });
    //add an information layer where annotations and other
    //visual information can be set on the proposal
    var projectInformationLayer = new OpenLayers.Layer.Vector(
                "Project information",
                {
                    styleMap: new OpenLayers.StyleMap({
                        'default': {
                            strokeWidth: 3,
                            strokeColor: $('body').css('background-color'),
                            fillOpacity: 0,
                            strokeDashstyle: 'dash'
                        }
                    })
                });
    /* not working properly at the moment
    projectInformationLayer.addFeatures(proposal_area_feature);
    */

    map.addLayers([arcgisLayer,
                   proposalLayer,
                   areaLayer,
                   routeLayer,
                   pointLayer,
                   projectInformationLayer]);

    var pointcontrol = new OpenLayers.Control.DrawFeature(pointLayer,
                                OpenLayers.Handler.Point,
                                {'id': 'pointcontrol',
                                'featureAdded': feature_added});
    var routecontrol = new OpenLayers.Control.DrawFeature(routeLayer,
                                OpenLayers.Handler.Path,
                                {'id': 'routecontrol',
                                'featureAdded': feature_added})
    var areacontrol = new OpenLayers.Control.DrawFeature(areaLayer,
                                OpenLayers.Handler.Polygon,
                                {'id': 'areacontrol',
                                'featureAdded': feature_added})

    map.addControls([pointcontrol, routecontrol, areacontrol ]);
    //map.addControl(new OpenLayers.Control.LayerSwitcher());

    //select feature control
    var select_feature_control = new OpenLayers.Control.SelectFeature(
            [pointLayer, routeLayer, areaLayer],
            {
            id: 'selectcontrol',
            onSelect: on_feature_select_handler,
            onUnselect: on_feature_unselect_handler,
            toggle: false,
            clickout: true,
            multiple: false,
            hover: false
            });
    map.addControl(select_feature_control);
    select_feature_control.activate();

    map.setCenter(proposal_area_feature[0].geometry.getBounds().getCenterLonLat(), 0);
    map.zoomToScale(492159825);

    //draw buttons to activate drawing functionality
    $( "#point_feedback").drawButton({
        drawcontrol: "pointcontrol"
    });
    $( "#route_feedback").drawButton({
        drawcontrol: "routecontrol"
    });
    $( "#area_feedback").drawButton({
        drawcontrol: "areacontrol"
    });

    //hide all popups as default
    $('.popup').hide();

    //get the users feature if any
    gnt.geo.get_features(undefined,
                         feature_group,
                         '',
        {
           'success': function(data) {
               if (data.features) {
                   var pl = map.getLayersByName('Point Layer')[0];
                   var rl = map.getLayersByName('Route Layer')[0];
                   var al = map.getLayersByName('Area Layer')[0];
                   var gf = new OpenLayers.Format.GeoJSON();
                   var popupcontent = " default content ";

                   for(var i = 0; i < data.features.length; i++) {
                       var feature = gf.parseFeature(data.features[i]);
                       feature.lonlat = get_popup_lonlat(feature.geometry);

                       if(feature.geometry.id.contains( "Point" )) {
                           pl.addFeatures(feature);
                           popupcontent = $('#place').html();
                       } else if(feature.geometry.id.contains( "LineString" )) {
                           rl.addFeatures(feature);
                           popupcontent = $('#route').html();
                       } else if(feature.geometry.id.contains( "Polygon" )) {
                           al.addFeatures(feature);
                           popupcontent = $('#area').html();
                       }

                       feature.popupClass = OpenLayers.Popup.FramedCloud;
                       feature.data = {
                           popupSize: null,
                           popupContentHTML: popupcontent
                       };

                       //the createPopup function did not seem to work so here
                       feature.popup = new OpenLayers.Popup.FramedCloud(
                                           feature.id,
                                           feature.lonlat,
                                           feature.data.popupSize,
                                           feature.data.popupContentHTML,
                                           null,
                                           false);

                   }
               }
           }
       });
});

//delete the session on unload
$(window).unload(function(event) {
    //gnt.auth.delete_session();
    });
<|endoftext|>


<commit_before>var _ = require('underscore');
var VisView = require('../vis/vis-view');
var VisModel = require('../vis/vis');
var Loader = require('../core/loader');
var VizJSON = require('./vizjson');

var DEFAULT_OPTIONS = {
  tiles_loader: true,
  loaderControl: true,
  infowindow: true,
  tooltip: true,
  time_slider: true,
  logo: true,
  show_empty_infowindow_fields: false
};

var createVis = function (el, vizjson, options) {
  if (typeof el === 'string') {
    el = document.getElementById(el);
  }
  if (!el) {
    throw new TypeError('a valid DOM element or selector must be provided');
  }
  if (!vizjson) {
    throw new TypeError('a vizjson URL or object must be provided');
  }

  options = _.defaults(options || {}, DEFAULT_OPTIONS);

  var isProtocolHTTPs = window && window.location.protocol && window.location.protocol === 'https:';

  // TODO: We can check if all required options are present here! eg: if viz.json has some analyses
  // apiKey or authToken will be required (otherwise we know requests to Windshaft will fail)...

  var visModel = new VisModel({
    title: options.title || vizjson.title,
    description: options.description || vizjson.description,
    apiKey: options.apiKey,
    authToken: options.authToken,
    showLegends: options.legends === true || vizjson.legends === true,
    showEmptyInfowindowFields: options.show_empty_infowindow_fields === true,
    https: isProtocolHTTPs || options.https === true || vizjson.https === true
  });

  new VisView({ // eslint-disable-line
    el: el,
    model: visModel
  });

  if (typeof vizjson === 'string') {
    var url = vizjson;
    Loader.get(url, function (vizjson) {
      if (vizjson) {
        loadVizJSON(visModel, vizjson, options);
      } else {
        throw new Error('error fetching viz.json file');
      }
    });
  } else {
    loadVizJSON(visModel, vizjson, options);
  }

  return visModel;
};

var loadVizJSON = function (visModel, vizjsonData, options) {
  var vizjson = new VizJSON(vizjsonData);
  applyOptionsToVizJSON(vizjson, options);
  visModel.load(vizjson);
  if (!options.skipMapInstantiation) {
    visModel.instantiateMap();
  }
};

var applyOptionsToVizJSON = function (vizjson, options) {
  vizjson.scrollwheel = options.scrollwheel || vizjson.scrollwheel;

  if (!options.tiles_loader || !options.loaderControl) {
    vizjson.removeLoaderOverlay();
  }

  if (options.searchControl === true) {
    vizjson.addSearchOverlay();
  } else if (options.searchControl === false) {
    vizjson.removeSearchOverlay();
  }

  if ((options.title && vizjson.title) || (options.description && vizjson.description)) {
    vizjson.addHeaderOverlay(options.title, options.description, options.shareable);
  }

  if (options.layer_selector) {
    vizjson.addLayerSelectorOverlay();
  }

  if (options.zoomControl !== undefined && !options.zoomControl) {
    vizjson.removeZoomOverlay();
  }

  if (options.logo === false) {
    vizjson.removeLogoOverlay();
  }

  // if bounds are present zoom and center will not taken into account
  var zoom = parseInt(options.zoom, 10);
  if (!isNaN(zoom)) {
    vizjson.setZoom(zoom);
  }

  // Center coordinates?
  var center_lat = parseFloat(options.center_lat);
  var center_lon = parseFloat(options.center_lon);
  if (!isNaN(center_lat) && !isNaN(center_lon)) {
    vizjson.setCenter([center_lat, center_lon]);
  }

  // Center object
  if (options.center !== undefined) {
    vizjson.setCenter(options.center);
  }

  // Bounds?
  var sw_lat = parseFloat(options.sw_lat);
  var sw_lon = parseFloat(options.sw_lon);
  var ne_lat = parseFloat(options.ne_lat);
  var ne_lon = parseFloat(options.ne_lon);

  if (!isNaN(sw_lat) && !isNaN(sw_lon) && !isNaN(ne_lat) && !isNaN(ne_lon)) {
    vizjson.setBounds([
      [ sw_lat, sw_lon ],
      [ ne_lat, ne_lon ]
    ]);
  }

  if (options.gmaps_base_type) {
    vizjson.enforceGMapsBaseLayer(options.gmaps_base_type, options.gmaps_style);
  }
};

module.exports = createVis;
<commit_msg>check if `legends` option is present (true or false) and fallback to vizjson's `legends` flag if that's not the case<commit_after>var _ = require('underscore');
var VisView = require('../vis/vis-view');
var VisModel = require('../vis/vis');
var Loader = require('../core/loader');
var VizJSON = require('./vizjson');

var DEFAULT_OPTIONS = {
  tiles_loader: true,
  loaderControl: true,
  infowindow: true,
  tooltip: true,
  time_slider: true,
  logo: true,
  show_empty_infowindow_fields: false
};

var createVis = function (el, vizjson, options) {
  if (typeof el === 'string') {
    el = document.getElementById(el);
  }
  if (!el) {
    throw new TypeError('a valid DOM element or selector must be provided');
  }
  if (!vizjson) {
    throw new TypeError('a vizjson URL or object must be provided');
  }

  options = _.defaults(options || {}, DEFAULT_OPTIONS);

  var isProtocolHTTPs = window && window.location.protocol && window.location.protocol === 'https:';

  // TODO: We can check if all required options are present here! eg: if viz.json has some analyses
  // apiKey or authToken will be required (otherwise we know requests to Windshaft will fail)...

  var showLegends = true;
  if (_.isBoolean(options.legends)) {
    showLegends = options.legends;
  } else if (_.isBoolean(vizjson.legends)) {
    showLegends = false;
  }

  var visModel = new VisModel({
    title: options.title || vizjson.title,
    description: options.description || vizjson.description,
    apiKey: options.apiKey,
    authToken: options.authToken,
    showLegends: showLegends,
    showEmptyInfowindowFields: options.show_empty_infowindow_fields === true,
    https: isProtocolHTTPs || options.https === true || vizjson.https === true
  });

  new VisView({ // eslint-disable-line
    el: el,
    model: visModel
  });

  if (typeof vizjson === 'string') {
    var url = vizjson;
    Loader.get(url, function (vizjson) {
      if (vizjson) {
        loadVizJSON(visModel, vizjson, options);
      } else {
        throw new Error('error fetching viz.json file');
      }
    });
  } else {
    loadVizJSON(visModel, vizjson, options);
  }

  return visModel;
};

var loadVizJSON = function (visModel, vizjsonData, options) {
  var vizjson = new VizJSON(vizjsonData);
  applyOptionsToVizJSON(vizjson, options);
  visModel.load(vizjson);
  if (!options.skipMapInstantiation) {
    visModel.instantiateMap();
  }
};

var applyOptionsToVizJSON = function (vizjson, options) {
  vizjson.scrollwheel = options.scrollwheel || vizjson.scrollwheel;

  if (!options.tiles_loader || !options.loaderControl) {
    vizjson.removeLoaderOverlay();
  }

  if (options.searchControl === true) {
    vizjson.addSearchOverlay();
  } else if (options.searchControl === false) {
    vizjson.removeSearchOverlay();
  }

  if ((options.title && vizjson.title) || (options.description && vizjson.description)) {
    vizjson.addHeaderOverlay(options.title, options.description, options.shareable);
  }

  if (options.layer_selector) {
    vizjson.addLayerSelectorOverlay();
  }

  if (options.zoomControl !== undefined && !options.zoomControl) {
    vizjson.removeZoomOverlay();
  }

  if (options.logo === false) {
    vizjson.removeLogoOverlay();
  }

  // if bounds are present zoom and center will not taken into account
  var zoom = parseInt(options.zoom, 10);
  if (!isNaN(zoom)) {
    vizjson.setZoom(zoom);
  }

  // Center coordinates?
  var center_lat = parseFloat(options.center_lat);
  var center_lon = parseFloat(options.center_lon);
  if (!isNaN(center_lat) && !isNaN(center_lon)) {
    vizjson.setCenter([center_lat, center_lon]);
  }

  // Center object
  if (options.center !== undefined) {
    vizjson.setCenter(options.center);
  }

  // Bounds?
  var sw_lat = parseFloat(options.sw_lat);
  var sw_lon = parseFloat(options.sw_lon);
  var ne_lat = parseFloat(options.ne_lat);
  var ne_lon = parseFloat(options.ne_lon);

  if (!isNaN(sw_lat) && !isNaN(sw_lon) && !isNaN(ne_lat) && !isNaN(ne_lon)) {
    vizjson.setBounds([
      [ sw_lat, sw_lon ],
      [ ne_lat, ne_lon ]
    ]);
  }

  if (options.gmaps_base_type) {
    vizjson.enforceGMapsBaseLayer(options.gmaps_base_type, options.gmaps_style);
  }
};

module.exports = createVis;
<|endoftext|>


<commit_before>/*global angular, define*/
define(['app/appaffinity/appaffinity.module'], function(appaff) {

    appaff.factory('ODLRest', function(Restangular, ENV) {
        return Restangular.withConfig(function(RestangularConfig) {
            RestangularConfig.setBaseUrl(ENV.getBaseURL("MD_SAL"));
        });
    });

    appaff.factory('AARest', function(Restangular) {
        return Restangular.withConfig(function(RestangularConfig) {
          var url = window.location.protocol+"//"+window.location.hostname+":"+"8089/";
          RestangularConfig.setBaseUrl(url);
        });
      });

    appaff.factory('appaffinitySvc', function(AARest, ODLRest) {
        var svc = {

            // TODO: determine them someway and cut this out!
            P : 3,
            W : 2,

            inventory: function() {
                return ODLRest.one('restconf/config/opendaylight-inventory:nodes');
            },
            affinity: function() {
                return AARest.one('affinity');
            },
            tMat: function() {
                return AARest.one('trafficmatrix/matrix');
            }
        };

        svc.getTraffic = function(cb) {
            return svc.tMat().get().then(function(mat) {
                nodes = {};
                var i,j;
                var n = mat.length;
                for (i = 0; i < n; i++) {
                    for (j = 0; j < n; j++) {
                        if (mat[i][j] !== 0){

                            var pSrc = Math.floor(i/svc.W),
                            wSrc = i % svc.W,
                            srcId = 'p' + pSrc + '-w' + wSrc;

                            var pDes = Math.floor(j/svc.W),
                            wDes = j % svc.W,
                            desId = 'p' + pDes + '-w' + wDes;

                            if (nodes[srcId] === undefined) {
                                nodes[srcId] = {id:srcId, incoming: [], outgoing: []};
                            }
                            if (nodes[desId] === undefined) {
                                nodes[desId] = {id:desId, incoming: [], outgoing: []};
                            }
                            nodes[desId].incoming.push([srcId, mat[i][j]]);
                            nodes[srcId].outgoing.push([desId, mat[i][j]]);
                            ;
                        }
                    }
                }
                for (var key in nodes){
                    var node = nodes[key];
                    var inLen = 0, outLen = 0;
                    if (node.incoming) {
                        inLen = Object.keys(node.incoming).length;
                    }
                    if (node.outgoing) {
                        outLen = Object.keys(node.outgoing).length;
                    }
                    node.rows = inLen + outLen;
                }
                cb(nodes);
            },
            function(response) {
                console.log("Error with status code ", response.status);
                cb(undefined); //sends null data to the controller since the call failed
            });
        };

        svc.parseFlow = function(flow) {
            var output = {};
            output.id = flow.id;

            var outAction = flow.instructions.instruction[0]['apply-actions'].action[0]['output-action'];
            output.outPort = outAction['output-node-connector'];
            if (outAction.timeslot) {
                output.timeslot = outAction.timeslot;
            }
            if (outAction.wavelength) {
                output.wavelength = outAction.wavelength;
            }

            output.inPort = flow.match['in-port'];

            return output;
        };

        svc.parseNode = function(node) {
            node.rows = 0;
            var flowList;
            for (var i = 0; i< node['flow-node-inventory:table'].length; i++) {
                 if (node['flow-node-inventory:table'][i].id == 0) {
                     flowList = node['flow-node-inventory:table'][i].flow;
                 }
            }
            var outflows = [];
            for (var flow in flowList) {
                outflows.push(svc.parseFlow(flow));
                node.rows = node.rows + 1;
            }
            return outflows;
        };

        svc.getFlows= function(cb) {
            return svc.inventory().get().then(function(inventory) {
                lst = inventory['nodes']['node'];
                var nodes = [];
                for (var data in lst) {
                    var node = {};
                    node.id = data.id;
                    node.flows = svc.parseNode(node);
                    nodes.push(node);
                }
                cb(nodes);
            }, function(response) {
                console.log("error with status code " + response.status);
            });
        };

        svc.submitService = function(service) {
            return svc.affinity().one('connection').post(service)
        }
        return svc;
    });
});
<commit_msg>DLUX beta version (plus fix forgotten)<commit_after>/*global angular, define*/
define(['app/appaffinity/appaffinity.module'], function(appaff) {

    appaff.factory('ODLRest', function(Restangular, ENV) {
        return Restangular.withConfig(function(RestangularConfig) {
            RestangularConfig.setBaseUrl(ENV.getBaseURL("MD_SAL"));
        });
    });

    appaff.factory('AARest', function(Restangular) {
        return Restangular.withConfig(function(RestangularConfig) {
          var url = window.location.protocol+"//"+window.location.hostname+":"+"8089/";
          RestangularConfig.setBaseUrl(url);
        });
      });

    appaff.factory('appaffinitySvc', function(AARest, ODLRest) {
        var svc = {

            // TODO: determine them someway and cut this out!
            P : 3,
            W : 2,

            inventory: function() {
                return ODLRest.one('restconf/config/opendaylight-inventory:nodes');
            },
            affinity: function() {
                return AARest.one('affinity');
            },
            tMat: function() {
                return AARest.one('trafficmatrix/matrix');
            }
        };

        svc.getTraffic = function(cb) {
            return svc.tMat().get().then(function(mat) {
                nodes = {};
                var i,j;
                var n = mat.length;
                for (i = 0; i < n; i++) {
                    for (j = 0; j < n; j++) {
                        if (mat[i][j] !== 0){

                            var pSrc = Math.floor(i/svc.W),
                            wSrc = i % svc.W,
                            srcId = 'p' + pSrc + '-w' + wSrc;

                            var pDes = Math.floor(j/svc.W),
                            wDes = j % svc.W,
                            desId = 'p' + pDes + '-w' + wDes;

                            if (nodes[srcId] === undefined) {
                                nodes[srcId] = {id:srcId, incoming: [], outgoing: []};
                            }
                            if (nodes[desId] === undefined) {
                                nodes[desId] = {id:desId, incoming: [], outgoing: []};
                            }
                            nodes[desId].incoming.push([srcId, mat[i][j]]);
                            nodes[srcId].outgoing.push([desId, mat[i][j]]);
                            ;
                        }
                    }
                }
                for (var key in nodes){
                    var node = nodes[key];
                    var inLen = 0, outLen = 0;
                    if (node.incoming) {
                        inLen = Object.keys(node.incoming).length;
                    }
                    if (node.outgoing) {
                        outLen = Object.keys(node.outgoing).length;
                    }
                    node.rows = inLen + outLen;
                }
                cb(nodes);
            },
            function(response) {
                console.log("Error with status code ", response.status);
                cb(undefined); //sends null data to the controller since the call failed
            });
        };

        svc.parseFlow = function(flow) {
            var output = {};
            output.id = flow.id;

            var outAction = flow.instructions.instruction[0]['apply-actions'].action[0]['output-action'];
            output.outPort = outAction['output-node-connector'];
            if (outAction.timeslot) {
                output.timeslot = outAction.timeslot;
            }
            if (outAction.wavelength) {
                output.wavelength = outAction.wavelength;
            }

            output.inPort = flow.match['in-port'];

            return output;
        };

        svc.parseNode = function(node) {
            node.rows = 0;
            var flowList;
            for (var i = 0; i< node['flow-node-inventory:table'].length; i++) {
                 if (node['flow-node-inventory:table'][i].id == 0) {
                     flowList = node['flow-node-inventory:table'][i].flow;
                 }
            }
            var outflows = [];
            for (var flow in flowList) {
                outflows.push(svc.parseFlow(flow));
                node.rows = node.rows + 1;
            }
            return outflows;
        };

        svc.getFlows= function(cb) {
            return svc.inventory().get().then(function(inventory) {
                lst = inventory['nodes']['node'];
                var nodes = [];
                for (var data in lst) {
                    var node = {};
                    node.id = data.id;
                    node.flows = svc.parseNode(node);
                    nodes.push(node);
                }
                cb(nodes);
            }, function(response) {
                console.log("error with status code " + response.status);
            });
        };

        svc.submitService = function(service) {
            return svc.affinity().all('connection').post(service)
        }
        return svc;
    });
});
<|endoftext|>


<commit_before>import { IS_NON_DIMENSIONAL } from '../constants';
import options from '../options';

/**
 * Diff the old and new properties of a VNode and apply changes to the DOM node
 * @param {import('../internal').PreactElement} dom The DOM node to apply
 * changes to
 * @param {object} newProps The new props
 * @param {object} oldProps The old props
 * @param {boolean} isSvg Whether or not this node is an SVG node
 * @param {boolean} hydrate Whether or not we are in hydration mode
 */
export function diffProps(dom, newProps, oldProps, isSvg, hydrate) {
	let i;

	for (i in oldProps) {
		if (i !== 'children' && i !== 'key' && !(i in newProps)) {
			setProperty(dom, i, null, oldProps[i], isSvg);
		}
	}

	for (i in newProps) {
		if (
			(!hydrate || typeof newProps[i] == 'function') &&
			i !== 'children' &&
			i !== 'key' &&
			i !== 'value' &&
			i !== 'checked' &&
			oldProps[i] !== newProps[i]
		) {
			setProperty(dom, i, newProps[i], oldProps[i], isSvg);
		}
	}
}

function setStyle(style, key, value) {
	if (key[0] === '-') {
		style.setProperty(key, value);
	} else if (value == null) {
		style[key] = '';
	} else if (typeof value != 'number' || IS_NON_DIMENSIONAL.test(key)) {
		style[key] = value;
	} else {
		style[key] = value + 'px';
	}
}

/**
 * Set a property value on a DOM node
 * @param {import('../internal').PreactElement} dom The DOM node to modify
 * @param {string} name The name of the property to set
 * @param {*} value The value to set the property to
 * @param {*} oldValue The old value the property had
 * @param {boolean} isSvg Whether or not this DOM node is an SVG node or not
 */
export function setProperty(dom, name, value, oldValue, isSvg) {
	let useCapture, nameLower, proxy;

	o: if (name === 'style') {
		if (typeof value == 'string') {
			dom.style.cssText = value;
		} else {
			if (typeof oldValue == 'string') {
				dom.style.cssText = oldValue = '';
			}

			if (oldValue) {
				for (name in oldValue) {
					if (!(value && name in value)) {
						setStyle(dom.style, name, '');
					}
				}
			}

			if (value) {
				for (name in value) {
					if (!oldValue || value[name] !== oldValue[name]) {
						setStyle(dom.style, name, value[name]);
					}
				}
			}
		}
	}
	// Benchmark for comparison: https://esbench.com/bench/574c954bdb965b9a00965ac6
	else if (name[0] === 'o' && name[1] === 'n') {
		useCapture = name !== (name = name.replace(/Capture$/, ''));
		nameLower = name.toLowerCase();
		if (nameLower in dom) name = nameLower;
		name = name.slice(2);

		if (!dom._listeners) dom._listeners = {};
		dom._listeners[name + useCapture] = value;

		proxy = useCapture ? eventProxyCapture : eventProxy;
		if (value) {
			if (!oldValue) dom.addEventListener(name, proxy, useCapture);
		} else {
			dom.removeEventListener(name, proxy, useCapture);
		}
	} else if (name !== 'dangerouslySetInnerHTML') {
		if (isSvg) {
			// Normalize incorrect prop usage for SVG:
			// - xlink:href / xlinkHref --> href (xlink:href was removed from SVG and isn't needed)
			// - className --> class
			name = name.replace(/xlink[H:h]/, 'h').replace(/sName$/, 's');
		} else if (
			name !== 'href' &&
			name !== 'list' &&
			name !== 'form' &&
			name !== 'download' &&
			name in dom
		) {
			try {
				dom[name] = value == null ? '' : value;
				// labelled break is 1b smaller here than a return statement (sorry)
				break o;
			} catch (e) {}
		}

		// ARIA-attributes have a different notion of boolean values.
		// The value `false` is different from the attribute not
		// existing on the DOM, so we can't remove it. For non-boolean
		// ARIA-attributes we could treat false as a removal, but the
		// amount of exceptions would cost us too many bytes. On top of
		// that other VDOM frameworks also always stringify `false`.

		if (typeof value === 'function') {
			// never serialize functions as attribute values
		} else if (value != null && (value !== false || /^ar/.test(name))) {
			dom.setAttribute(name, value);
		} else {
			dom.removeAttribute(name);
		}
	}
}

/**
 * Proxy an event to hooked event handlers
 * @param {Event} e The event object from the browser
 * @private
 */
function eventProxy(e) {
	this._listeners[e.type + false](options.event ? options.event(e) : e);
}

function eventProxyCapture(e) {
	this._listeners[e.type + true](options.event ? options.event(e) : e);
}
<commit_msg>golf aria attribute prefix check<commit_after>import { IS_NON_DIMENSIONAL } from '../constants';
import options from '../options';

/**
 * Diff the old and new properties of a VNode and apply changes to the DOM node
 * @param {import('../internal').PreactElement} dom The DOM node to apply
 * changes to
 * @param {object} newProps The new props
 * @param {object} oldProps The old props
 * @param {boolean} isSvg Whether or not this node is an SVG node
 * @param {boolean} hydrate Whether or not we are in hydration mode
 */
export function diffProps(dom, newProps, oldProps, isSvg, hydrate) {
	let i;

	for (i in oldProps) {
		if (i !== 'children' && i !== 'key' && !(i in newProps)) {
			setProperty(dom, i, null, oldProps[i], isSvg);
		}
	}

	for (i in newProps) {
		if (
			(!hydrate || typeof newProps[i] == 'function') &&
			i !== 'children' &&
			i !== 'key' &&
			i !== 'value' &&
			i !== 'checked' &&
			oldProps[i] !== newProps[i]
		) {
			setProperty(dom, i, newProps[i], oldProps[i], isSvg);
		}
	}
}

function setStyle(style, key, value) {
	if (key[0] === '-') {
		style.setProperty(key, value);
	} else if (value == null) {
		style[key] = '';
	} else if (typeof value != 'number' || IS_NON_DIMENSIONAL.test(key)) {
		style[key] = value;
	} else {
		style[key] = value + 'px';
	}
}

/**
 * Set a property value on a DOM node
 * @param {import('../internal').PreactElement} dom The DOM node to modify
 * @param {string} name The name of the property to set
 * @param {*} value The value to set the property to
 * @param {*} oldValue The old value the property had
 * @param {boolean} isSvg Whether or not this DOM node is an SVG node or not
 */
export function setProperty(dom, name, value, oldValue, isSvg) {
	let useCapture, nameLower, proxy;

	o: if (name === 'style') {
		if (typeof value == 'string') {
			dom.style.cssText = value;
		} else {
			if (typeof oldValue == 'string') {
				dom.style.cssText = oldValue = '';
			}

			if (oldValue) {
				for (name in oldValue) {
					if (!(value && name in value)) {
						setStyle(dom.style, name, '');
					}
				}
			}

			if (value) {
				for (name in value) {
					if (!oldValue || value[name] !== oldValue[name]) {
						setStyle(dom.style, name, value[name]);
					}
				}
			}
		}
	}
	// Benchmark for comparison: https://esbench.com/bench/574c954bdb965b9a00965ac6
	else if (name[0] === 'o' && name[1] === 'n') {
		useCapture = name !== (name = name.replace(/Capture$/, ''));
		nameLower = name.toLowerCase();
		if (nameLower in dom) name = nameLower;
		name = name.slice(2);

		if (!dom._listeners) dom._listeners = {};
		dom._listeners[name + useCapture] = value;

		proxy = useCapture ? eventProxyCapture : eventProxy;
		if (value) {
			if (!oldValue) dom.addEventListener(name, proxy, useCapture);
		} else {
			dom.removeEventListener(name, proxy, useCapture);
		}
	} else if (name !== 'dangerouslySetInnerHTML') {
		if (isSvg) {
			// Normalize incorrect prop usage for SVG:
			// - xlink:href / xlinkHref --> href (xlink:href was removed from SVG and isn't needed)
			// - className --> class
			name = name.replace(/xlink[H:h]/, 'h').replace(/sName$/, 's');
		} else if (
			name !== 'href' &&
			name !== 'list' &&
			name !== 'form' &&
			name !== 'download' &&
			name in dom
		) {
			try {
				dom[name] = value == null ? '' : value;
				// labelled break is 1b smaller here than a return statement (sorry)
				break o;
			} catch (e) {}
		}

		// ARIA-attributes have a different notion of boolean values.
		// The value `false` is different from the attribute not
		// existing on the DOM, so we can't remove it. For non-boolean
		// ARIA-attributes we could treat false as a removal, but the
		// amount of exceptions would cost us too many bytes. On top of
		// that other VDOM frameworks also always stringify `false`.

		if (typeof value === 'function') {
			// never serialize functions as attribute values
		} else if (
			value != null &&
			(value !== false || (name[0] === 'a' && name[1] === 'r'))
		) {
			dom.setAttribute(name, value);
		} else {
			dom.removeAttribute(name);
		}
	}
}

/**
 * Proxy an event to hooked event handlers
 * @param {Event} e The event object from the browser
 * @private
 */
function eventProxy(e) {
	this._listeners[e.type + false](options.event ? options.event(e) : e);
}

function eventProxyCapture(e) {
	this._listeners[e.type + true](options.event ? options.event(e) : e);
}
<|endoftext|>


<commit_before>/*!
 * Copyright 2012 The Toolkitchen Authors. All rights reserved.
 * Use of this source code is governed by a BSD-style
 * license that can be found in the LICENSE file.
 */

(function(scope) {
 /**
  * This module is for normalizing events. Mouse and Touch events will be
  * collected here, and fire PointerEvents that have the same semantics, no
  * matter the source.
  * Events fired:
  *   - pointerdown: a pointing is added
  *   - pointerup: a pointer is removed
  *   - pointermove: a pointer is moved
  *   - pointerover: a pointer crosses into an element
  *   - pointerout: a pointer leaves an element
  *   - pointercancel: a pointer will no longer generate events
  */
  var dispatcher = {
    targets: new SideTable('target'),
    handledEvents: new SideTable('pointer'),
    events: [],
    eventMap: {},
    // Scope objects for native events.
    // This exists for ease of testing.
    eventSources: {},
    /**
     * Add a new event source that will generate pointer events.
     *
     * `inSource` must contain an array of event names named `events`, and
     * functions with the names specified in the `events` array.
     * @param {string} inName A name for the event source
     * @param {Object} inSource A new source of platform events.
     */
    registerSource: function(inName, inSource) {
      var s = inSource;
      this.events = s.events;
      this.events.forEach(function(e) {
        if (s[e]) {
          this.eventMap[e] = s[e].bind(s);
        }
      }, this);
      this.eventSources[inName] = s;
    },
    // add event listeners for inTarget
    registerTarget: function(inTarget) {
      this.listen(this.events, inTarget);
    },
    // remove event listeners for inTarget
    unregisterTarget: function(inTarget) {
      this.unlisten(this.events, inTarget);
    },
    // EVENTS
    down: function(inEvent) {
      this.fireEvent('pointerdown', inEvent)
    },
    move: function(inEvent) {
      this.fireEvent('pointermove', inEvent);
    },
    up: function(inEvent) {
      this.fireEvent('pointerup', inEvent);
    },
    enter: function(inEvent) {
      this.fireEvent('pointerenter', inEvent)
    },
    leave: function(inEvent) {
      this.fireEvent('pointerleave', inEvent);
    },
    over: function(inEvent) {
      this.fireEvent('pointerover', inEvent)
    },
    out: function(inEvent) {
      this.fireEvent('pointerout', inEvent);
    },
    cancel: function(inEvent) {
      this.fireEvent('pointercancel', inEvent);
    },
    // LISTENER LOGIC
    eventHandler: function(inEvent) {
      // This is used to prevent multiple dispatch of pointerevents from
      // platform events. This can happen when two elements in different scopes
      // are set up to create pointer events, which is relevant to Shadow DOM.
      if (this.handledEvents.get(inEvent)) {
        return;
      }
      var type = inEvent.type;
      var fn = this.eventMap && this.eventMap[type];
      if (fn) {
        fn(inEvent);
      }
      this.handledEvents.set(inEvent, true);
    },
    // set up event listeners
    listen: function(inEvents, inTarget) {
      inEvents.forEach(function(e) {
        this.addEvent(e, this.boundHandler, false, inTarget);
      }, this);
    },
    // remove event listeners
    unlisten: function(inEvents) {
      inEvents.forEach(function(e) {
        this.removeEvent(e, this.boundHandler, false, inTarget);
      }, this);
    },
    addEvent: function(inEventName, inEventHandler, inCapture, inTarget) {
      inTarget.addEventListener(inEventName, inEventHandler, inCapture);
    },
    removeEvent: function(inEventName, inEventHandler, inCapture, inTarget) {
      inTarget.removeEventListener(inEventName, inEventHandler, inCapture);
    },
    // EVENT CREATION AND TRACKING
    /**
     * Creates a new Event of type `inType`, based on the information in
     * `inEvent`.
     *
     * @param {string} inType A string representing the type of event to create
     * @param {Event} inEvent A platform event with a target
     * @return {Event} A PointerEvent of type `inType`
     */
    makeEvent: function(inType, inEvent) {
      var e = new PointerEvent(inType, inEvent);
      this.targets.set(e, this.targets.get(inEvent) || inEvent.target);
      return e;
    },
    // make and dispatch an event in one call
    fireEvent: function(inType, inEvent) {
      var e = this.makeEvent(inType, inEvent);
      return this.dispatchEvent(e);
    },
    /**
     * Returns a snapshot of inEvent, with writable properties.
     *
     * @param {Event} inEvent An event that contains properties to copy.
     * @return {Object} An object containing shallow copies of `inEvent`'s
     *    properties.
     */
    cloneEvent: function(inEvent) {
      var eventCopy = {};
      for (var n in inEvent) {
        eventCopy[n] = inEvent[n];
      }
      return eventCopy;
    },
    // TODO (dfreedman): Implement pointer capturing
    getTarget: function(inEvent) {
      // if pointer capture is set, route all events for the specified pointerId
      // to the capture target
      if (this.captureInfo) {
        if (this.captureInfo.id === inEvent.pointerId) {
          return this.captureInfo.target;
        }
      }
      return this.targets.get(inEvent);
    },
    /**
     * Dispatches the event to its target.
     *
     * @param {Event} inEvent The event to be dispatched.
     * @return {Boolean} True if an event handler returns true, false otherwise.
     */
    dispatchEvent: function(inEvent) {
      var t = this.getTarget(inEvent);
      if (t) {
        return t.dispatchEvent(inEvent);
      }
    }
  };
  dispatcher.boundHandler = dispatcher.eventHandler.bind(dispatcher);
  scope.dispatcher = dispatcher;
  /**
   * Convenience function for users to register targets that may be out of the
   * scope of document.
   *
   * @param {Element} InTarget A scope that will create and route PointerEvents
   */
  scope.register = function(inTarget) {
    dispatcher.registerTarget(inTarget);
  };
  /**
   * Convenience function for users to unregister targets that may be out of the
   * scope of document.
   *
   * @param {Element} InTarget A scope created and routed PointerEvents
   */
  scope.unregister = function(inTarget) {
    dispatcher.unregisterTarget(inTarget);
  };
})(window.__PointerEventShim__);
<commit_msg>fix arguments to unlisten<commit_after>/*!
 * Copyright 2012 The Toolkitchen Authors. All rights reserved.
 * Use of this source code is governed by a BSD-style
 * license that can be found in the LICENSE file.
 */

(function(scope) {
 /**
  * This module is for normalizing events. Mouse and Touch events will be
  * collected here, and fire PointerEvents that have the same semantics, no
  * matter the source.
  * Events fired:
  *   - pointerdown: a pointing is added
  *   - pointerup: a pointer is removed
  *   - pointermove: a pointer is moved
  *   - pointerover: a pointer crosses into an element
  *   - pointerout: a pointer leaves an element
  *   - pointercancel: a pointer will no longer generate events
  */
  var dispatcher = {
    targets: new SideTable('target'),
    handledEvents: new SideTable('pointer'),
    events: [],
    eventMap: {},
    // Scope objects for native events.
    // This exists for ease of testing.
    eventSources: {},
    /**
     * Add a new event source that will generate pointer events.
     *
     * `inSource` must contain an array of event names named `events`, and
     * functions with the names specified in the `events` array.
     * @param {string} inName A name for the event source
     * @param {Object} inSource A new source of platform events.
     */
    registerSource: function(inName, inSource) {
      var s = inSource;
      this.events = s.events;
      this.events.forEach(function(e) {
        if (s[e]) {
          this.eventMap[e] = s[e].bind(s);
        }
      }, this);
      this.eventSources[inName] = s;
    },
    // add event listeners for inTarget
    registerTarget: function(inTarget) {
      this.listen(this.events, inTarget);
    },
    // remove event listeners for inTarget
    unregisterTarget: function(inTarget) {
      this.unlisten(this.events, inTarget);
    },
    // EVENTS
    down: function(inEvent) {
      this.fireEvent('pointerdown', inEvent)
    },
    move: function(inEvent) {
      this.fireEvent('pointermove', inEvent);
    },
    up: function(inEvent) {
      this.fireEvent('pointerup', inEvent);
    },
    enter: function(inEvent) {
      this.fireEvent('pointerenter', inEvent)
    },
    leave: function(inEvent) {
      this.fireEvent('pointerleave', inEvent);
    },
    over: function(inEvent) {
      this.fireEvent('pointerover', inEvent)
    },
    out: function(inEvent) {
      this.fireEvent('pointerout', inEvent);
    },
    cancel: function(inEvent) {
      this.fireEvent('pointercancel', inEvent);
    },
    // LISTENER LOGIC
    eventHandler: function(inEvent) {
      // This is used to prevent multiple dispatch of pointerevents from
      // platform events. This can happen when two elements in different scopes
      // are set up to create pointer events, which is relevant to Shadow DOM.
      if (this.handledEvents.get(inEvent)) {
        return;
      }
      var type = inEvent.type;
      var fn = this.eventMap && this.eventMap[type];
      if (fn) {
        fn(inEvent);
      }
      this.handledEvents.set(inEvent, true);
    },
    // set up event listeners
    listen: function(inEvents, inTarget) {
      inEvents.forEach(function(e) {
        this.addEvent(e, this.boundHandler, false, inTarget);
      }, this);
    },
    // remove event listeners
    unlisten: function(inEvents, inTarget) {
      inEvents.forEach(function(e) {
        this.removeEvent(e, this.boundHandler, false, inTarget);
      }, this);
    },
    addEvent: function(inEventName, inEventHandler, inCapture, inTarget) {
      inTarget.addEventListener(inEventName, inEventHandler, inCapture);
    },
    removeEvent: function(inEventName, inEventHandler, inCapture, inTarget) {
      inTarget.removeEventListener(inEventName, inEventHandler, inCapture);
    },
    // EVENT CREATION AND TRACKING
    /**
     * Creates a new Event of type `inType`, based on the information in
     * `inEvent`.
     *
     * @param {string} inType A string representing the type of event to create
     * @param {Event} inEvent A platform event with a target
     * @return {Event} A PointerEvent of type `inType`
     */
    makeEvent: function(inType, inEvent) {
      var e = new PointerEvent(inType, inEvent);
      this.targets.set(e, this.targets.get(inEvent) || inEvent.target);
      return e;
    },
    // make and dispatch an event in one call
    fireEvent: function(inType, inEvent) {
      var e = this.makeEvent(inType, inEvent);
      return this.dispatchEvent(e);
    },
    /**
     * Returns a snapshot of inEvent, with writable properties.
     *
     * @param {Event} inEvent An event that contains properties to copy.
     * @return {Object} An object containing shallow copies of `inEvent`'s
     *    properties.
     */
    cloneEvent: function(inEvent) {
      var eventCopy = {};
      for (var n in inEvent) {
        eventCopy[n] = inEvent[n];
      }
      return eventCopy;
    },
    // TODO (dfreedman): Implement pointer capturing
    getTarget: function(inEvent) {
      // if pointer capture is set, route all events for the specified pointerId
      // to the capture target
      if (this.captureInfo) {
        if (this.captureInfo.id === inEvent.pointerId) {
          return this.captureInfo.target;
        }
      }
      return this.targets.get(inEvent);
    },
    /**
     * Dispatches the event to its target.
     *
     * @param {Event} inEvent The event to be dispatched.
     * @return {Boolean} True if an event handler returns true, false otherwise.
     */
    dispatchEvent: function(inEvent) {
      var t = this.getTarget(inEvent);
      if (t) {
        return t.dispatchEvent(inEvent);
      }
    }
  };
  dispatcher.boundHandler = dispatcher.eventHandler.bind(dispatcher);
  scope.dispatcher = dispatcher;
  /**
   * Convenience function for users to register targets that may be out of the
   * scope of document.
   *
   * @param {Element} InTarget A scope that will create and route PointerEvents
   */
  scope.register = function(inTarget) {
    dispatcher.registerTarget(inTarget);
  };
  /**
   * Convenience function for users to unregister targets that may be out of the
   * scope of document.
   *
   * @param {Element} InTarget A scope created and routed PointerEvents
   */
  scope.unregister = function(inTarget) {
    dispatcher.unregisterTarget(inTarget);
  };
})(window.__PointerEventShim__);
<|endoftext|>