<commit_before>goog.require("ol");

// ol.map
goog.exportSymbol('ol.map', ol.map );
goog.exportSymbol('ol.Map', ol.Map );
goog.exportProperty( ol.Map.prototype, 'renderTo', ol.Map.prototype.renderTo );
goog.exportProperty( ol.Map.prototype, 'center', ol.Map.prototype.center );
goog.exportProperty( ol.Map.prototype, 'projection', ol.Map.prototype.projection );
goog.exportProperty( ol.Map.prototype, 'userProjection', ol.Map.prototype.userProjection );
goog.exportProperty( ol.Map.prototype, 'zoom', ol.Map.prototype.zoom );
goog.exportProperty( ol.Map.prototype, 'numZoomLevels', ol.Map.prototype.numZoomLevels );
goog.exportProperty( ol.Map.prototype, 'resolutions', ol.Map.prototype.resolutions );
goog.exportProperty( ol.Map.prototype, 'layers', ol.Map.prototype.layers );
goog.exportProperty( ol.Map.prototype, 'controls', ol.Map.prototype.controls );
goog.exportProperty( ol.Map.prototype, 'maxExtent', ol.Map.prototype.maxExtent );
goog.exportProperty( ol.Map.prototype, 'destroy', ol.Map.prototype.destroy );

// ol.loc
goog.exportSymbol('ol.loc', ol.loc );
goog.exportSymbol('ol.Loc', ol.Loc ); // This is not required only for the tests with isInstanceOf
goog.exportProperty( ol.Loc.prototype, 'projection', ol.Loc.prototype.projection );
goog.exportProperty( ol.Loc.prototype, 'x', ol.Loc.prototype.x );
goog.exportProperty( ol.Loc.prototype, 'y', ol.Loc.prototype.y );
goog.exportProperty( ol.Loc.prototype, 'z', ol.Loc.prototype.z );
goog.exportProperty( ol.Loc.prototype, 'transform', ol.Loc.prototype.transform );
goog.exportProperty( ol.Loc.prototype, 'destroy', ol.Loc.prototype.destroy );

// ol.projection
goog.exportSymbol('ol.projection', ol.projection );
goog.exportSymbol('ol.Projection', ol.Projection );
goog.exportProperty( ol.Projection.prototype, 'code', ol.Projection.prototype.code );
goog.exportProperty( ol.Projection.prototype, 'units', ol.Projection.prototype.units );

// ol.bounds
goog.exportSymbol('ol.bounds', ol.bounds );
goog.exportSymbol('ol.Bounds', ol.Bounds );
goog.exportProperty( ol.Bounds.prototype, 'projection', ol.Bounds.prototype.projection );
goog.exportProperty( ol.Bounds.prototype, 'minX', ol.Bounds.prototype.minX );
goog.exportProperty( ol.Bounds.prototype, 'minY', ol.Bounds.prototype.minY );
goog.exportProperty( ol.Bounds.prototype, 'maxX', ol.Bounds.prototype.maxX );
goog.exportProperty( ol.Bounds.prototype, 'maxY', ol.Bounds.prototype.maxY );

// ol.layer.xyz
goog.exportSymbol('ol.layer.xyz', ol.layer.xyz);
goog.exportSymbol('ol.layer.XYZ', ol.layer.XYZ);

// ol.layer.osm
goog.exportSymbol('ol.layer.osm', ol.layer.osm);
goog.exportSymbol('ol.layer.OSM', ol.layer.OSM);

// ol.layer.wms
goog.exportSymbol('ol.layer.wms', ol.layer.wms);
goog.exportSymbol('ol.layer.WMS', ol.layer.WMS);

// ol.feature
goog.exportSymbol('ol.feature', ol.feature);
goog.exportSymbol('ol.Feature', ol.Feature);
goog.exportProperty(ol.Feature.prototype, 'set', ol.Feature.prototype.set);
goog.exportProperty(ol.Feature.prototype, 'get', ol.Feature.prototype.get);
goog.exportProperty(ol.Feature.prototype, 'geometry', ol.Feature.prototype.geometry);

// ol.geometry
goog.exportSymbol('ol.geom.geometry', ol.geom.geometry);
goog.exportSymbol('ol.geom.Geometry', ol.geom.Geometry);
goog.exportProperty(ol.geom.Geometry.prototype, 'bounds', ol.geom.Geometry.prototype.bounds);
goog.exportProperty(ol.geom.Geometry.prototype, 'centroid', ol.geom.Geometry.prototype.centroid);

// ol.geom.collection
goog.exportSymbol('ol.geom.collection', ol.geom.collection);
goog.exportSymbol('ol.geom.Collection', ol.geom.Collection);
goog.exportProperty(ol.geom.Collection.prototype, 'components', ol.geom.Collection.prototype.components);
goog.exportProperty(ol.geom.Collection.prototype, 'add', ol.geom.Collection.prototype.add);
goog.exportProperty(ol.geom.Collection.prototype, 'addAll', ol.geom.Collection.prototype.addAll);
goog.exportProperty(ol.geom.Collection.prototype, 'remove', ol.geom.Collection.prototype.remove);
goog.exportProperty(ol.geom.Collection.prototype, 'centroid', ol.geom.Collection.prototype.centroid);

// ol.geom.point
goog.exportSymbol('ol.geom.point', ol.geom.point);
goog.exportSymbol('ol.geom.Point', ol.geom.Point);
goog.exportProperty(ol.geom.Point.prototype, 'x', ol.geom.Point.prototype.x);
goog.exportProperty(ol.geom.Point.prototype, 'y', ol.geom.Point.prototype.y);
goog.exportProperty(ol.geom.Point.prototype, 'z', ol.geom.Point.prototype.z);
goog.exportProperty(ol.geom.Point.prototype, 'projection', ol.geom.Point.prototype.projection);
goog.exportProperty(ol.geom.Point.prototype, 'centroid', ol.geom.Point.prototype.centroid);

// ol.geom.linestring
goog.exportSymbol('ol.geom.linestring', ol.geom.linestring);
goog.exportSymbol('ol.geom.LineString', ol.geom.LineString);
goog.exportProperty(ol.geom.LineString.prototype, 'vertices', ol.geom.LineString.prototype.vertices);
goog.exportProperty(ol.geom.LineString.prototype, 'add', ol.geom.LineString.prototype.add);
goog.exportProperty(ol.geom.LineString.prototype, 'addAll', ol.geom.LineString.prototype.addAll);
goog.exportProperty(ol.geom.LineString.prototype, 'remove', ol.geom.LineString.prototype.remove);
goog.exportProperty(ol.geom.LineString.prototype, 'centroid', ol.geom.LineString.prototype.centroid);

// ol.geom.multipoint
goog.exportSymbol('ol.geom.multipoint', ol.geom.multipoint);
goog.exportSymbol('ol.geom.MultiPoint', ol.geom.MultiPoint);
goog.exportProperty(ol.geom.MultiPoint.prototype, 'points', ol.geom.MultiPoint.prototype.points);
goog.exportProperty(ol.geom.MultiPoint.prototype, 'add', ol.geom.MultiPoint.prototype.add);
goog.exportProperty(ol.geom.MultiPoint.prototype, 'addAll', ol.geom.MultiPoint.prototype.addAll);
goog.exportProperty(ol.geom.MultiPoint.prototype, 'remove', ol.geom.MultiPoint.prototype.remove);
goog.exportProperty(ol.geom.MultiPoint.prototype, 'centroid', ol.geom.MultiPoint.prototype.centroid);

// ol.geom.multilinestring
goog.exportSymbol('ol.geom.multilinestring', ol.geom.multilinestring);
goog.exportSymbol('ol.geom.MultiLineString', ol.geom.MultiLineString);
goog.exportProperty(ol.geom.MultiLineString.prototype, 'linestrings', ol.geom.MultiLineString.prototype.linestrings);
goog.exportProperty(ol.geom.MultiLineString.prototype, 'add', ol.geom.MultiLineString.prototype.add);
goog.exportProperty(ol.geom.MultiLineString.prototype, 'addAll', ol.geom.MultiLineString.prototype.addAll);
goog.exportProperty(ol.geom.MultiLineString.prototype, 'remove', ol.geom.MultiLineString.prototype.remove);
goog.exportProperty(ol.geom.MultiLineString.prototype, 'centroid', ol.geom.MultiLineString.prototype.centroid);

// ol.popup
goog.exportSymbol('ol.popup', ol.popup);
goog.exportSymbol('ol.Popup', ol.Popup);
goog.exportProperty(ol.Popup.prototype, 'anchor', ol.Popup.prototype.anchor);
goog.exportProperty(ol.Popup.prototype, 'map', ol.Popup.prototype.map);
goog.exportProperty(ol.Popup.prototype, 'content', ol.Popup.prototype.content);
goog.exportProperty(ol.Popup.prototype, 'template', ol.Popup.prototype.template);
goog.exportProperty(ol.Popup.prototype, 'open', ol.Popup.prototype.open);

/**
 * Lookup for dynamically registered controls and renderers does not work in
 * advanced compiled mode.  For now, we duplicate the registration calls here.
 *
 * TODO: determine a good way for plugins to register
 */
goog.exportProperty(ol.renderer.Composite, 'isSupported', ol.renderer.Composite.isSupported);
goog.exportProperty(ol.renderer.TileLayerRenderer, 'isSupported', ol.renderer.TileLayerRenderer.isSupported);
goog.exportProperty(ol.renderer.TileLayerRenderer, 'canRender', ol.renderer.TileLayerRenderer.canRender);
goog.exportProperty(ol.renderer.TileLayerRenderer, 'getType', ol.renderer.TileLayerRenderer.getType);
ol.control.addControl('navigation', ol.control.Navigation);
<commit_msg>do no export ol.Map.prototype.destroy, it is gone<commit_after>goog.require("ol");

// ol.map
goog.exportSymbol('ol.map', ol.map );
goog.exportSymbol('ol.Map', ol.Map );
goog.exportProperty( ol.Map.prototype, 'renderTo', ol.Map.prototype.renderTo );
goog.exportProperty( ol.Map.prototype, 'center', ol.Map.prototype.center );
goog.exportProperty( ol.Map.prototype, 'projection', ol.Map.prototype.projection );
goog.exportProperty( ol.Map.prototype, 'userProjection', ol.Map.prototype.userProjection );
goog.exportProperty( ol.Map.prototype, 'zoom', ol.Map.prototype.zoom );
goog.exportProperty( ol.Map.prototype, 'numZoomLevels', ol.Map.prototype.numZoomLevels );
goog.exportProperty( ol.Map.prototype, 'resolutions', ol.Map.prototype.resolutions );
goog.exportProperty( ol.Map.prototype, 'layers', ol.Map.prototype.layers );
goog.exportProperty( ol.Map.prototype, 'controls', ol.Map.prototype.controls );
goog.exportProperty( ol.Map.prototype, 'maxExtent', ol.Map.prototype.maxExtent );

// ol.loc
goog.exportSymbol('ol.loc', ol.loc );
goog.exportSymbol('ol.Loc', ol.Loc ); // This is not required only for the tests with isInstanceOf
goog.exportProperty( ol.Loc.prototype, 'projection', ol.Loc.prototype.projection );
goog.exportProperty( ol.Loc.prototype, 'x', ol.Loc.prototype.x );
goog.exportProperty( ol.Loc.prototype, 'y', ol.Loc.prototype.y );
goog.exportProperty( ol.Loc.prototype, 'z', ol.Loc.prototype.z );
goog.exportProperty( ol.Loc.prototype, 'transform', ol.Loc.prototype.transform );
goog.exportProperty( ol.Loc.prototype, 'destroy', ol.Loc.prototype.destroy );

// ol.projection
goog.exportSymbol('ol.projection', ol.projection );
goog.exportSymbol('ol.Projection', ol.Projection );
goog.exportProperty( ol.Projection.prototype, 'code', ol.Projection.prototype.code );
goog.exportProperty( ol.Projection.prototype, 'units', ol.Projection.prototype.units );

// ol.bounds
goog.exportSymbol('ol.bounds', ol.bounds );
goog.exportSymbol('ol.Bounds', ol.Bounds );
goog.exportProperty( ol.Bounds.prototype, 'projection', ol.Bounds.prototype.projection );
goog.exportProperty( ol.Bounds.prototype, 'minX', ol.Bounds.prototype.minX );
goog.exportProperty( ol.Bounds.prototype, 'minY', ol.Bounds.prototype.minY );
goog.exportProperty( ol.Bounds.prototype, 'maxX', ol.Bounds.prototype.maxX );
goog.exportProperty( ol.Bounds.prototype, 'maxY', ol.Bounds.prototype.maxY );

// ol.layer.xyz
goog.exportSymbol('ol.layer.xyz', ol.layer.xyz);
goog.exportSymbol('ol.layer.XYZ', ol.layer.XYZ);

// ol.layer.osm
goog.exportSymbol('ol.layer.osm', ol.layer.osm);
goog.exportSymbol('ol.layer.OSM', ol.layer.OSM);

// ol.layer.wms
goog.exportSymbol('ol.layer.wms', ol.layer.wms);
goog.exportSymbol('ol.layer.WMS', ol.layer.WMS);

// ol.feature
goog.exportSymbol('ol.feature', ol.feature);
goog.exportSymbol('ol.Feature', ol.Feature);
goog.exportProperty(ol.Feature.prototype, 'set', ol.Feature.prototype.set);
goog.exportProperty(ol.Feature.prototype, 'get', ol.Feature.prototype.get);
goog.exportProperty(ol.Feature.prototype, 'geometry', ol.Feature.prototype.geometry);

// ol.geometry
goog.exportSymbol('ol.geom.geometry', ol.geom.geometry);
goog.exportSymbol('ol.geom.Geometry', ol.geom.Geometry);
goog.exportProperty(ol.geom.Geometry.prototype, 'bounds', ol.geom.Geometry.prototype.bounds);
goog.exportProperty(ol.geom.Geometry.prototype, 'centroid', ol.geom.Geometry.prototype.centroid);

// ol.geom.collection
goog.exportSymbol('ol.geom.collection', ol.geom.collection);
goog.exportSymbol('ol.geom.Collection', ol.geom.Collection);
goog.exportProperty(ol.geom.Collection.prototype, 'components', ol.geom.Collection.prototype.components);
goog.exportProperty(ol.geom.Collection.prototype, 'add', ol.geom.Collection.prototype.add);
goog.exportProperty(ol.geom.Collection.prototype, 'addAll', ol.geom.Collection.prototype.addAll);
goog.exportProperty(ol.geom.Collection.prototype, 'remove', ol.geom.Collection.prototype.remove);
goog.exportProperty(ol.geom.Collection.prototype, 'centroid', ol.geom.Collection.prototype.centroid);

// ol.geom.point
goog.exportSymbol('ol.geom.point', ol.geom.point);
goog.exportSymbol('ol.geom.Point', ol.geom.Point);
goog.exportProperty(ol.geom.Point.prototype, 'x', ol.geom.Point.prototype.x);
goog.exportProperty(ol.geom.Point.prototype, 'y', ol.geom.Point.prototype.y);
goog.exportProperty(ol.geom.Point.prototype, 'z', ol.geom.Point.prototype.z);
goog.exportProperty(ol.geom.Point.prototype, 'projection', ol.geom.Point.prototype.projection);
goog.exportProperty(ol.geom.Point.prototype, 'centroid', ol.geom.Point.prototype.centroid);

// ol.geom.linestring
goog.exportSymbol('ol.geom.linestring', ol.geom.linestring);
goog.exportSymbol('ol.geom.LineString', ol.geom.LineString);
goog.exportProperty(ol.geom.LineString.prototype, 'vertices', ol.geom.LineString.prototype.vertices);
goog.exportProperty(ol.geom.LineString.prototype, 'add', ol.geom.LineString.prototype.add);
goog.exportProperty(ol.geom.LineString.prototype, 'addAll', ol.geom.LineString.prototype.addAll);
goog.exportProperty(ol.geom.LineString.prototype, 'remove', ol.geom.LineString.prototype.remove);
goog.exportProperty(ol.geom.LineString.prototype, 'centroid', ol.geom.LineString.prototype.centroid);

// ol.geom.multipoint
goog.exportSymbol('ol.geom.multipoint', ol.geom.multipoint);
goog.exportSymbol('ol.geom.MultiPoint', ol.geom.MultiPoint);
goog.exportProperty(ol.geom.MultiPoint.prototype, 'points', ol.geom.MultiPoint.prototype.points);
goog.exportProperty(ol.geom.MultiPoint.prototype, 'add', ol.geom.MultiPoint.prototype.add);
goog.exportProperty(ol.geom.MultiPoint.prototype, 'addAll', ol.geom.MultiPoint.prototype.addAll);
goog.exportProperty(ol.geom.MultiPoint.prototype, 'remove', ol.geom.MultiPoint.prototype.remove);
goog.exportProperty(ol.geom.MultiPoint.prototype, 'centroid', ol.geom.MultiPoint.prototype.centroid);

// ol.geom.multilinestring
goog.exportSymbol('ol.geom.multilinestring', ol.geom.multilinestring);
goog.exportSymbol('ol.geom.MultiLineString', ol.geom.MultiLineString);
goog.exportProperty(ol.geom.MultiLineString.prototype, 'linestrings', ol.geom.MultiLineString.prototype.linestrings);
goog.exportProperty(ol.geom.MultiLineString.prototype, 'add', ol.geom.MultiLineString.prototype.add);
goog.exportProperty(ol.geom.MultiLineString.prototype, 'addAll', ol.geom.MultiLineString.prototype.addAll);
goog.exportProperty(ol.geom.MultiLineString.prototype, 'remove', ol.geom.MultiLineString.prototype.remove);
goog.exportProperty(ol.geom.MultiLineString.prototype, 'centroid', ol.geom.MultiLineString.prototype.centroid);

// ol.popup
goog.exportSymbol('ol.popup', ol.popup);
goog.exportSymbol('ol.Popup', ol.Popup);
goog.exportProperty(ol.Popup.prototype, 'anchor', ol.Popup.prototype.anchor);
goog.exportProperty(ol.Popup.prototype, 'map', ol.Popup.prototype.map);
goog.exportProperty(ol.Popup.prototype, 'content', ol.Popup.prototype.content);
goog.exportProperty(ol.Popup.prototype, 'template', ol.Popup.prototype.template);
goog.exportProperty(ol.Popup.prototype, 'open', ol.Popup.prototype.open);

/**
 * Lookup for dynamically registered controls and renderers does not work in
 * advanced compiled mode.  For now, we duplicate the registration calls here.
 *
 * TODO: determine a good way for plugins to register
 */
goog.exportProperty(ol.renderer.Composite, 'isSupported', ol.renderer.Composite.isSupported);
goog.exportProperty(ol.renderer.TileLayerRenderer, 'isSupported', ol.renderer.TileLayerRenderer.isSupported);
goog.exportProperty(ol.renderer.TileLayerRenderer, 'canRender', ol.renderer.TileLayerRenderer.canRender);
goog.exportProperty(ol.renderer.TileLayerRenderer, 'getType', ol.renderer.TileLayerRenderer.getType);
ol.control.addControl('navigation', ol.control.Navigation);
<|endoftext|>


<commit_before>var init;

//-------------------------------------------------- old code

var deviceWidth = [];
var deviceHeight = [];

(function (window, document, $) {
    $(function () {
        var dynamicId,
            dynamicClass,
            pages = [],
            numPages = 0,
            pageId = "";
        //--------------------gui functions
        var gui = {
            loadNewInfo: function (dynamicArgument, dynamicDestination) {
                $(dynamicDestination).empty();
                $.get('ajax/html/' + dynamicArgument + 'Info.html', function (data) {
                    $(dynamicDestination).html(data);
                });
                return
            },
            loadScript: function (dynamicScript) {
                $.getScript("ajax/scripts/" + dynamicScript + ".js")
                    .done(function (script, textStatus) {
                        console.log(textStatus);
                    })
                    .fail(function (jqxhr, settings, exception) {
                        $("div.log").text("Triggered ajaxError handler.");
                    });
            },

            showModal: function () {
                $("#modal").attr("data-state", "right");
                $("#modal").css("z-index", "100");
                return
            },
            hideModal: function () {
                $("#modal").attr("data-state", "hideRight");
            },
            slideSwitch: function (slideId) {
                if (slideId == 'slideZero') {
                    /* work on auto loop
                                prevSlide = pages[i++].id;
                                currentSlide = pages[i].id;
                                nextSlide = pages[i--].id;

                                $("#" + currentSlide).css ({
                                    'left' : '-100%',
                                    'z-index' : '0'
                                });

                                $("#" + nextSlide).css ({
                                    'left' : '0%',
                                    'z-index' : '20'
                                });

                                $("#" + prevSlide).css ({
                                    'left' : '100%',
                                    'z-index' : '10'
                                });
                                */
                    $("#slideZero").attr("data-state", "left");
                    $("#slidePositive").attr("data-state", "right");

                } else if (slideId == 'slidePositive') {
                    $("#slidePositive").attr("data-state", "left");

                    $("#slideNegative").attr("data-state", "right");

                } else if (slideId == 'slideNegative') {
                    $("#slideNegative").attr("data-state", "left");

                    $("#slideZero").attr("data-state", "right");
                }
            }
        };

        //--------------------gui run
        /*$('body').on('click', '.modalLink', function (ev) {
            ev.preventDefault;
            dynamicId = $(this).attr('id');
            dynamicClass = $(this).attr('class').substr(0, 5);

            gui.loadNewInfo(dynamicId, dynamicClass);
            gui.showModule();

            return
        });

        $('body').on('click', '.pageLink', function (ev) {
            ev.preventDefault;

            dynamicId = $(this).attr('id');
            dynamicClass = $(this).attr('class').substr(0, 4);

            dynamicParent = $(this).parents('div').addBack().first();
            slideId = $(this).parent('div').addBack().first().attr('id');

            gui.loadNewInfo(dynamicId, dynamicClass);
            gui.slideSwitch(slideId);
            gui.showNewPage()
        });*/

        //--------------------swipe gestures

        $("#englishContent").click(function () {
            $("#languagePreference").attr('data-state', 'left');
        });

        var intro = document.getElementById('introSection');
        var mc = new Hammer(intro);
        mc.get('pan').set({
            direction: Hammer.DIRECTION_ALL
        });
        mc.on("panleft", function (ev) {
            intro.setAttribute('data-state', 'left');
        });

        var instructions = document.getElementById('instructionsSection');
        var mc1 = new Hammer(instructions);
        mc1.get('pan').set({
            direction: Hammer.DIRECTION_ALL
        });
        mc1.on("panleft", function (ev) {
            instructions.setAttribute('data-state', 'left');
        });

        var links = document.getElementById('transitionLinksWrap');
        var message = document.getElementById('messageSection');
        var mc2 = new Hammer(message);
        mc2.get('pan').set({
            direction: Hammer.DIRECTION_ALL
        });
        mc2.on("panleft", function (ev) {
            message.setAttribute('data-state', 'left');
            links.setAttribute('data-state', 'left');
        });

        $("#signUpSocail").click(function () {
            $(".opaqueBlackBackground").attr('data-state', 'right')
            $("#signUpSocialSection").attr('data-state', 'right');
            $("#signUpSocialSection").addClass('z90');
        });

        var bBk = document.getElementById('opaqueBlackBackground');
        var socailM = document.getElementById('signUpSocail');
        var mc = new Hammer(socailM);
        mc2.get('pan').set({
            direction: Hammer.DIRECTION_ALL
        });

        $("#signUp").click(function () {
            $(".opaqueBlackBackground").attr('data-state', 'right')
            $("#signUpSection").attr('data-state', 'right');
            $("#signUpSection").addClass('z100');
        })

        var links = document.getElementById('transitionLinksWrap');
        var message = document.getElementById('messageSection');
        var mc2 = new Hammer(message);
        mc2.get('pan').set({
            direction: Hammer.DIRECTION_ALL
        });
        mc2.on("panleft", function (ev) {
            message.setAttribute('data-state', 'left');
            links.setAttribute('data-state', 'left');
        });

        $("#accountLoginLink").click(function () {
            $(".opaqueBlackBackground").attr('data-state', 'right')
            $("#linkClickedLogInSection").attr('data-state', 'right');
            $("#linkClickedLogInSection").addClass('z90');
        })

        var links = document.getElementById('transitionLinksWrap');
        var message = document.getElementById('messageSection');
        var mc2 = new Hammer(message);
        mc2.get('pan').set({
            direction: Hammer.DIRECTION_ALL
        });
        mc2.on("panleft panright panup pandown tap press", function (ev) {
            message.setAttribute('data-state', 'left');
            links.setAttribute('data-state', 'left');
        });

        var bBk = document.getElementById('opaqueBlackBackground');

        var socailLinks = document.getElementById('signUpSocailSection');
        var signUpForm = document.getElementById('signUpSocialSection');
        var logIn = document.getElementById('linkClickedLogInSection');
        //var mc2 = new Hammer(socailLinks);
        var mc3 = new Hammer(signUpForm);
        var mc4 = new Hammer(logIn);
        mc2.get('pan').set({
            direction: Hammer.DIRECTION_ALL
        });
        mc3.on("panleft", function (ev) {
            signUpForm.setAttribute('data-state', 'left');
            bBk.setAttribute('data-state', 'left');
        });
        mc4.on("panleft", function (ev) {
            logIn.setAttribute('data-state', 'left');
            bBk.setAttribute('data-state', 'left');
        });

        //--------------------nav functions (fix)
        $('body').on('click', '#navBtn', function (event) {
            event.preventDefault();
            dynamicArgument = $(this).attr('id');
            dynamicDestination = "#modal";

            gui.loadNewInfo(dynamicArgument, dynamicDestination);
            gui.showModal();
        });

        $('body').on('click', '#navBtnBack', function (event) {
            gui.hideModal();
        });
        //--------------------getInfoToDatabases
        $('body').on('click', '#signUpFormSubmit', function (event) {
            event.preventDefault();
             signUp.validateInput();

			 // Cannot show the next page if the info is not valid
			 if (isValid && stringGood)
			 {
				 dynamicArgument = 'savingsGoal';
				 dynamicDestination = "#slidePositive";
				 slideId = $(this).parents('div').addBack().first().attr('id');
				 SQLite.createTables("profile");
				 gui.loadNewInfo(dynamicArgument, dynamicDestination);
				 gui.slideSwitch(slideId);
			 }
			 else
			 	return;
        });

        $('body').on('click', '#savingsGoalSubmitBtn', function (event) {
            event.preventDefault();
			validate.checkMinLength(document.getElementById("goalName").value, 3);
			validate.checkMinLength(document.getElementById("goalPrice").value, 3); // not sure if max 3 characters is sufficient for this value
			validate.checkMinLength(document.getElementById("deadline").value, 10); // requires a better validation to check if the date is written correctly

			// Continue if the strings contain input
			if (stringGood){
				user.insertGoal();
				dynamicArgument = 'chooseChallenge';
				dynamicDestination = "#slideNegative";
				slideId = $(this).parents('div').addBack().first().attr('id');
				gui.loadNewInfo(dynamicArgument, dynamicDestination);
				gui.slideSwitch(slideId);
			} else
			return;

        });

        $('body').on('click', '#coffee', function (event) {
            event.preventDefault();
            dynamicArgument = 'myChallenges';
            dynamicDestination = "#slideZero";
            slideId = $(this).parents('div').addBack().first().attr('id');

            SQLite.createTables("challenges");
            //insertProfile()

            gui.loadNewInfo(dynamicArgument, dynamicDestination);
            gui.slideSwitch(slideId);
        });

        $('#drop').click(function (event) {
            event.preventDefault();

            SQLite.dropTable("challenges");
            SQLite.dropTable("profile");
        });
    });
}(window, document, window.jQuery));<commit_msg>cleaning up code<commit_after>var deviceWidth = [];
var deviceHeight = [];

(function (window, document, $) {
    $(function () {
        var dynamicId,
            dynamicClass,
            pages = [],
            numPages = 0,
            pageId = "";
        //--------------------gui functions
        var gui = {
            loadNewInfo: function (dynamicArgument, dynamicDestination) {
                $(dynamicDestination).empty();
                $.get('ajax/html/' + dynamicArgument + 'Info.html', function (data) {
                    $(dynamicDestination).html(data);
                });
                return
            },
            loadScript: function (dynamicScript) {
                $.getScript("ajax/scripts/" + dynamicScript + ".js")
                    .done(function (script, textStatus) {
                        console.log(textStatus);
                    })
                    .fail(function (jqxhr, settings, exception) {
                        $("div.log").text("Triggered ajaxError handler.");
                    });
            },

            showModal: function () {
                $("#modal").attr("data-state", "right");
                $("#modal").css("z-index", "100");
                return
            },
            hideModal: function () {
                $("#modal").attr("data-state", "hideRight");
            },
            slideSwitch: function (slideId) {
                if (slideId == 'slideZero') {
                    /* work on auto loop
                                prevSlide = pages[i++].id;
                                currentSlide = pages[i].id;
                                nextSlide = pages[i--].id;

                                $("#" + currentSlide).css ({
                                    'left' : '-100%',
                                    'z-index' : '0'
                                });

                                $("#" + nextSlide).css ({
                                    'left' : '0%',
                                    'z-index' : '20'
                                });

                                $("#" + prevSlide).css ({
                                    'left' : '100%',
                                    'z-index' : '10'
                                });
                                */
                    $("#slideZero").attr("data-state", "left");
                    $("#slidePositive").attr("data-state", "right");

                } else if (slideId == 'slidePositive') {
                    $("#slidePositive").attr("data-state", "left");

                    $("#slideNegative").attr("data-state", "right");

                } else if (slideId == 'slideNegative') {
                    $("#slideNegative").attr("data-state", "left");

                    $("#slideZero").attr("data-state", "right");
                }
            }
        };

        //--------------------gui run
        /*$('body').on('click', '.modalLink', function (ev) {
            ev.preventDefault;
            dynamicId = $(this).attr('id');
            dynamicClass = $(this).attr('class').substr(0, 5);

            gui.loadNewInfo(dynamicId, dynamicClass);
            gui.showModule();

            return
        });

        $('body').on('click', '.pageLink', function (ev) {
            ev.preventDefault;

            dynamicId = $(this).attr('id');
            dynamicClass = $(this).attr('class').substr(0, 4);

            dynamicParent = $(this).parents('div').addBack().first();
            slideId = $(this).parent('div').addBack().first().attr('id');

            gui.loadNewInfo(dynamicId, dynamicClass);
            gui.slideSwitch(slideId);
            gui.showNewPage()
        });*/

        //--------------------swipe gestures

        $("#englishContent").click(function () {
            $("#languagePreference").attr('data-state', 'left');
        });

        var intro = document.getElementById('introSection');
        var mc = new Hammer(intro);
        mc.get('pan').set({
            direction: Hammer.DIRECTION_ALL
        });
        mc.on("panleft", function (ev) {
            intro.setAttribute('data-state', 'left');
        });

        var instructions = document.getElementById('instructionsSection');
        var mc1 = new Hammer(instructions);
        mc1.get('pan').set({
            direction: Hammer.DIRECTION_ALL
        });
        mc1.on("panleft", function (ev) {
            instructions.setAttribute('data-state', 'left');
        });

        var links = document.getElementById('transitionLinksWrap');
        var message = document.getElementById('messageSection');
        var mc2 = new Hammer(message);
        mc2.get('pan').set({
            direction: Hammer.DIRECTION_ALL
        });
        mc2.on("panleft", function (ev) {
            message.setAttribute('data-state', 'left');
            links.setAttribute('data-state', 'left');
        });

        $("#signUpSocail").click(function () {
            $(".opaqueBlackBackground").attr('data-state', 'right')
            $("#signUpSocialSection").attr('data-state', 'right');
            $("#signUpSocialSection").addClass('z90');
        });

        var bBk = document.getElementById('opaqueBlackBackground');
        var socailM = document.getElementById('signUpSocail');
        var mc = new Hammer(socailM);
        mc2.get('pan').set({
            direction: Hammer.DIRECTION_ALL
        });

        $("#signUp").click(function () {
            $(".opaqueBlackBackground").attr('data-state', 'right')
            $("#signUpSection").attr('data-state', 'right');
            $("#signUpSection").addClass('z100');
        })

        var links = document.getElementById('transitionLinksWrap');
        var message = document.getElementById('messageSection');
        var mc2 = new Hammer(message);
        mc2.get('pan').set({
            direction: Hammer.DIRECTION_ALL
        });
        mc2.on("panleft", function (ev) {
            message.setAttribute('data-state', 'left');
            links.setAttribute('data-state', 'left');
        });

        $("#accountLoginLink").click(function () {
            $(".opaqueBlackBackground").attr('data-state', 'right')
            $("#linkClickedLogInSection").attr('data-state', 'right');
            $("#linkClickedLogInSection").addClass('z90');
        })

        var links = document.getElementById('transitionLinksWrap');
        var message = document.getElementById('messageSection');
        var mc2 = new Hammer(message);
        mc2.get('pan').set({
            direction: Hammer.DIRECTION_ALL
        });
        mc2.on("panleft panright panup pandown tap press", function (ev) {
            message.setAttribute('data-state', 'left');
            links.setAttribute('data-state', 'left');
        });

        var bBk = document.getElementById('opaqueBlackBackground');

        var socailLinks = document.getElementById('signUpSocailSection');
        var signUpForm = document.getElementById('signUpSocialSection');
        var logIn = document.getElementById('linkClickedLogInSection');
        //var mc2 = new Hammer(socailLinks);
        var mc3 = new Hammer(signUpForm);
        var mc4 = new Hammer(logIn);
        mc2.get('pan').set({
            direction: Hammer.DIRECTION_ALL
        });
        mc3.on("panleft", function (ev) {
            signUpForm.setAttribute('data-state', 'left');
            bBk.setAttribute('data-state', 'left');
        });
        mc4.on("panleft", function (ev) {
            logIn.setAttribute('data-state', 'left');
            bBk.setAttribute('data-state', 'left');
        });

        //--------------------nav functions (fix)
        $('body').on('click', '#navBtn', function (event) {
            event.preventDefault();
            dynamicArgument = $(this).attr('id');
            dynamicDestination = "#modal";

            gui.loadNewInfo(dynamicArgument, dynamicDestination);
            gui.showModal();
        });

        $('body').on('click', '#navBtnBack', function (event) {
            gui.hideModal();
        });
        //--------------------getInfoToDatabases
        $('body').on('click', '#signUpFormSubmit', function (event) {
            event.preventDefault();
             signUp.validateInput();

			 // Cannot show the next page if the info is not valid
			 if (isValid && stringGood)
			 {
				 dynamicArgument = 'savingsGoal';
				 dynamicDestination = "#slidePositive";
				 slideId = $(this).parents('div').addBack().first().attr('id');
				 SQLite.createTables("profile");
				 gui.loadNewInfo(dynamicArgument, dynamicDestination);
				 gui.slideSwitch(slideId);
			 }
			 else
			 	return;
        });

        $('body').on('click', '#savingsGoalSubmitBtn', function (event) {
            event.preventDefault();
			validate.checkMinLength(document.getElementById("goalName").value, 3);
			validate.checkMinLength(document.getElementById("goalPrice").value, 3); // not sure if max 3 characters is sufficient for this value
			validate.checkMinLength(document.getElementById("deadline").value, 10); // requires a better validation to check if the date is written correctly

			// Continue if the strings contain input
			if (stringGood){
				user.insertGoal();
				dynamicArgument = 'chooseChallenge';
				dynamicDestination = "#slideNegative";
				slideId = $(this).parents('div').addBack().first().attr('id');
				gui.loadNewInfo(dynamicArgument, dynamicDestination);
				gui.slideSwitch(slideId);
			} else
			return;

        });

        $('body').on('click', '#coffee', function (event) {
            event.preventDefault();
            dynamicArgument = 'myChallenges';
            dynamicDestination = "#slideZero";
            slideId = $(this).parents('div').addBack().first().attr('id');

            SQLite.createTables("challenges");
            //insertProfile()

            gui.loadNewInfo(dynamicArgument, dynamicDestination);
            gui.slideSwitch(slideId);
        });

        $('#drop').click(function (event) {
            event.preventDefault();

            SQLite.dropTable("challenges");
            SQLite.dropTable("profile");
        });
    });
}(window, document, window.jQuery));<|endoftext|>


<commit_before>/**
 * This class controls a gameplay experiment where the player is
 * invited to play all the games, one after another, while
 * some data are collected (facial expressions, etc).
 */

 var FTG = FTG || {};

 FTG.Experiment = function() {
     this.mUid;
     this.mCurrentGame;
     this.mRestTime;
     this.mEnableFaceTracking;
     this.mDebug;
     this.mFinished;
     this.mData;
     this.mBipSound;
     this.mTanSound;
     this.mCalmSound;

     this.mGames = [
         {id: 1, name: 'card-flipper', url: '../card-flipper/', width: 1300, height: 975, paddingLeft: 300},
         {id: 2, name: 'tetris', url: '../tetris/', width: 640, height: 960, paddingLeft: 600},
         {id: 3, name: 'platformer', url: '../platformer/', width: 1300, height: 975, paddingLeft: 300}
     ];

     this.mGamesSorting = [
         [0, 1, 2],
         [0, 2, 1],
         [1, 0, 2],
         [1, 2, 0],
         [2, 1, 0],
         [2, 0, 1],
     ];
     this.mSorting;

    // Initialize the whole thing up
    this.init();
 };

// Singleton that will be used by all games
FTG.Experiment.instance = null;

// Methods

FTG.Experiment.prototype.init = function() {
    this.mUid = FTG.Utils.getURLParamByName('user');

    this.mCurrentGame = -1; // TODO: get from URL.
    this.mRestTime = FTG.Utils.getURLParamByName('rest') || 3;
    this.mEnableFaceTracking = FTG.Utils.getURLParamByName('face') || false;
    this.mDebug = FTG.Utils.getURLParamByName('debug') || false;
    this.mBipSound = document.getElementById('bip');
    this.mTanSound = document.getElementById('tan');
    this.mCalmSound = document.getElementById('calm');
    this.mSorting = this.mUid ? this.mUid % this.mGamesSorting.length : 0;
    this.mFinished = false;

    this.mData = new FTG.Collector();

    this.mRestTime *= 60 * 1000;

    console.log('[Experiment] Init with user uid:' + this.mUid + ', rest: ' + this.mRestTime + ', facial tracking: ' + this.mEnableFaceTracking + ', sorting: ' + this.mSorting + ' [' + this.mGamesSorting[this.mSorting].join(',') + ']');

    // Warn the user before leaving the page
    window.onbeforeunload = function() {
        return 'You did something that will stop the study before it is over. Please, click "Stay on this Page" to resume your study.';
    };

    // Disable mouse right-click (prevent problems during the experiment)
    document.addEventListener('contextmenu', function(theEvent) {
        theEvent.preventDefault();
    	return false;
    }, false);

    if(this.mUid == null) {
        alert('User id not informed! Append ?user=DDD to the URL.');
    } else {
        // Reverse the order of the games for a subset of users.
        if(this.mUid % 2 == 0) {
            this.mGames.reverse();
        }
        this.greetings();
    }
};

FTG.Experiment.prototype.enableCalmMusic = function(theStatus) {
    if(theStatus) {
        this.mCalmSound.loop = true;
        this.mCalmSound.play();
    } else {
        this.mCalmSound.pause();
    }
};

FTG.Experiment.prototype.playBipSound = function() {
    this.mBipSound.currentTime = 0;
    this.mBipSound.play();
};

FTG.Experiment.prototype.playTanSound = function() {
    this.mTanSound.currentTime = 0;
    this.mTanSound.play();
};

FTG.Experiment.prototype.greetings = function() {
    var aSelf = this;

    $('#info').html(
        '
' +
            '
Instructions
' +
            '
User: ' + this.mUid + '
' +
            '
Welcome! Please wait the researcher let you know when to start.
When you are told to start, click the "Start" button below.

Thank you for being part of this research!
' +
            '<button id="start">Start</button> <button id="heart">HR watch</button>' +
        '
'
    );

    $('#start').click(function() {
        aSelf.startNewGame();
    });

    $('#heart').click(function() {
        aSelf.mData.logMilestone(aSelf.mUid, -1, 'experiment_hr_start');
        aSelf.playBipSound();
        $(this).hide();
    });

    // Play the bip sound to indicate everything is set.
    this.playBipSound();
};

FTG.Experiment.prototype.generateGameURL = function(theGameInfo) {
    return theGameInfo.url + '?user=' + this.mUid + '&game=' + theGameInfo.id + '&rand=' + Math.random() + '&face=' + this.mEnableFaceTracking + '&MUSIC_VOLUME=0.3&SFX_VOLUME=0.4';
};

FTG.Experiment.prototype.startNewGame = function() {
    var aGame;

    if(this.anyMoreGamesToPlay()) {
        this.mCurrentGame++;
        aGame = this.getCurrentGame();

        console.log('[Experiment] New game about to start: ' + aGame.name + ' (id=' + aGame.id + ')');
        this.playTanSound();
        this.mData.logMilestone(this.mUid, aGame.id, 'experiment_game_start');

        // Add the game iframe and ajust its src property (prevent chache issues)
        $('#info').html('');
        document.getElementById('game').src = this.generateGameURL(aGame);

        if(this.mDebug) {
            var aSelf = this;

            $('#info').append('<button id="conclude">Conclude</button>');
            $('#conclude').click(function() {
                aSelf.concludeCurrentGame();
            });
        }

    } else {
        console.log('[Experiment] No more games to play, finishing now');
        this.finish();
    }
};

FTG.Experiment.prototype.concludeCurrentQuestionnaire = function(theData) {
    var aSelf = this;

    console.log('[Experiment] Sending questionnaire data.', theData);

    $.ajax({
        url: '../backend/',
        method: 'POST',
        data: {
            method: 'answer',
            user: this.mUid,
            game: this.getCurrentGame().id,
            data: JSON.stringify({t: Date.now(), d: theData})
        },
        dataType: 'json'

    }).done(function(theData) {
        if(theData.success) {
            console.log('[Experiment] Questionnaire data has been saved!');

            if(aSelf.anyMoreGamesToPlay()) {
                aSelf.rest();
            } else {
                aSelf.finish();
            }

        } else {
            console.error('[Experiment] Backend didn\'t like the answers: ' + theData.message);
        }
    }).fail(function(theXHR, theText) {
        // TODO: show some user friendly messages?
        console.error('Something wrong: ' + theXHR.responseText, theXHR, theText);
    });
};

FTG.Experiment.prototype.concludeCurrentGame = function() {
    var aGame,
        aQuestions;

    aGame = this.getCurrentGame();

    console.log('[Experiment] Current game (' + aGame.name + ', id=' + aGame.id + ') was concluded.');
    this.playTanSound();
    this.mData.logMilestone(this.mUid, aGame.id, 'experiment_game_end');

    $('#info').html(
        '
' +
            '
Questions
' +
            '
Regarding the game you just played, please answer the questions below.
' +
            '

' +
        '
'
    );

    aQuestions = new FTG.Questionnaire(
        'questions',
        this.mUid,
        aGame.id,
        FTG.Questions.Game,
        this.concludeCurrentQuestionnaire,
        this
    );
};

FTG.Experiment.prototype.rest = function() {
    var aFuture = Date.now() + this.mRestTime,
        aSelf = this,
        aId;

    console.log('[Experiment] Resting for ' + (this.mRestTime/1000) + ' seconds...');
    this.mData.logMilestone(this.mUid, -1, 'experiment_rest_start');

    this.enableCalmMusic(true);
    $('#info').html('

Please, relax.

Next game will start in a moment...

');

    aId = setInterval(function() {
        var aRemaining = aFuture - Date.now();

        if(aRemaining <= 0) {
            clearInterval(aId);
            aSelf.enableCalmMusic(false);
            aSelf.startNewGame();
        }
    }, 200);
};

FTG.Experiment.prototype.finish = function() {
    if(this.mFinished) {
        this.sendSubjectHome();
        return;
    }

    console.log('[Experiment] Finishing up. Last chance to ask anything.');
    this.playTanSound();
    this.mData.logMilestone(this.mUid, -1, 'experiment_final_questions_start');

    $('#info').html(
        '
' +
            '
Questions
' +
            '
Please tell us a bit about you.
' +
            '

' +
        '
'
    );

    aQuestions = new FTG.Questionnaire(
        'questions',
        this.mUid,
        -1, // no game
        FTG.Questions.User,
        this.concludeCurrentQuestionnaire,
        this
    );

    this.mFinished = true;
};

FTG.Experiment.prototype.sendSubjectHome = function() {
    console.log('[Experiment] The party is over! Last one to leave turn off the lights.');
    $('#info').html('

The end!

You are good to go. Thank you for helping us help you help us all! :)

');

    this.mData.logMilestone(this.mUid, -1, 'experiment_end');
};

FTG.Experiment.prototype.getCurrentGame = function() {
    return this.mGames[this.mGamesSorting[this.mSorting][this.mCurrentGame]];
};

FTG.Experiment.prototype.anyMoreGamesToPlay = function() {
    return (this.mCurrentGame + 1) < this.mGamesSorting[this.mSorting].length;
};

// Start the party!
$(function() {
    FTG.Experiment.instance = new FTG.Experiment();
});
<commit_msg>Reset calm song instead of playing from where it paused last time.<commit_after>/**
 * This class controls a gameplay experiment where the player is
 * invited to play all the games, one after another, while
 * some data are collected (facial expressions, etc).
 */

 var FTG = FTG || {};

 FTG.Experiment = function() {
     this.mUid;
     this.mCurrentGame;
     this.mRestTime;
     this.mEnableFaceTracking;
     this.mDebug;
     this.mFinished;
     this.mData;
     this.mBipSound;
     this.mTanSound;
     this.mCalmSound;

     this.mGames = [
         {id: 1, name: 'card-flipper', url: '../card-flipper/', width: 1300, height: 975, paddingLeft: 300},
         {id: 2, name: 'tetris', url: '../tetris/', width: 640, height: 960, paddingLeft: 600},
         {id: 3, name: 'platformer', url: '../platformer/', width: 1300, height: 975, paddingLeft: 300}
     ];

     this.mGamesSorting = [
         [0, 1, 2],
         [0, 2, 1],
         [1, 0, 2],
         [1, 2, 0],
         [2, 1, 0],
         [2, 0, 1],
     ];
     this.mSorting;

    // Initialize the whole thing up
    this.init();
 };

// Singleton that will be used by all games
FTG.Experiment.instance = null;

// Methods

FTG.Experiment.prototype.init = function() {
    this.mUid = FTG.Utils.getURLParamByName('user');

    this.mCurrentGame = -1; // TODO: get from URL.
    this.mRestTime = FTG.Utils.getURLParamByName('rest') || 3;
    this.mEnableFaceTracking = FTG.Utils.getURLParamByName('face') || false;
    this.mDebug = FTG.Utils.getURLParamByName('debug') || false;
    this.mBipSound = document.getElementById('bip');
    this.mTanSound = document.getElementById('tan');
    this.mCalmSound = document.getElementById('calm');
    this.mSorting = this.mUid ? this.mUid % this.mGamesSorting.length : 0;
    this.mFinished = false;

    this.mData = new FTG.Collector();

    this.mRestTime *= 60 * 1000;

    console.log('[Experiment] Init with user uid:' + this.mUid + ', rest: ' + this.mRestTime + ', facial tracking: ' + this.mEnableFaceTracking + ', sorting: ' + this.mSorting + ' [' + this.mGamesSorting[this.mSorting].join(',') + ']');

    // Warn the user before leaving the page
    window.onbeforeunload = function() {
        return 'You did something that will stop the study before it is over. Please, click "Stay on this Page" to resume your study.';
    };

    // Disable mouse right-click (prevent problems during the experiment)
    document.addEventListener('contextmenu', function(theEvent) {
        theEvent.preventDefault();
    	return false;
    }, false);

    if(this.mUid == null) {
        alert('User id not informed! Append ?user=DDD to the URL.');
    } else {
        // Reverse the order of the games for a subset of users.
        if(this.mUid % 2 == 0) {
            this.mGames.reverse();
        }
        this.greetings();
    }
};

FTG.Experiment.prototype.enableCalmMusic = function(theStatus) {
    if(theStatus) {
        this.mCalmSound.loop = true;
        this.mCalmSound.currentTime = 0;
        this.mCalmSound.play();
    } else {
        this.mCalmSound.pause();
    }
};

FTG.Experiment.prototype.playBipSound = function() {
    this.mBipSound.currentTime = 0;
    this.mBipSound.play();
};

FTG.Experiment.prototype.playTanSound = function() {
    this.mTanSound.currentTime = 0;
    this.mTanSound.play();
};

FTG.Experiment.prototype.greetings = function() {
    var aSelf = this;

    $('#info').html(
        '
' +
            '
Instructions
' +
            '
User: ' + this.mUid + '
' +
            '
Welcome! Please wait the researcher let you know when to start.
When you are told to start, click the "Start" button below.

Thank you for being part of this research!
' +
            '<button id="start">Start</button> <button id="heart">HR watch</button>' +
        '
'
    );

    $('#start').click(function() {
        aSelf.startNewGame();
    });

    $('#heart').click(function() {
        aSelf.mData.logMilestone(aSelf.mUid, -1, 'experiment_hr_start');
        aSelf.playBipSound();
        $(this).hide();
    });

    // Play the bip sound to indicate everything is set.
    this.playBipSound();
};

FTG.Experiment.prototype.generateGameURL = function(theGameInfo) {
    return theGameInfo.url + '?user=' + this.mUid + '&game=' + theGameInfo.id + '&rand=' + Math.random() + '&face=' + this.mEnableFaceTracking + '&MUSIC_VOLUME=0.3&SFX_VOLUME=0.4';
};

FTG.Experiment.prototype.startNewGame = function() {
    var aGame;

    if(this.anyMoreGamesToPlay()) {
        this.mCurrentGame++;
        aGame = this.getCurrentGame();

        console.log('[Experiment] New game about to start: ' + aGame.name + ' (id=' + aGame.id + ')');
        this.playTanSound();
        this.mData.logMilestone(this.mUid, aGame.id, 'experiment_game_start');

        // Add the game iframe and ajust its src property (prevent chache issues)
        $('#info').html('');
        document.getElementById('game').src = this.generateGameURL(aGame);

        if(this.mDebug) {
            var aSelf = this;

            $('#info').append('<button id="conclude">Conclude</button>');
            $('#conclude').click(function() {
                aSelf.concludeCurrentGame();
            });
        }

    } else {
        console.log('[Experiment] No more games to play, finishing now');
        this.finish();
    }
};

FTG.Experiment.prototype.concludeCurrentQuestionnaire = function(theData) {
    var aSelf = this;

    console.log('[Experiment] Sending questionnaire data.', theData);

    $.ajax({
        url: '../backend/',
        method: 'POST',
        data: {
            method: 'answer',
            user: this.mUid,
            game: this.getCurrentGame().id,
            data: JSON.stringify({t: Date.now(), d: theData})
        },
        dataType: 'json'

    }).done(function(theData) {
        if(theData.success) {
            console.log('[Experiment] Questionnaire data has been saved!');

            if(aSelf.anyMoreGamesToPlay()) {
                aSelf.rest();
            } else {
                aSelf.finish();
            }

        } else {
            console.error('[Experiment] Backend didn\'t like the answers: ' + theData.message);
        }
    }).fail(function(theXHR, theText) {
        // TODO: show some user friendly messages?
        console.error('Something wrong: ' + theXHR.responseText, theXHR, theText);
    });
};

FTG.Experiment.prototype.concludeCurrentGame = function() {
    var aGame,
        aQuestions;

    aGame = this.getCurrentGame();

    console.log('[Experiment] Current game (' + aGame.name + ', id=' + aGame.id + ') was concluded.');
    this.playTanSound();
    this.mData.logMilestone(this.mUid, aGame.id, 'experiment_game_end');

    $('#info').html(
        '
' +
            '
Questions
' +
            '
Regarding the game you just played, please answer the questions below.
' +
            '

' +
        '
'
    );

    aQuestions = new FTG.Questionnaire(
        'questions',
        this.mUid,
        aGame.id,
        FTG.Questions.Game,
        this.concludeCurrentQuestionnaire,
        this
    );
};

FTG.Experiment.prototype.rest = function() {
    var aFuture = Date.now() + this.mRestTime,
        aSelf = this,
        aId;

    console.log('[Experiment] Resting for ' + (this.mRestTime/1000) + ' seconds...');
    this.mData.logMilestone(this.mUid, -1, 'experiment_rest_start');

    this.enableCalmMusic(true);
    $('#info').html('

Please, relax.

Next game will start in a moment...

');

    aId = setInterval(function() {
        var aRemaining = aFuture - Date.now();

        if(aRemaining <= 0) {
            clearInterval(aId);
            aSelf.enableCalmMusic(false);
            aSelf.startNewGame();
        }
    }, 200);
};

FTG.Experiment.prototype.finish = function() {
    if(this.mFinished) {
        this.sendSubjectHome();
        return;
    }

    console.log('[Experiment] Finishing up. Last chance to ask anything.');
    this.playTanSound();
    this.mData.logMilestone(this.mUid, -1, 'experiment_final_questions_start');

    $('#info').html(
        '
' +
            '
Questions
' +
            '
Please tell us a bit about you.
' +
            '

' +
        '
'
    );

    aQuestions = new FTG.Questionnaire(
        'questions',
        this.mUid,
        -1, // no game
        FTG.Questions.User,
        this.concludeCurrentQuestionnaire,
        this
    );

    this.mFinished = true;
};

FTG.Experiment.prototype.sendSubjectHome = function() {
    console.log('[Experiment] The party is over! Last one to leave turn off the lights.');
    $('#info').html('

The end!

You are good to go. Thank you for helping us help you help us all! :)

');

    this.mData.logMilestone(this.mUid, -1, 'experiment_end');
};

FTG.Experiment.prototype.getCurrentGame = function() {
    return this.mGames[this.mGamesSorting[this.mSorting][this.mCurrentGame]];
};

FTG.Experiment.prototype.anyMoreGamesToPlay = function() {
    return (this.mCurrentGame + 1) < this.mGamesSorting[this.mSorting].length;
};

// Start the party!
$(function() {
    FTG.Experiment.instance = new FTG.Experiment();
});
<|endoftext|>


<commit_before>/**
 * @author alteredq / http://alteredqualia.com/
 */

THREE.EffectComposer = function( renderer, renderTarget ) {

	this.renderer = renderer;

	this.renderTarget1 = renderTarget;

	if ( this.renderTarget1 === undefined ) {

		var width = window.innerWidth || 1;
		var height = window.innerHeight || 1;

		this.renderTargetParameters = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBFormat, stencilBuffer: false };
		this.renderTarget1 = new THREE.WebGLRenderTarget( width, height, this.renderTargetParameters );

	}

	this.renderTarget2 = this.renderTarget1.clone();

	this.writeBuffer = this.renderTarget1;
	this.readBuffer = this.renderTarget2;

	this.passes = [];

	this.copyPass = new THREE.ShaderPass( THREE.ShaderExtras[ "screen" ] );

};

THREE.EffectComposer.prototype = {

	swapBuffers: function() {

		var tmp = this.readBuffer;
		this.readBuffer = this.writeBuffer;
		this.writeBuffer = tmp;

	},

	addPass: function ( pass ) {

		this.passes.push( pass );

	},

	render: function ( delta ) {

		this.writeBuffer = this.renderTarget1;
		this.readBuffer = this.renderTarget2;

		var maskActive = false;

		var pass, i, il = this.passes.length;

		for ( i = 0; i < il; i ++ ) {

			pass = this.passes[ i ];

			if ( !pass.enabled ) continue;

			pass.render( this.renderer, this.writeBuffer, this.readBuffer, delta, maskActive );

			if ( pass.needsSwap ) {

				if ( maskActive ) {

					var context = this.renderer.context;

					context.stencilFunc( context.NOTEQUAL, 1, 0xffffffff );

					this.copyPass.render( this.renderer, this.writeBuffer, this.readBuffer, delta );

					context.stencilFunc( context.EQUAL, 1, 0xffffffff );

				}

				this.swapBuffers();

			}

			if ( pass instanceof THREE.MaskPass ) {

				maskActive = true;

			} else if ( pass instanceof THREE.ClearMaskPass ) {

				maskActive = false;

			}

		}

	},

	reset: function ( renderTarget ) {

		this.renderTarget1 = renderTarget;

		if ( this.renderTarget1 === undefined ) {

			this.renderTarget1 = new THREE.WebGLRenderTarget( window.innerWidth, window.innerHeight, this.renderTargetParameters );

		}

		this.renderTarget2 = this.renderTarget1.clone();

		this.writeBuffer = this.renderTarget1;
		this.readBuffer = this.renderTarget2;

		THREE.EffectComposer.quad.scale.set( window.innerWidth, window.innerHeight, 1 );

		THREE.EffectComposer.camera.left = window.innerWidth / - 2;
		THREE.EffectComposer.camera.right = window.innerWidth / 2;
		THREE.EffectComposer.camera.top = window.innerHeight / 2;
		THREE.EffectComposer.camera.bottom = window.innerHeight / - 2;

		THREE.EffectComposer.camera.updateProjectionMatrix();

	}

};

// shared ortho camera

THREE.EffectComposer.initWidth = window.innerWidth || 1;
THREE.EffectComposer.initHeight = window.innerHeight || 1;

THREE.EffectComposer.camera = new THREE.OrthographicCamera( THREE.EffectComposer.initWidth / - 2, THREE.EffectComposer.initWidth / 2, THREE.EffectComposer.initHeight / 2, THREE.EffectComposer.initHeight / - 2, -10000, 10000 );

// shared fullscreen quad scene

THREE.EffectComposer.geometry = new THREE.PlaneGeometry( 1, 1 );
THREE.EffectComposer.geometry.applyMatrix( new THREE.Matrix4().makeRotationX( Math.PI / 2 ) );

THREE.EffectComposer.quad = new THREE.Mesh( THREE.EffectComposer.geometry, null );
THREE.EffectComposer.quad.position.z = -100;
THREE.EffectComposer.quad.scale.set( THREE.EffectComposer.initWidth, THREE.EffectComposer.initHeight, 1 );

THREE.EffectComposer.scene = new THREE.Scene();
THREE.EffectComposer.scene.add( THREE.EffectComposer.quad );
THREE.EffectComposer.scene.add( THREE.EffectComposer.camera );
<commit_msg>Fixed inverted U in postprocessing.<commit_after>/**
 * @author alteredq / http://alteredqualia.com/
 */

THREE.EffectComposer = function( renderer, renderTarget ) {

	this.renderer = renderer;

	this.renderTarget1 = renderTarget;

	if ( this.renderTarget1 === undefined ) {

		var width = window.innerWidth || 1;
		var height = window.innerHeight || 1;

		this.renderTargetParameters = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBFormat, stencilBuffer: false };
		this.renderTarget1 = new THREE.WebGLRenderTarget( width, height, this.renderTargetParameters );

	}

	this.renderTarget2 = this.renderTarget1.clone();

	this.writeBuffer = this.renderTarget1;
	this.readBuffer = this.renderTarget2;

	this.passes = [];

	this.copyPass = new THREE.ShaderPass( THREE.ShaderExtras[ "screen" ] );

};

THREE.EffectComposer.prototype = {

	swapBuffers: function() {

		var tmp = this.readBuffer;
		this.readBuffer = this.writeBuffer;
		this.writeBuffer = tmp;

	},

	addPass: function ( pass ) {

		this.passes.push( pass );

	},

	render: function ( delta ) {

		this.writeBuffer = this.renderTarget1;
		this.readBuffer = this.renderTarget2;

		var maskActive = false;

		var pass, i, il = this.passes.length;

		for ( i = 0; i < il; i ++ ) {

			pass = this.passes[ i ];

			if ( !pass.enabled ) continue;

			pass.render( this.renderer, this.writeBuffer, this.readBuffer, delta, maskActive );

			if ( pass.needsSwap ) {

				if ( maskActive ) {

					var context = this.renderer.context;

					context.stencilFunc( context.NOTEQUAL, 1, 0xffffffff );

					this.copyPass.render( this.renderer, this.writeBuffer, this.readBuffer, delta );

					context.stencilFunc( context.EQUAL, 1, 0xffffffff );

				}

				this.swapBuffers();

			}

			if ( pass instanceof THREE.MaskPass ) {

				maskActive = true;

			} else if ( pass instanceof THREE.ClearMaskPass ) {

				maskActive = false;

			}

		}

	},

	reset: function ( renderTarget ) {

		this.renderTarget1 = renderTarget;

		if ( this.renderTarget1 === undefined ) {

			this.renderTarget1 = new THREE.WebGLRenderTarget( window.innerWidth, window.innerHeight, this.renderTargetParameters );

		}

		this.renderTarget2 = this.renderTarget1.clone();

		this.writeBuffer = this.renderTarget1;
		this.readBuffer = this.renderTarget2;

		THREE.EffectComposer.quad.scale.set( window.innerWidth, window.innerHeight, 1 );

		THREE.EffectComposer.camera.left = window.innerWidth / - 2;
		THREE.EffectComposer.camera.right = window.innerWidth / 2;
		THREE.EffectComposer.camera.top = window.innerHeight / 2;
		THREE.EffectComposer.camera.bottom = window.innerHeight / - 2;

		THREE.EffectComposer.camera.updateProjectionMatrix();

	}

};

// shared ortho camera

THREE.EffectComposer.initWidth = window.innerWidth || 1;
THREE.EffectComposer.initHeight = window.innerHeight || 1;

THREE.EffectComposer.camera = new THREE.OrthographicCamera( THREE.EffectComposer.initWidth / - 2, THREE.EffectComposer.initWidth / 2, THREE.EffectComposer.initHeight / 2, THREE.EffectComposer.initHeight / - 2, -10000, 10000 );

// shared fullscreen quad scene

THREE.EffectComposer.geometry = new THREE.PlaneGeometry( 1, 1 );
THREE.EffectComposer.geometry.applyMatrix( new THREE.Matrix4().makeRotationX( Math.PI / 2 ) );
THREE.EffectComposer.geometry.applyMatrix( new THREE.Matrix4().makeScale( 1, -1, 1 ) );

THREE.EffectComposer.quad = new THREE.Mesh( THREE.EffectComposer.geometry, null );
THREE.EffectComposer.quad.position.z = -100;
THREE.EffectComposer.quad.flipSided = true;
THREE.EffectComposer.quad.scale.set( THREE.EffectComposer.initWidth, THREE.EffectComposer.initHeight, 1 );

THREE.EffectComposer.scene = new THREE.Scene();
THREE.EffectComposer.scene.add( THREE.EffectComposer.quad );
THREE.EffectComposer.scene.add( THREE.EffectComposer.camera );
<|endoftext|>


<commit_before>/**
 * @fileoverview HTTP Transport.
 *
 * Provide HTTP request.
 */

goog.provide('ydn.http.ITransport');
goog.provide('ydn.http.Transport');
goog.provide('ydn.http.CallbackResult');

/**
 *
 * @constructor
 * @param {string} content_type
 * @param {string} text
 * @param {string} url
 * @param {number} status
 * @param {*=} response
 * @param {Object.<string>=} headers response headers
 */
ydn.http.CallbackResult = function (content_type, text, url, status, response, headers) {
  /** @final */
  this.status = status;
  /** @final */
  this.contentType = content_type;
  /** @final */
  this.responseText = text || '';
  /** @final */
  this.url = url;
  /* final */
  this.response = response || null;
  /* final */
  this.headers = headers || {};
};

/**
 * @type {number}
 */
ydn.http.CallbackResult.prototype.status;

/**
 * @type {string}
 */
ydn.http.CallbackResult.prototype.contentType;

/**
 * @type {string}
 */
ydn.http.CallbackResult.prototype.responseText;

/**
 * @type {string}
 */
ydn.http.CallbackResult.prototype.url;

/**
 * @type {*}
 */
ydn.http.CallbackResult.prototype.response;

/**
 * @type {Object.<string>}
 */
ydn.http.CallbackResult.prototype.headers;

/**
 *
 * @param {!Object} result_json
 * @return {ydn.http.CallbackResult}
 */
ydn.http.CallbackResult.wrap = function (result_json) {
  if (result_json instanceof ydn.http.CallbackResult) {
    return result_json;
  } else {
    return new ydn.http.CallbackResult(
        result_json['contentType'],
        result_json['responseText'],
        result_json['url'],
        result_json['status'],
        result_json['response'],
        result_json['headers']);
  }
};

/**
 *
 * @param {string} header the header
 * @return {string|undefined} header value
 */
ydn.http.CallbackResult.prototype.getHeader = function(header) {
  return this.headers[header];
};

/**
 *
 * @return {!Object}
 */
ydn.http.CallbackResult.prototype.getResponseJson = function() {
  var is_content_json = this.contentType == 'json' ||
      goog.string.startsWith(this.contentType, 'application/json');
  if (is_content_json &&
      this.response != null && typeof this.response == 'object') {
    return /** @type {!Object} */ (this.response);
  } else {
    return ydn.json.parse(this.responseText);
  }
};

/**
 *
 * @return {number}
 */
ydn.http.CallbackResult.prototype.getStatus = function() {
  return this.status;
};

/**
 *
 * @return {string}
 */
ydn.http.CallbackResult.prototype.getUrl = function() {
  return this.url;
};

/**
 *
 * @return {boolean}
 */
ydn.http.CallbackResult.prototype.isSuccessStatusCode = function() {
  return this.status >= 200 && this.status < 400;
};

/**
 * Return status and shortened text from the result.
 * @return {string}
 */
ydn.http.CallbackResult.prototype.getMessage = function() {
  var txt = goog.isString(this.responseText) ? this.responseText.substring(0, 200) : '';
  return this.status + ': ' + txt;
};

/**
 *
 * @return {boolean} if content_type is json
 */
ydn.http.CallbackResult.prototype.isContentJson = function() {
  return /application\/json/.test(this.contentType);
};

/**
 *
 * @return {boolean} if content_type is javascript
 */
ydn.http.CallbackResult.prototype.isContentJavascript = function() {
  return /text\/javascript/.test(this.contentType);
};

/**
 * @return {string}
 */
ydn.http.CallbackResult.prototype.toString = function() {
  if (goog.DEBUG) {
    var msg = this.message ? this.message : this.responseText;
    return this.status + ' ' + this.url + ' ' + msg;
  } else {
    return goog.base(this, 'toString');
  }
};

/**
 *
 * @interface
 */
ydn.http.ITransport = function() {};

/**
 * @typedef {{
 * method: (string|undefined),
 * body: (string|undefined),
 * headers: (Object.<string>|undefined),
 * params: (Object.<string>|undefined)
 * }}
 */
ydn.http.ITransport.Options;

/**
 *
 * @param {Object=} options given option
 * @return {!ydn.http.ITransport.Options} return given options if not
 * default options. input argument is not modified.
 */
ydn.http.getDefaultOptions = function(options) {
  var default_options = {
    method: 'GET',
    body: undefined,
    headers: {},
    params: {}

  };
  if (goog.isDefAndNotNull(options)) {
    return {
      method: options.method || default_options.method,
      body: options.body,
      headers: options.headers || {},
      params: options.params || {}
    }
  } else {
    return default_options;
  }
};

/**
 * Submit HTTP request.
 *
 * @param {string} url
 * @param {function(ydn.http.CallbackResult)=} opt_callback
 * @param {ydn.http.ITransport.Options=} opt_options
 * @return {goog.async.Deferred|undefined} if not provided, callback result
 * is return in the deferred function.
 */
ydn.http.ITransport.prototype.send =  function(url, opt_callback, opt_options) {

};

/**
 *
 * @constructor
 * @implements {ydn.http.ITransport}
 */
ydn.http.Transport = function() {};

/**
 * @inheritDoc
 */
ydn.http.Transport.prototype.send = goog.abstractMethod;

<commit_msg>all test update.<commit_after>/**
 * @fileoverview HTTP Transport.
 *
 * Provide HTTP request.
 */

goog.provide('ydn.http.ITransport');
goog.provide('ydn.http.Transport');
goog.provide('ydn.http.CallbackResult');

/**
 *
 * @constructor
 * @param {string} content_type
 * @param {string} text
 * @param {string} url
 * @param {number} status
 * @param {*=} response
 * @param {Object.<string>=} headers response headers
 */
ydn.http.CallbackResult = function (content_type, text, url, status, response, headers) {
  /** @final */
  this.status = status;
  /** @final */
  this.contentType = content_type;
  /** @final */
  this.responseText = text || '';
  /** @final */
  this.url = url;
  /* final */
  this.response = response || null;
  /* final */
  this.headers = headers || {};
};

/**
 * @type {number}
 */
ydn.http.CallbackResult.prototype.status;

/**
 * @type {string}
 */
ydn.http.CallbackResult.prototype.contentType;

/**
 * @type {string}
 */
ydn.http.CallbackResult.prototype.responseText;

/**
 * @type {string}
 */
ydn.http.CallbackResult.prototype.url;

/**
 * @type {*}
 */
ydn.http.CallbackResult.prototype.response;

/**
 * @type {Object.<string>}
 */
ydn.http.CallbackResult.prototype.headers;

/**
 *
 * @param {!Object} result_json
 * @return {ydn.http.CallbackResult}
 */
ydn.http.CallbackResult.wrap = function (result_json) {
  if (result_json instanceof ydn.http.CallbackResult) {
    return result_json;
  } else {
    return new ydn.http.CallbackResult(
        result_json['contentType'],
        result_json['responseText'],
        result_json['url'],
        result_json['status'],
        result_json['response'],
        result_json['headers']);
  }
};

/**
 *
 * @param {string} header the header
 * @return {string|undefined} header value
 */
ydn.http.CallbackResult.prototype.getHeader = function(header) {
  return this.headers[header];
};

/**
 *
 * @return {!Object}
 */
ydn.http.CallbackResult.prototype.getResponseJson = function() {
  var is_content_json = this.contentType == 'json' ||
      goog.string.startsWith(this.contentType, 'application/json');
  if (is_content_json &&
      this.response != null && typeof this.response == 'object') {
    return /** @type {!Object} */ (this.response);
  } else {
    return ydn.json.parse(this.responseText);
  }
};

/**
 *
 * @return {number}
 */
ydn.http.CallbackResult.prototype.getStatus = function() {
  return this.status;
};

/**
 *
 * @return {string}
 */
ydn.http.CallbackResult.prototype.getUrl = function() {
  return this.url;
};

/**
 *
 * @return {boolean}
 */
ydn.http.CallbackResult.prototype.isSuccessStatusCode = function() {
  return this.status >= 200 && this.status < 400;
};

/**
 * Return status and shortened text from the result.
 * @return {string}
 */
ydn.http.CallbackResult.prototype.getMessage = function() {
  var txt = goog.isString(this.responseText) ?
    this.responseText.substring(0, 200) : '';
  return this.status + ': ' + txt;
};

/**
 *
 * @return {boolean} if content_type is json
 */
ydn.http.CallbackResult.prototype.isContentJson = function() {
  return /application\/json/.test(this.contentType);
};

/**
 *
 * @return {boolean} if content_type is javascript
 */
ydn.http.CallbackResult.prototype.isContentJavascript = function() {
  return /text\/javascript/.test(this.contentType);
};

/**
 * @return {string}
 */
ydn.http.CallbackResult.prototype.toString = function() {
  if (goog.DEBUG) {
    var msg = this.message ? this.message : this.responseText;
    return this.status + ' ' + this.url + ' ' + msg;
  } else {
    return goog.base(this, 'toString');
  }
};

/**
 *
 * @interface
 */
ydn.http.ITransport = function() {};

/**
 * @typedef {{
 * method: (string|undefined),
 * body: (string|undefined),
 * headers: (Object.<string>|undefined),
 * params: (Object.<string>|undefined)
 * }}
 */
ydn.http.ITransport.Options;

/**
 *
 * @param {Object=} options given option
 * @return {!ydn.http.ITransport.Options} return given options if not
 * default options. input argument is not modified.
 */
ydn.http.getDefaultOptions = function(options) {
  var default_options = {
    method: 'GET',
    body: undefined,
    headers: {},
    params: {}

  };
  if (goog.isDefAndNotNull(options)) {
    return {
      method: options.method || default_options.method,
      body: options.body,
      headers: options.headers || {},
      params: options.params || {}
    }
  } else {
    return default_options;
  }
};

/**
 * Submit HTTP request.
 *
 * @param {string} url
 * @param {function(ydn.http.CallbackResult)=} opt_callback
 * @param {ydn.http.ITransport.Options=} opt_options
 * @return {goog.async.Deferred|undefined} if not provided, callback result
 * is return in the deferred function.
 */
ydn.http.ITransport.prototype.send =  function(url, opt_callback, opt_options) {

};

/**
 *
 * @constructor
 * @implements {ydn.http.ITransport}
 */
ydn.http.Transport = function() {};

/**
 * @inheritDoc
 */
ydn.http.Transport.prototype.send = goog.abstractMethod;

<|endoftext|>


<commit_before>iD.ui.Geocoder = function(context) {

    var key = 'f';

    function resultExtent(bounds) {
        return new iD.geo.Extent(
            [parseFloat(bounds[3]), parseFloat(bounds[0])],
            [parseFloat(bounds[2]), parseFloat(bounds[1])]);
    }

    function geocoder(selection) {

        var shown = false;

        function keydown() {
            if (d3.event.keyCode !== 13) return;
            d3.event.preventDefault();
            var searchVal = this.value;
            inputNode.classed('loading', true);
            d3.json('http://nominatim.openstreetmap.org/search/' +
                encodeURIComponent(searchVal) + '?limit=10&format=json', function(err, resp) {
                    inputNode.classed('loading', false);
                    if (err) return hide();
                    if (!resp.length) {
                        resultsList.html('')
                            .call(iD.ui.Toggle(true))
                            .append('span')
                                .attr('class', 'not-found')
                                .text(t('geocoder.no_results', {name: searchVal}));
                    } else if (resp.length > 1) {
                        var spans = resultsList.html('').selectAll('span')
                            .data(resp, function(d) { return d.place_id; });

                        spans.enter()
                            .append('span')
                            .text(function(d) {
                                return d.type.charAt(0).toUpperCase() + d.type.slice(1) + ': ';
                            })
                            .append('a')
                            .attr('tabindex', 1)
                            .text(function(d) {
                                if (d.display_name.length > 80) {
                                    return d.display_name.substr(0, 80) + '…';
                                } else {
                                    return d.display_name;
                                }
                            })
                            .on('click', clickResult)
                            .on('keydown', function(d) {
                                // support tabbing to and accepting this
                                // entry
                                if (d3.event.keyCode == 13) clickResult(d);
                            });
                        spans.exit().remove();
                        resultsList.call(iD.ui.Toggle(true));
                    } else {
                        applyBounds(resultExtent(resp[0].boundingbox));
                        selectId(resp[0].osm_type, resp[0].osm_id);
                    }
                });
        }

        function clickResult(d) {
            selectId(d.osm_type, d.osm_id);
            applyBounds(resultExtent(d.boundingbox));
        }

        function applyBounds(extent) {
            hide();
            var map = context.map();
            map.extent(extent);
            if (map.zoom() > 19) map.zoom(19);
        }

        function selectId(type, id) {
            id = type[0] + id;

            if (context.entity(id)) {
                context.enter(iD.modes.Select(context, [id]));

            } else {
                context.map().on('drawn.geocoder', function() {
                    if (!context.entity(id)) return;
                    context.enter(iD.modes.Select(context, [id]));
                });

                context.on('enter.geocoder', function() {
                    if (context.mode().id !== 'browse') {
                        context.map()
                            .on('drawn.geocoder', null)
                            .on('enter.geocoder', null);
                    }
                });
            }
        }

        var tooltip = bootstrap.tooltip()
            .placement('right')
            .html(true)
            .title(iD.ui.tooltipHtml(t('geocoder.title'), key));

        var gcForm = selection.append('form');

        var inputNode = gcForm.attr('class', 'fillL map-overlay content hide')
            .append('input')
            .attr({ type: 'text', placeholder: t('geocoder.placeholder') })
            .attr('tabindex', 1)
            .on('keydown', keydown);

        var resultsList = selection.append('div')
            .attr('class', 'fillL map-overlay hide');

        var keybinding = d3.keybinding('geocoder');

        function hide() { setVisible(false); }
        function toggle() {
            if (d3.event) d3.event.preventDefault();
            tooltip.hide(button);
            setVisible(!button.classed('active'));
        }

        function setVisible(show) {
            if (show !== shown) {
                button.classed('active', show);
                shown = show;

                if (!show && !resultsList.classed('hide')) {
                    resultsList.call(iD.ui.Toggle(show));
                    // remove results so that they lose focus. if the user has
                    // tabbed into the list, then they will have focus still,
                    // even if they're hidden.
                    resultsList.selectAll('span').remove();
                }

                if (show) {
                    selection.on('mousedown.geocoder-inside', function() {
                        return d3.event.stopPropagation();
                    });
                    gcForm.style('display', 'block')
                        .style('left', '-500px')
                        .transition()
                        .duration(200)
                        .style('left', '30px');
                        inputNode.node().focus();
                } else {
                    selection.on('mousedown.geocoder-inside', null);
                    gcForm.style('display', 'block')
                        .style('left', '30px')
                        .transition()
                        .duration(200)
                        .style('left', '-500px')
                        .each('end', function() {
                            d3.select(this).style('display', 'none');
                        });
                    inputNode.node().blur();
                }
            }
        }
        var button = selection.append('button')
            .attr('tabindex', -1)
            .on('click', toggle)
            .call(tooltip);

        button.append('span')
            .attr('class', 'icon geocode light');

        keybinding.on(key, toggle);

        d3.select(document)
            .call(keybinding);

        context.surface().on('mousedown.geocoder-outside', hide);
        context.container().on('mousedown.b.geocoder-outside', hide);

    }
    return geocoder;
};
<commit_msg>fix geocoder<commit_after>iD.ui.Geocoder = function(context) {

    var key = 'f';

    function resultExtent(bounds) {
        return new iD.geo.Extent(
            [parseFloat(bounds[3]), parseFloat(bounds[0])],
            [parseFloat(bounds[2]), parseFloat(bounds[1])]);
    }

    function geocoder(selection) {

        var shown = false;

        function keydown() {
            if (d3.event.keyCode !== 13) return;
            d3.event.preventDefault();
            var searchVal = this.value;
            inputNode.classed('loading', true);
            d3.json('http://nominatim.openstreetmap.org/search/' +
                encodeURIComponent(searchVal) + '?limit=10&format=json', function(err, resp) {
                    inputNode.classed('loading', false);
                    if (err) return hide();
                    if (!resp.length) {
                        resultsList.html('')
                            .call(iD.ui.Toggle(true))
                            .append('span')
                                .attr('class', 'not-found')
                                .text(t('geocoder.no_results', {name: searchVal}));
                    } else if (resp.length > 1) {
                        var spans = resultsList.html('').selectAll('span')
                            .data(resp, function(d) { return d.place_id; });

                        spans.enter()
                            .append('span')
                            .text(function(d) {
                                return d.type.charAt(0).toUpperCase() + d.type.slice(1) + ': ';
                            })
                            .append('a')
                            .attr('tabindex', 1)
                            .text(function(d) {
                                if (d.display_name.length > 80) {
                                    return d.display_name.substr(0, 80) + '…';
                                } else {
                                    return d.display_name;
                                }
                            })
                            .on('click', clickResult)
                            .on('keydown', function(d) {
                                // support tabbing to and accepting this
                                // entry
                                if (d3.event.keyCode == 13) clickResult(d);
                            });
                        spans.exit().remove();
                        resultsList.call(iD.ui.Toggle(true));
                    } else {
                        applyBounds(resultExtent(resp[0].boundingbox));
                        selectId(resp[0].osm_type, resp[0].osm_id);
                    }
                });
        }

        function clickResult(d) {
            selectId(d.osm_type, d.osm_id);
            applyBounds(resultExtent(d.boundingbox));
        }

        function applyBounds(extent) {
            hide();
            var map = context.map();
            map.extent(extent);
            if (map.zoom() > 19) map.zoom(19);
        }

        function selectId(type, id) {
            id = type[0] + id;

            if (context.entity(id)) {
                context.enter(iD.modes.Select(context, [id]));

            } else {
                context.map().on('drawn.geocoder', function() {
                    if (!context.entity(id)) return;
                    context.enter(iD.modes.Select(context, [id]));
                });

                context.on('enter.geocoder', function() {
                    if (context.mode().id !== 'browse') {
                        context.on('enter.geocoder', null)
                            .map().on('drawn.geocoder', null);
                    }
                });
            }
        }

        var tooltip = bootstrap.tooltip()
            .placement('right')
            .html(true)
            .title(iD.ui.tooltipHtml(t('geocoder.title'), key));

        var gcForm = selection.append('form');

        var inputNode = gcForm.attr('class', 'fillL map-overlay content hide')
            .append('input')
            .attr({ type: 'text', placeholder: t('geocoder.placeholder') })
            .attr('tabindex', 1)
            .on('keydown', keydown);

        var resultsList = selection.append('div')
            .attr('class', 'fillL map-overlay hide');

        var keybinding = d3.keybinding('geocoder');

        function hide() { setVisible(false); }
        function toggle() {
            if (d3.event) d3.event.preventDefault();
            tooltip.hide(button);
            setVisible(!button.classed('active'));
        }

        function setVisible(show) {
            if (show !== shown) {
                button.classed('active', show);
                shown = show;

                if (!show && !resultsList.classed('hide')) {
                    resultsList.call(iD.ui.Toggle(show));
                    // remove results so that they lose focus. if the user has
                    // tabbed into the list, then they will have focus still,
                    // even if they're hidden.
                    resultsList.selectAll('span').remove();
                }

                if (show) {
                    selection.on('mousedown.geocoder-inside', function() {
                        return d3.event.stopPropagation();
                    });
                    gcForm.style('display', 'block')
                        .style('left', '-500px')
                        .transition()
                        .duration(200)
                        .style('left', '30px');
                        inputNode.node().focus();
                } else {
                    selection.on('mousedown.geocoder-inside', null);
                    gcForm.style('display', 'block')
                        .style('left', '30px')
                        .transition()
                        .duration(200)
                        .style('left', '-500px')
                        .each('end', function() {
                            d3.select(this).style('display', 'none');
                        });
                    inputNode.node().blur();
                }
            }
        }
        var button = selection.append('button')
            .attr('tabindex', -1)
            .on('click', toggle)
            .call(tooltip);

        button.append('span')
            .attr('class', 'icon geocode light');

        keybinding.on(key, toggle);

        d3.select(document)
            .call(keybinding);

        context.surface().on('mousedown.geocoder-outside', hide);
        context.container().on('mousedown.b.geocoder-outside', hide);

    }
    return geocoder;
};
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */
/*globals async, caches, fetch, Response, Request, self*/
/*exported CacheTasks */

"use strict";
(function(exports) {
  /**
   * Collection of common task performed by a Service Worker cache.
   */
  const openedCaches = new Map();
  const memoizedCaches = {
    open: async(function*(cacheName) {
      if (openedCaches.has(cacheName)) {
        return openedCaches.get(cacheName);
      }
      var cache = yield caches.open(cacheName);
      openedCaches.set(cacheName, cache);
      return cache;
    })
  };

  const CacheTasks = {
    /**
     * Populates the a cache with a list of requests.
     *
     * @param {String} cacheName The name of the cache.
     * @param {Array} requests The requests (URLs or Requests) to cache.
     */
    populateCache: async(function* (cacheName, requests) {
      var cache = yield memoizedCaches.open(cacheName);
      var success = true;
      try {
        yield cache.addAll(requests);
      } catch (err) {
        var msg = `Error adding resources to cache ${cacheName}.`;
        console.warn(msg, err);
        success = false;
      }
      return success;
    }),
    /**
     * Saves a binary file into a cache.
     *
     * @param {String} cacheName The name of the cache to save into.
     * @param {ArrayBuffer} arrayBuffer The arrayBuffer holding the file's data.
     * @param {String} type MimeType of the data being stored.
     * @param {String|URL} requestURL The URL this request maps to.
     */
    saveBinaryToCache: async(function* (cacheName, arrayBuffer, type, requestURL) {
      var cache = yield memoizedCaches.open(cacheName);
      var blob = new Blob([arrayBuffer], {
        type
      });
      var responseInit = {
        headers: {
          "Content-Type": type,
        }
      };
      var request = new Request(requestURL);
      var response = new Response(blob, responseInit);
      try {
        yield cache.put(request, response);
      } catch (err) {
        var msg = `putting blob in cache ${cacheName} for ${requestURL}.`;
        console.warn(msg, err);
        throw err;
      }
    }),
    /**
     * Respond to a request from the SW's caches.
     *
     * @param {Request|String} request The request
     * @param {String} [cacheName] The name of the cache to look in.
     * @param {String} [strategy] The strategy to use when the response
     *                              is not found. "throw" causes this to throw
     *                              otherwise, it passes the request to the
     *                              network via fetch.
     */
    respondFromCache: async(function* (request, cacheName, strategy = "") {
      var cache = yield memoizedCaches.open(cacheName);
      var url = request.url || request;
      var response = yield cache.match(request);
      var msg = "";
      if (response) {
        return response;
      }
      switch (strategy) {
      case "throw":
        msg = `Not found in ${cacheName} cache: ${url}`;
        var error = new Error(msg);
        console.warn(error);
        throw error;
      case "store":
        try {
          response = yield fetch(request);
          yield cache.put(request, response.clone());
        } catch (err) {
          var msg = `failed to store ${url} in ${cacheName}.`;
          console.warn(msg, err);
          throw err;
        }
        break;
      //Default passes the request to network using fetch()
      default:
        msg = `Not in cache ${cacheName}. Fetching but not storing: ${url}`;
        console.warn(msg);
        response = yield fetch(request);
        break;
      }
      return response;
    }),
    /**
     * Checks if there is a cache entry for a particular request.
     *
     * @param {Request|String} request The request to check for.
     * @param {String} [cacheName] The cache's name to look in.
     * @return {Boolean} True if it has the request, false otherwise.
     */
    hasCacheEntry: async(function* (request, cacheName) {
      var cache = yield memoizedCaches.open(cacheName);
      var response = yield cache.match(request);
      return (response) ? true : false;
    }),
    /**
     * Deletes a cache entry.
     *
     * @param {Request[]|String[]} request The request.
     * @param {String} cacheName The cache name from where to delete.
     * @returns {Boolean}
     */
    deleteCacheEntry: async(function* (request, cacheName, options={}) {
      var cache = yield memoizedCaches.open(cacheName);
      var result = yield cache.delete(request, options);
      return result;
    }),
    /**
     * Delete all the SW's caches.
     *
     * @returns {Map<String,Boolean>} A map representing the keys and the result
     *                                of deleting the cache.
     */
    deleteAllCaches: async(function* () {
      var keys = yield caches.keys();
      var promises = keys.map(key => caches.delete(key));
      var results = yield Promise.all(promises);
      var keyResult = new Map();
      keys.forEach((key, index) => keyResult.set(key, results[index]));
      return keyResult;
    }),
  };
  exports.CacheTasks = CacheTasks;
}(self));
<commit_msg>feat(cachetasks): don't need this anymore<commit_after><|endoftext|>


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

// !dependencies: false

ilib.CType=CType;ilib._roundFnc={};
ilib.Date=DateFactory;ilib.Cal=CalendarFactory;ilib.Measurement=MeasurementFactory;ilib.extend2(ilib.Date, Astro);
ilib.shallowCopy=JSUtils.shallowCopy;ilib.deepCopy=JSUtils.deepCopy;ilib.mapString=JSUtils.mapString;ilib.indexOf=JSUtils.indexOf;ilib.toHexString=JSUtils.toHexString;ilib.isDate=JSUtils.isDate;ilib.merge=JSUtils.merge;ilib.isEmpty=JSUtils.isEmpty;ilib.hashCode=JSUtils.hashCode;ilib.Locale=Locale;ilib.mergeLocData=Utils.mergeLocData;ilib.getLocFiles=Utils.getLocFiles;ilib.loadData=Utils.loadData;ilib.LocaleInfo=LocaleInfo;ilib.signum=MathUtils.signum;ilib.mod=MathUtils.mod;ilib.amod=MathUtils.amod;ilib.String=IString;ilib.Cal.newInstance=CalendarFactory;ilib.Cal.getCalendars=CalendarFactory.getCalendars;ilib.Cal.Gregorian=GregorianCal;ilib.JulianDay=JulianDay;ilib.Date.RataDie=RataDie;ilib.Date.GregRataDie=GregRataDie;ilib.TimeZone=TimeZone;ilib.bsearch=SearchUtils.bsearch;ilib.bisectionSearch=SearchUtils.bisectionSearch;ilib.Date.GregDate=GregorianDate;ilib.Date.newInstance=DateFactory;ilib.ResBundle=ResBundle;ilib.DateFmt=DateFmt;ilib.DateRngFmt=DateRngFmt;ilib.Cal.Hebrew=HebrewCal;ilib.Date.HebrewDate=HebrewDate;ilib.Cal.Islamic=IslamicCal;ilib.Date.IslamicDate=IslamicDate;ilib.Cal.Julian=JulianCal;ilib.Date.JulDate=JulianDate;ilib.Date.JulRataDie=JulianRataDie;
ilib.Cal.ThaiSolar=ThaiSolarCal;ilib.Date.ThaiSolarDate=ThaiSolarDate;ilib.Date.initAstro=Astro.initAstro;ilib.Date.PersAstroRataDie=PersRataDie;ilib.Cal.Persian=PersianCal;ilib.Date.PersDate=PersianDate;ilib.Cal.PersianAlgo=PersianAlgoCal;ilib.Date.PersAlgoDate=PersianAlgoDate;ilib.Date.PersAlgoRataDie=PersAlgoRataDie;ilib.Cal.Han=HanCal;ilib.Date.HanDate=HanDate;ilib.Date.HanRataDie=HanRataDie;
ilib.Cal.Ethiopic=EthiopicCal;ilib.Date.EthiopicDate=EthiopicDate;ilib.Date.EthiopicRataDie = EthiopicRataDie;
ilib.Cal.Coptic=CopticCal;ilib.Date.CopticDate=CopticDate;ilib.Date.CopticRataDie=CopticRataDie;
ilib.CType.isDigit=isDigit;ilib.CType.isSpace=isSpace;ilib.Currency=Currency;ilib.Number=INumber;ilib.NumFmt=NumFmt;ilib.DurFmt=DurationFmt;ilib.CType.isAlpha=isAlpha;ilib.CType.isAlnum=isAlnum;ilib.CType.isAscii=isAscii;ilib.CType.isBlank=isBlank;ilib.CType.isCntrl=isCntrl;ilib.CType.isGraph=isGraph;ilib.CType.isIdeo=isIdeo;ilib.CType.isLower=isLower;ilib.CType.isPrint=isPrint;ilib.CType.isPunct=isPunct;ilib.CType.isUpper=isUpper;ilib.CType.isXdigit=isXdigit;ilib.CType.isScript=isScript;ilib.ScriptInfo=ScriptInfo;ilib.Name=Name;ilib.NameFmt=NameFmt;ilib.Address=Address;ilib.AddressFmt=AddressFmt;ilib.GlyphString=GlyphString;ilib.NormString=NormString;ilib.CodePointSource=CodePointSource;ilib.ElementIterator=ElementIterator;ilib.Collator=Collator;ilib.LocaleMatcher=LocaleMatcher;ilib.CaseMapper=CaseMapper;ilib.NumPlan=NumberingPlan;ilib.PhoneLoc=PhoneLocale;ilib.StateHandler=PhoneHandler;ilib._handlerFactory=PhoneHandlerFactory;ilib.PhoneNumber=PhoneNumber;ilib.PhoneFmt=PhoneFmt;ilib.GeoLocator=PhoneGeoLocator;ilib.Measurement.Unknown=UnknownUnit;ilib.Measurement.Area=AreaUnit;ilib.Measurement.DigitalStorage=DigitalStorageUnit;ilib.Measurement.Energy=EnergyUnit;ilib.Measurement.FuelConsumption=FuelConsumptionUnit;ilib.Measurement.Length=LengthUnit;ilib.Measurement.Mass=MassUnit;ilib.Measurement.Temperature=TemperatureUnit;ilib.Measurement.Time=TimeUnit;ilib.Measurement.Speed=VelocityUnit;ilib.Measurement.Volume=VolumeUnit;ilib.UnitFmt=UnitFmt;
<commit_msg>Generated file<commit_after>/* This is a generated file. DO NOT EDIT, as your changes will be lost. */
/* Instead, fix the code in mkstubs.js which generated this file.       */
ilib.CType=CType;ilib._roundFnc={};
ilib.Date=IDate;ilib.Cal=Calendar;ilib.Measurement=MeasurementFactory;
ilib.shallowCopy=JSUtils.shallowCopy;ilib.deepCopy=JSUtils.deepCopy;ilib.mapString=JSUtils.mapString;ilib.indexOf=JSUtils.indexOf;ilib.isDate=JSUtils.isDate;ilib.merge=JSUtils.merge;ilib.isEmpty=JSUtils.isEmpty;ilib.hashCode=JSUtils.hashCode;ilib.Locale=Locale;ilib.mergeLocData=Utils.mergeLocData;ilib.getLocFiles=Utils.getLocFiles;ilib.loadData=Utils.loadData;ilib.LocaleInfo=LocaleInfo;ilib.signum=MathUtils.signum;ilib.mod=MathUtils.mod;ilib.amod=MathUtils.amod;ilib.String=IString;ilib.Cal.newInstance=CalendarFactory;ilib.Cal.getCalendars=CalendarFactory.getCalendars;ilib.Cal.Gregorian=GregorianCal;ilib.JulianDay=JulianDay;ilib.Date.RataDie=RataDie;ilib.Date.GregRataDie=GregRataDie;ilib.TimeZone=TimeZone;ilib.bsearch=SearchUtils.bsearch;ilib.bisectionSearch=SearchUtils.bisectionSearch;ilib.Date.GregDate=GregorianDate;ilib.Date.newInstance=DateFactory;ilib.ResBundle=ResBundle;ilib.DateFmt=DateFmt;ilib.DateRngFmt=DateRngFmt;ilib.Cal.Hebrew=HebrewCal;ilib.Date.HebrewDate=HebrewDate;ilib.Cal.Islamic=IslamicCal;ilib.Date.IslamicDate=IslamicDate;ilib.Cal.Julian=JulianCal;ilib.Date.JulianDate=JulianDate;ilib.Cal.ThaiSolar=ThaiSolarCal;ilib.Date.ThaiSolarDate=ThaiSolarDate;ilib.Date.PersAstroRataDie=PersRataDie;ilib.Cal.Persian=PersianCal;ilib.Date.PersDate=PersianDate;ilib.Cal.PersianAlgo=PersianAlgoCal;ilib.Date.PersAlgoDate=PersianAlgoDate;ilib.Cal.Han=HanCal;ilib.Date.HanDate=HanDate;ilib.Cal.Ethiopic=EthiopicCal;ilib.Date.EthiopicDate=EthiopicDate;ilib.Cal.Coptic=CopticCal;ilib.Date.CopticDate=CopticDate;ilib.CType.isDigit=isDigit;ilib.CType.isSpace=isSpace;ilib.Currency=Currency;ilib.Number=INumber;ilib.NumFmt=NumFmt;ilib.DurFmt=DurationFmt;ilib.CType.isAlpha=isAlpha;ilib.CType.isAlnum=isAlnum;ilib.CType.isAscii=isAscii;ilib.CType.isBlank=isBlank;ilib.CType.isCntrl=isCntrl;ilib.CType.isGraph=isGraph;ilib.CType.isIdeo=isIdeo;ilib.CType.isLower=isLower;ilib.CType.isPrint=isPrint;ilib.CType.isPunct=isPunct;ilib.CType.isUpper=isUpper;ilib.CType.isXdigit=isXdigit;ilib.CType.isScript=isScript;ilib.ScriptInfo=ScriptInfo;ilib.Name=Name;ilib.NameFmt=NameFmt;ilib.Address=Address;ilib.AddressFmt=AddressFmt;ilib.GlyphString=GlyphString;ilib.NormString=NormString;ilib.CodePointSource=CodePointSource;ilib.ElementIterator=ElementIterator;ilib.Collator=Collator;ilib.LocaleMatcher=LocaleMatcher;ilib.CaseMapper=CaseMapper;ilib.NumPlan=NumberingPlan;ilib.PhoneLoc=PhoneLocale;ilib.StateHandler=PhoneHandler;ilib.PhoneNumber=PhoneNumber;ilib.PhoneFmt=PhoneFmt;ilib.GeoLocator=PhoneGeoLocator;ilib.Measurement.Unknown=UnknownUnit;ilib.Measurement.Area=AreaUnit;ilib.Measurement.DigitalStorage=DigitalStorageUnit;ilib.Measurement.Energy=EnergyUnit;ilib.Measurement.FuelConsumption=FuelConsumptionUnit;ilib.Measurement.Length=LengthUnit;ilib.Measurement.Mass=MassUnit;ilib.Measurement.Temperature=TemperatureUnit;ilib.Measurement.Time=TimeUnit;ilib.Measurement.Speed=VelocityUnit;ilib.Measurement.Volume=VolumeUnit;ilib.UnitFmt=UnitFmt;
<|endoftext|>


<commit_before>(function (__undefined) {
    this.GgpkEntry = Class.extend({
        init: function (props) {
            this.props = props;
        },
        valueAsArray: function (key) {
            // filter(empty) + map(parseInt)
            return $.map(this.getProp(key).split(","), function (n) {
                if (n === null || n === '') {
                    return null;
                }
                return +n;
            });
        },
        getProp: function (key) {
            if (this.props[key] === __undefined) {
                console.log("key `" + key + "` doesnt exist");
            }
            return this.props[key];
        },
        setProp: function (key, value) {
            if (this.props[key] !== __undefined) {
                this.props[key] = value;
            }
        }
    });
})();

<commit_msg>string support<commit_after>(function (__undefined) {
    this.GgpkEntry = Class.extend({
        init: function (props) {
            this.props = props;
        },
        valueAsArray: function (key) {
            // filter(empty) + map(parseInt)
            return $.map(this.getProp(key).split(","), function (n) {
                if (n === null || n === '') {
                    return null;
                }

                if (isNaN(+n)) {
                    return n;
                }
                return +n;
            });
        },
        getProp: function (key) {
            if (this.props[key] === __undefined) {
                console.log("key `" + key + "` doesnt exist");
            }
            return this.props[key];
        },
        setProp: function (key, value) {
            if (this.props[key] !== __undefined) {
                this.props[key] = value;
            }
        }
    });
})();

<|endoftext|>