<commit_before>var INACCURATE_MARKER_OPACITY = 0.5;

var MarkerView = Backbone.View.extend({
    events : {
        "click .delete-button" : "clickDelete",
        "click .accordion-container input" : "accordionInputClick"
    },
    initialize : function(options) {
        this.map = options.map;
        _.bindAll(this, "clickMarker");
    },
    localize : function(field,value) {
        //localizes non-mandatory data (which has the same consistent html and python field names)
            if (this.model.has(value) && this.model.get(value)!="" &&
                    localization[field][this.model.get(value)]!=undefined) {
                this.$el.find("." + value).text(fields[field] + ": " + localization[field][this.model.get(value)]);
        }
    },

    render : function() {

        var markerPosition = new google.maps.LatLng(this.model.get("latitude"),
                                                    this.model.get("longitude"));

        this.marker = new google.maps.Marker({
            position: markerPosition,
            id: this.model.get("id")
        });

        if (this.model.get("type") == MARKER_TYPE_DISCUSSION) {
            this.marker.setIcon( app.retinaIconsResize(DISCUSSION_ICON) );
            this.marker.setTitle("דיון"); //this.model.get("title"));
            this.marker.setMap(this.map);
            this.marker.view = this;
            google.maps.event.addListener(this.marker, "click",
                _.bind(app.showDiscussion, app, this.model.get("identifier")) );
            return this;
        }

        //app.clusterer.addMarker(this.marker);
        if (app.map.zoom < MINIMAL_ZOOM) {
            return this;
        }

        this.marker.setOpacity(this.model.get("locationAccuracy") == 1 ? 1.0 : INACCURATE_MARKER_OPACITY);
        this.marker.setIcon(this.getIcon());
        this.marker.setTitle(this.getTitle());
        this.marker.setMap(this.map);
        this.marker.view = this;

        app.oms.addMarker(this.marker);

        this.$el.html($("#marker-content-template").html());

        this.$el.width(400);
        this.$el.find(".title").text(this.marker.get("title"));
        this.$el.find(".id").text(fields.ACC_ID + ": " + this.marker.get("id"));
        this.$el.find(".provider_code").text(fields.PROVIDER_CODE + ": " + this.model.get("provider_code"));
        this.$el.find(".roadType").text(fields.SUG_DEREH + ": " + localization.SUG_DEREH[this.model.get("roadType")]);
        this.$el.find(".accidentType").text(fields.SUG_TEUNA+ ": " + localization.SUG_TEUNA[this.model.get("subtype")]);
        this.$el.find(".roadShape").text(fields.ZURAT_DEREH+ ": " + localization.ZURAT_DEREH[this.model.get("roadShape")]);
        this.$el.find(".severityText").text(fields.HUMRAT_TEUNA + ": " + localization.HUMRAT_TEUNA[this.model.get("severity")]);
        this.$el.find(".dayType").text(fields.SUG_YOM + ": " + localization.SUG_YOM[this.model.get("dayType")]);
        this.$el.find(".igun").text(fields.STATUS_IGUN + ": " + localization.STATUS_IGUN[this.model.get("locationAccuracy")]);
        this.$el.find(".unit").text(fields.YEHIDA + ": " + localization.YEHIDA[this.model.get("unit")]);
        this.$el.find(".mainStreet").text(this.model.get("mainStreet"));
        this.$el.find(".secondaryStreet").text(this.model.get("secondaryStreet"));
        this.$el.find(".junction").text(this.model.get("junction"));
        // Non-mandatory fields:
        this.localize("HAD_MASLUL","one_lane");
        this.localize("RAV_MASLUL","multi_lane");
        this.localize("MEHIRUT_MUTERET","speed_limit");
        this.localize("TKINUT","intactness");
        this.localize("ROHAV","road_width");
        this.localize("SIMUN_TIMRUR","road_sign");
        this.localize("TEURA","road_light");
        this.localize("BAKARA","road_control");
        this.localize("MEZEG_AVIR","weather");
        this.localize("PNE_KVISH","road_surface");
        this.localize("SUG_EZEM","road_object");
        this.localize("MERHAK_EZEM","object_distance");
        this.localize("LO_HAZA","didnt_cross");
        this.localize("OFEN_HAZIYA","cross_mode");
        this.localize("MEKOM_HAZIYA","cross_location");
        this.localize("KIVUN_HAZIYA","cross_direction");

        this.$el.find(".creation-date").text("תאריך: " +
                    moment(this.model.get("created")).format("LLLL"));
        this.$el.find(".profile-image").attr("src", "/static/img/lamas.png");
        this.$el.find(".profile-image").attr("width", "50px");
        display_user = 'הלשכה המרכזית לסטטיסטיקה';
        this.$el.find(".added-by").text("מקור: " + display_user);

        return this;
    },
    getIcon : function() {
        return getIcon(this.model.get("subtype"), this.model.get("severity"));
    },
    getTitle : function() {
        if (this.model.get("junction") !== "") {
        loc = this.model.get("junction");
        }
        else if (this.model.get("secondaryStreet") !== "") {
            loc = "ברחוב " + this.model.get("secondaryStreet") + " פינת " + this.model.get("mainStreet");
        }
        else if (this.model.get("mainStreet") !== "") {
            loc = "ברחוב " + this.model.get("mainStreet");
        }
        else {
            loc = "";
        }
        return "ביום " + moment(this.model.get("created")).format("dddd") + ", ה-"
        + moment(this.model.get("created")).format("LL")
        + " תאונה " + SEVERITY_MAP[this.model.get("severity")]
        + " מסוג " + localization.SUG_TEUNA[this.model.get("subtype")] + " "
        + loc;
    },
    choose : function() {
        if (app.oms.markersNearMarker(this.marker).length) {
            new google.maps.event.trigger(this.marker, "click");
        }
        new google.maps.event.trigger(this.marker, "click");
    },
    getUrl: function () {
        return "/?marker=" + this.model.get("id") + "&" + app.getCurrentUrlParams();
    },
    localize_data: function(data,field,value,dataType,involved_or_vehicles) {
        switch (dataType) {
            case "invs":
                if (inv_dict[field] != undefined && inv_dict[field][data[i][value]] != undefined) {
                    text_line = "
" + fields[field] + ": " + inv_dict[field][data[i][value]] + "
";
                    that.$el.find("#" + involved_or_vehicles).append(text_line);
                }
                break;

            case "vehs":
                if (veh_dict[field] != undefined && veh_dict[field][data[i][value]] != undefined) {
                    text_line = "
" + fields[field] + ": " + veh_dict[field][data[i][value]] + "
";
                    that.$el.find("#" + involved_or_vehicles).append(text_line);
                }
                break;

            case "nums":
                if (value == "seats" && data[i]["seats"] == 99) { break; };
                if ([data[i][value]] != undefined && [data[i][value]] != 0 && [data[i][value]] != -1) {
                    text_line = "
" + fields[field] + ": " + data[i][value] + "
";
                    that.$el.find("#" + involved_or_vehicles).append(text_line);
                }
                break;
        }
    },
    clickMarker : function() {
        that = this;
        this.highlight();
        app.closeInfoWindow();
        app.selectedMarker = this;

        if (this.marker_clicked) {
            app.infoWindow = new google.maps.InfoWindow({
                content: that.el
            });
            app.infoWindow.open(that.map, that.marker);
            app.updateUrl(that.getUrl());
        } else {
            this.marker_clicked = true;
            $.get("/markers/" + this.model.get("id"), function (data) {
                data = JSON.parse(data);

                var j = 1;
                for (i in data) {
                    if (data[i]["sex"] != undefined) {
                        text_line = "
פרטי אדם מעורב" + " " + (i*1+1) + "
";
                        that.$el.find("#involved").append(text_line);
                        that.localize_data(data,"SUG_MEORAV","involved_type","invs","involved");
                        that.localize_data(data,"SHNAT_HOZAA","license_acquiring_date","nums","involved");
                        that.localize_data(data,"KVUZA_GIL","age_group","nums","involved");
                        that.localize_data(data,"MIN","sex","invs","involved");
                        that.localize_data(data,"MAHOZ_MEGURIM","home_district","nums","involved");
                        that.localize_data(data,"SUG_REHEV_NASA_LMS","car_type","invs","involved");
                        that.localize_data(data,"EMZAE_BETIHUT","safety_measures","invs","involved");
                        that.localize_data(data,"HUMRAT_PGIA","injury_severity","invs","involved");
                        that.localize_data(data,"SUG_NIFGA_LMS","injured_type","invs","involved");
                        that.localize_data(data,"PEULAT_NIFGA_LMS","injured_position","invs","involved");
                        that.localize_data(data,"KVUTZAT_OHLUSIYA_LMS","population_type","nums","involved");
                        that.$el.find("#involved").append("

");
                    }else{
                        text_line = "
פרטי רכב מעורב" + " " + (j) + "
";
                        that.$el.find("#vehicles").append(text_line);
                        that.localize_data(data,"SUG_REHEV_LMS","vehicle_type","vehs","vehicles");
                        that.localize_data(data,"NEFAH","engine_volume","nums","vehicles");
                        that.localize_data(data,"SHNAT_YITZUR","manufacturing_year","nums","vehicles");
                        that.localize_data(data,"KIVUNE_NESIA","driving_directions","nums","vehicles");
                        that.localize_data(data,"MATZAV_REHEV","vehicle_status","vehs","vehicles");
                        that.localize_data(data,"SHIYUH_REHEV_LMS","vehicle_attribution","vehs","vehicles");
                        that.localize_data(data,"MEKOMOT_YESHIVA_LMS","seats","nums","vehicles");
                        that.localize_data(data,"MISHKAL_KOLEL_LMS","total_weight","nums","vehicles");
                        that.$el.find("#vehicles").append("

");
                        j++;
                    }
                }
                app.infoWindow = new google.maps.InfoWindow({
                    content: that.el
                });
                app.infoWindow.open(that.map, that.marker);
                app.updateUrl(that.getUrl());
            });
        }

        $(document).keydown(app.ESCinfoWindow);
    },
    highlight : function() {
        if (app.oms.markersNearMarker(this.marker, true)[0]  && !this.model.get("currentlySpiderfied")){
            this.resetOpacitySeverity();
        }
        this.marker.setAnimation(google.maps.Animation.BOUNCE);

        // ##############################
        // # Another option, if we don't want the somewhat unintuitive experience where an icon start's bouncing,
        // # but other icons in the same place stay still, will be to do like so: (option 2)
        // ##############################

        // _.each(app.oms.markersNearMarker(this.marker), function (marker){

        //     marker.setAnimation(google.maps.Animation.BOUNCE);

        // });
        // this.marker.setAnimation(google.maps.Animation.BOUNCE);

        // ## END (option 2)

    },
    unhighlight : function() {
        if (app.oms.markersNearMarker(this.marker, true)[0] && !this.model.get("currentlySpiderfied")){
            this.opacitySeverityForGroup();
        }
        this.marker.setAnimation(null);

        // ##############################
        // # Option 2
        // ##############################

        // _.each(app.oms.markersNearMarker(this.marker), function (marker){

        //     marker.setAnimation(null);

        // });
        // this.marker.setAnimation(null);

        // ## END (option 2)

    },
    clickShare : function() {
        FB.ui({
            method: "feed",
            name: this.model.get("title"),
            link: document.location.href,
            description: this.model.get("description"),
            caption: SUBTYPE_STRING[this.model.get("subtype")]
            // picture
        });
    },
    resetOpacitySeverity : function() {
        this.marker.icon = this.getIcon();
        this.marker.opacity = this.model.get("locationAccuracy") == 1 ? 1.0 : INACCURATE_MARKER_OPACITY;
    },
    opacitySeverityForGroup : function() {
        var group = this.model.get("groupID") -1;
        this.marker.icon = app.retinaIconsResize(MULTIPLE_ICONS[app.groupsData[group].severity]);
        if (app.groupsData[group].opacity != 'opaque'){
            this.marker.opacity = INACCURATE_MARKER_OPACITY / app.groupsData[group].opacity;
        }
    },
    accordionInputClick : function(e) {
        var input = e.currentTarget;
        if (input.checked){
            var infoWindow = $(input).parents(".marker-info-window");
            var labelTop = $(input).siblings("label").offset().top;
            var infoWindowPos = infoWindow.offset().top;
            var IwHalfHeight = infoWindow.height() / 2;
            var labelPosRelativeToIw = labelTop - infoWindowPos;
            if (labelPosRelativeToIw > IwHalfHeight) {
                var curIwScroll = infoWindow.scrollTop();
                var labelPos = labelTop - infoWindowPos + curIwScroll;

                setTimeout(function(){
                    var sectionHeightScroll = $(input).siblings(".accordion-roller").height() + curIwScroll;
                    var bestScrollTo = sectionHeightScroll < labelPos ? sectionHeightScroll : labelPos;
                    $(infoWindow).animate({
                        scrollTop: bestScrollTo
                    }, 1300);
                }.bind(this),550);
            }
        }
    }
});
<commit_msg>This commit fixes a situation in which the user starts scrolling during the autoScroll mechanism animation.<commit_after>var INACCURATE_MARKER_OPACITY = 0.5;

var MarkerView = Backbone.View.extend({
    events : {
        "click .delete-button" : "clickDelete",
        "click .accordion-container input" : "accordionInputClick"
    },
    initialize : function(options) {
        this.map = options.map;
        _.bindAll(this, "clickMarker");
    },
    localize : function(field,value) {
        //localizes non-mandatory data (which has the same consistent html and python field names)
            if (this.model.has(value) && this.model.get(value)!="" &&
                    localization[field][this.model.get(value)]!=undefined) {
                this.$el.find("." + value).text(fields[field] + ": " + localization[field][this.model.get(value)]);
        }
    },

    render : function() {

        var markerPosition = new google.maps.LatLng(this.model.get("latitude"),
                                                    this.model.get("longitude"));

        this.marker = new google.maps.Marker({
            position: markerPosition,
            id: this.model.get("id")
        });

        if (this.model.get("type") == MARKER_TYPE_DISCUSSION) {
            this.marker.setIcon( app.retinaIconsResize(DISCUSSION_ICON) );
            this.marker.setTitle("דיון"); //this.model.get("title"));
            this.marker.setMap(this.map);
            this.marker.view = this;
            google.maps.event.addListener(this.marker, "click",
                _.bind(app.showDiscussion, app, this.model.get("identifier")) );
            return this;
        }

        //app.clusterer.addMarker(this.marker);
        if (app.map.zoom < MINIMAL_ZOOM) {
            return this;
        }

        this.marker.setOpacity(this.model.get("locationAccuracy") == 1 ? 1.0 : INACCURATE_MARKER_OPACITY);
        this.marker.setIcon(this.getIcon());
        this.marker.setTitle(this.getTitle());
        this.marker.setMap(this.map);
        this.marker.view = this;

        app.oms.addMarker(this.marker);

        this.$el.html($("#marker-content-template").html());

        this.$el.width(400);
        this.$el.find(".title").text(this.marker.get("title"));
        this.$el.find(".id").text(fields.ACC_ID + ": " + this.marker.get("id"));
        this.$el.find(".provider_code").text(fields.PROVIDER_CODE + ": " + this.model.get("provider_code"));
        this.$el.find(".roadType").text(fields.SUG_DEREH + ": " + localization.SUG_DEREH[this.model.get("roadType")]);
        this.$el.find(".accidentType").text(fields.SUG_TEUNA+ ": " + localization.SUG_TEUNA[this.model.get("subtype")]);
        this.$el.find(".roadShape").text(fields.ZURAT_DEREH+ ": " + localization.ZURAT_DEREH[this.model.get("roadShape")]);
        this.$el.find(".severityText").text(fields.HUMRAT_TEUNA + ": " + localization.HUMRAT_TEUNA[this.model.get("severity")]);
        this.$el.find(".dayType").text(fields.SUG_YOM + ": " + localization.SUG_YOM[this.model.get("dayType")]);
        this.$el.find(".igun").text(fields.STATUS_IGUN + ": " + localization.STATUS_IGUN[this.model.get("locationAccuracy")]);
        this.$el.find(".unit").text(fields.YEHIDA + ": " + localization.YEHIDA[this.model.get("unit")]);
        this.$el.find(".mainStreet").text(this.model.get("mainStreet"));
        this.$el.find(".secondaryStreet").text(this.model.get("secondaryStreet"));
        this.$el.find(".junction").text(this.model.get("junction"));
        // Non-mandatory fields:
        this.localize("HAD_MASLUL","one_lane");
        this.localize("RAV_MASLUL","multi_lane");
        this.localize("MEHIRUT_MUTERET","speed_limit");
        this.localize("TKINUT","intactness");
        this.localize("ROHAV","road_width");
        this.localize("SIMUN_TIMRUR","road_sign");
        this.localize("TEURA","road_light");
        this.localize("BAKARA","road_control");
        this.localize("MEZEG_AVIR","weather");
        this.localize("PNE_KVISH","road_surface");
        this.localize("SUG_EZEM","road_object");
        this.localize("MERHAK_EZEM","object_distance");
        this.localize("LO_HAZA","didnt_cross");
        this.localize("OFEN_HAZIYA","cross_mode");
        this.localize("MEKOM_HAZIYA","cross_location");
        this.localize("KIVUN_HAZIYA","cross_direction");

        this.$el.find(".creation-date").text("תאריך: " +
                    moment(this.model.get("created")).format("LLLL"));
        this.$el.find(".profile-image").attr("src", "/static/img/lamas.png");
        this.$el.find(".profile-image").attr("width", "50px");
        display_user = 'הלשכה המרכזית לסטטיסטיקה';
        this.$el.find(".added-by").text("מקור: " + display_user);

        return this;
    },
    getIcon : function() {
        return getIcon(this.model.get("subtype"), this.model.get("severity"));
    },
    getTitle : function() {
        if (this.model.get("junction") !== "") {
        loc = this.model.get("junction");
        }
        else if (this.model.get("secondaryStreet") !== "") {
            loc = "ברחוב " + this.model.get("secondaryStreet") + " פינת " + this.model.get("mainStreet");
        }
        else if (this.model.get("mainStreet") !== "") {
            loc = "ברחוב " + this.model.get("mainStreet");
        }
        else {
            loc = "";
        }
        return "ביום " + moment(this.model.get("created")).format("dddd") + ", ה-"
        + moment(this.model.get("created")).format("LL")
        + " תאונה " + SEVERITY_MAP[this.model.get("severity")]
        + " מסוג " + localization.SUG_TEUNA[this.model.get("subtype")] + " "
        + loc;
    },
    choose : function() {
        if (app.oms.markersNearMarker(this.marker).length) {
            new google.maps.event.trigger(this.marker, "click");
        }
        new google.maps.event.trigger(this.marker, "click");
    },
    getUrl: function () {
        return "/?marker=" + this.model.get("id") + "&" + app.getCurrentUrlParams();
    },
    localize_data: function(data,field,value,dataType,involved_or_vehicles) {
        switch (dataType) {
            case "invs":
                if (inv_dict[field] != undefined && inv_dict[field][data[i][value]] != undefined) {
                    text_line = "
" + fields[field] + ": " + inv_dict[field][data[i][value]] + "
";
                    that.$el.find("#" + involved_or_vehicles).append(text_line);
                }
                break;

            case "vehs":
                if (veh_dict[field] != undefined && veh_dict[field][data[i][value]] != undefined) {
                    text_line = "
" + fields[field] + ": " + veh_dict[field][data[i][value]] + "
";
                    that.$el.find("#" + involved_or_vehicles).append(text_line);
                }
                break;

            case "nums":
                if (value == "seats" && data[i]["seats"] == 99) { break; };
                if ([data[i][value]] != undefined && [data[i][value]] != 0 && [data[i][value]] != -1) {
                    text_line = "
" + fields[field] + ": " + data[i][value] + "
";
                    that.$el.find("#" + involved_or_vehicles).append(text_line);
                }
                break;
        }
    },
    clickMarker : function() {
        that = this;
        this.highlight();
        app.closeInfoWindow();
        app.selectedMarker = this;

        if (this.marker_clicked) {
            app.infoWindow = new google.maps.InfoWindow({
                content: that.el
            });
            app.infoWindow.open(that.map, that.marker);
            app.updateUrl(that.getUrl());
        } else {
            this.marker_clicked = true;
            $.get("/markers/" + this.model.get("id"), function (data) {
                data = JSON.parse(data);

                var j = 1;
                for (i in data) {
                    if (data[i]["sex"] != undefined) {
                        text_line = "
פרטי אדם מעורב" + " " + (i*1+1) + "
";
                        that.$el.find("#involved").append(text_line);
                        that.localize_data(data,"SUG_MEORAV","involved_type","invs","involved");
                        that.localize_data(data,"SHNAT_HOZAA","license_acquiring_date","nums","involved");
                        that.localize_data(data,"KVUZA_GIL","age_group","nums","involved");
                        that.localize_data(data,"MIN","sex","invs","involved");
                        that.localize_data(data,"MAHOZ_MEGURIM","home_district","nums","involved");
                        that.localize_data(data,"SUG_REHEV_NASA_LMS","car_type","invs","involved");
                        that.localize_data(data,"EMZAE_BETIHUT","safety_measures","invs","involved");
                        that.localize_data(data,"HUMRAT_PGIA","injury_severity","invs","involved");
                        that.localize_data(data,"SUG_NIFGA_LMS","injured_type","invs","involved");
                        that.localize_data(data,"PEULAT_NIFGA_LMS","injured_position","invs","involved");
                        that.localize_data(data,"KVUTZAT_OHLUSIYA_LMS","population_type","nums","involved");
                        that.$el.find("#involved").append("

");
                    }else{
                        text_line = "
פרטי רכב מעורב" + " " + (j) + "
";
                        that.$el.find("#vehicles").append(text_line);
                        that.localize_data(data,"SUG_REHEV_LMS","vehicle_type","vehs","vehicles");
                        that.localize_data(data,"NEFAH","engine_volume","nums","vehicles");
                        that.localize_data(data,"SHNAT_YITZUR","manufacturing_year","nums","vehicles");
                        that.localize_data(data,"KIVUNE_NESIA","driving_directions","nums","vehicles");
                        that.localize_data(data,"MATZAV_REHEV","vehicle_status","vehs","vehicles");
                        that.localize_data(data,"SHIYUH_REHEV_LMS","vehicle_attribution","vehs","vehicles");
                        that.localize_data(data,"MEKOMOT_YESHIVA_LMS","seats","nums","vehicles");
                        that.localize_data(data,"MISHKAL_KOLEL_LMS","total_weight","nums","vehicles");
                        that.$el.find("#vehicles").append("

");
                        j++;
                    }
                }
                app.infoWindow = new google.maps.InfoWindow({
                    content: that.el
                });
                app.infoWindow.open(that.map, that.marker);
                app.updateUrl(that.getUrl());
            });
        }

        $(document).keydown(app.ESCinfoWindow);
    },
    highlight : function() {
        if (app.oms.markersNearMarker(this.marker, true)[0]  && !this.model.get("currentlySpiderfied")){
            this.resetOpacitySeverity();
        }
        this.marker.setAnimation(google.maps.Animation.BOUNCE);

        // ##############################
        // # Another option, if we don't want the somewhat unintuitive experience where an icon start's bouncing,
        // # but other icons in the same place stay still, will be to do like so: (option 2)
        // ##############################

        // _.each(app.oms.markersNearMarker(this.marker), function (marker){

        //     marker.setAnimation(google.maps.Animation.BOUNCE);

        // });
        // this.marker.setAnimation(google.maps.Animation.BOUNCE);

        // ## END (option 2)

    },
    unhighlight : function() {
        if (app.oms.markersNearMarker(this.marker, true)[0] && !this.model.get("currentlySpiderfied")){
            this.opacitySeverityForGroup();
        }
        this.marker.setAnimation(null);

        // ##############################
        // # Option 2
        // ##############################

        // _.each(app.oms.markersNearMarker(this.marker), function (marker){

        //     marker.setAnimation(null);

        // });
        // this.marker.setAnimation(null);

        // ## END (option 2)

    },
    clickShare : function() {
        FB.ui({
            method: "feed",
            name: this.model.get("title"),
            link: document.location.href,
            description: this.model.get("description"),
            caption: SUBTYPE_STRING[this.model.get("subtype")]
            // picture
        });
    },
    resetOpacitySeverity : function() {
        this.marker.icon = this.getIcon();
        this.marker.opacity = this.model.get("locationAccuracy") == 1 ? 1.0 : INACCURATE_MARKER_OPACITY;
    },
    opacitySeverityForGroup : function() {
        var group = this.model.get("groupID") -1;
        this.marker.icon = app.retinaIconsResize(MULTIPLE_ICONS[app.groupsData[group].severity]);
        if (app.groupsData[group].opacity != 'opaque'){
            this.marker.opacity = INACCURATE_MARKER_OPACITY / app.groupsData[group].opacity;
        }
    },
    accordionInputClick : function(e) {
        var input = e.currentTarget;
        if (input.checked){
            var infoWindow = $(input).parents(".marker-info-window");
            var labelTop = $(input).siblings("label").offset().top;
            var infoWindowPos = infoWindow.offset().top;
            var IwHalfHeight = infoWindow.height() / 2;
            var labelPosRelativeToIw = labelTop - infoWindowPos;
            if (labelPosRelativeToIw > IwHalfHeight) {
                var curIwScroll = infoWindow.scrollTop();
                var labelPos = labelTop - infoWindowPos + curIwScroll;

                setTimeout(function(){
                    var sectionHeightScroll = $(input).siblings(".accordion-roller").height() + curIwScroll;
                    var bestScrollTo = sectionHeightScroll < labelPos ? sectionHeightScroll : labelPos;

                    $(infoWindow).on("mousewheel keyup mousedown DOMMouseScroll wheel touchmove", function(){
                        $(infoWindow).stop();
                    });

                    $(infoWindow).animate({
                        scrollTop: bestScrollTo
                    }, 1300, function(){
                        $(infoWindow).off("mousewheel keyup mousedown DOMMouseScroll wheel touchmove");
                    });
                }.bind(this),550);
            }
        }
    }
});
<|endoftext|>


<commit_before>/**
 * cuid.js
 * Collision-resistant client-side UID generator safe
 * for element IDs and server-side lookups.
 *
 * Extracted from CLCTR
 *
 * Copyright (c) Eric Elliott 2012
 * MIT License
 */

/*global window, navigator, document */
(function () {
  'use strict';
  var alpha = 'abcdefghijklmnopqrstuvwxyz',
    c = 0,
    globalCount = (function () {
      var i,
        count = 0;
      for (i in window) {
        count++;
      }
      return count;
    }()),

    /**
     * cuid returns a short random string prepended with
     * the current time and a little browser/page fingerprint
     * to prevent collisions from different clients.
     *
     * Sample: t6koe7ta5lf4cuzq4apz
     *
     * Broken down: u - 6koe7ta - 5l-f4 - cuzq - 4apz
     *
     * The first char is a random a-z char to make it HTML
     * ID friendly.
     *
     * The next group is a timestamp.
     *
     * After that is a fingerprint where the first chars
     * are obtained from the user agent string (which
     * is fairly unique), and the supported mimeTypes
     * (which is also fairly unique, except for IE, which
     * always returns 0).
     *
     * The next part of the browser fingerprint is a count of
     * global variables (which varies a lot).
     *
     * The next part is a counter to hammer out the last
     * same-machine collisions (was ~1 in 600,000).
     *
     * The final part is from Math.random().
     **/
    cuid = function cuid() {
      // Starting with a lowercase letter Makes
      // it HTML element ID friendly.
      var letter = alpha.charAt(Math.floor(Math.random()*26)),

        // timestamp with least useful digit shaved
        timestamp = (new Date().getTime()).toString(36).slice(1),

        // A few chars to generate distinct ids for different
        // browser / page combos (so different computers are far less
        // likely to generate the same id)
        fingerprint = (navigator.mimeTypes.length +
            navigator.userAgent.length).toString(36) +
          globalCount.toString(36),

        // Without this, 1 in 600,000 IDs collide.
        counter,

        // Grab some more chars from browser's .random() method
        random = ("0000" + (Math.random() *
            Math.pow(36, 4) << 0)
            .toString(36)).substr(-4);

        c = (c < 1000000) ? c : 0;
        counter = c.toString(36);

      c++; // this is not subliminal

      return  (letter + timestamp + fingerprint + counter + random);
    };

  window.cuid = cuid;
}());
<commit_msg>Comment typo<commit_after>/**
 * cuid.js
 * Collision-resistant client-side UID generator safe
 * for element IDs and server-side lookups.
 *
 * Extracted from CLCTR
 *
 * Copyright (c) Eric Elliott 2012
 * MIT License
 */

/*global window, navigator, document */
(function () {
  'use strict';
  var alpha = 'abcdefghijklmnopqrstuvwxyz',
    c = 0,
    globalCount = (function () {
      var i,
        count = 0;
      for (i in window) {
        count++;
      }
      return count;
    }()),

    /**
     * cuid returns a short random string prepended with
     * the current time and a little browser/page fingerprint
     * to prevent collisions from different clients.
     *
     * Sample: t6koe7ta5lf4cuzq4apz
     *
     * Broken down: t - 6koe7ta - 5l-f4 - cuzq - 4apz
     *
     * The first char is a random a-z char to make it HTML
     * ID friendly.
     *
     * The next group is a timestamp.
     *
     * After that is a fingerprint where the first chars
     * are obtained from the user agent string (which
     * is fairly unique), and the supported mimeTypes
     * (which is also fairly unique, except for IE, which
     * always returns 0).
     *
     * The next part of the browser fingerprint is a count of
     * global variables (which varies a lot).
     *
     * The next part is a counter to hammer out the last
     * same-machine collisions (was ~1 in 600,000).
     *
     * The final part is from Math.random().
     **/
    cuid = function cuid() {
      // Starting with a lowercase letter Makes
      // it HTML element ID friendly.
      var letter = alpha.charAt(Math.floor(Math.random()*26)),

        // timestamp with least useful digit shaved
        timestamp = (new Date().getTime()).toString(36).slice(1),

        // A few chars to generate distinct ids for different
        // browser / page combos (so different computers are far less
        // likely to generate the same id)
        fingerprint = (navigator.mimeTypes.length +
            navigator.userAgent.length).toString(36) +
          globalCount.toString(36),

        // Without this, 1 in 600,000 IDs collide.
        counter,

        // Grab some more chars from browser's .random() method
        random = ("0000" + (Math.random() *
            Math.pow(36, 4) << 0)
            .toString(36)).substr(-4);

        c = (c < 1000000) ? c : 0;
        counter = c.toString(36);

      c++; // this is not subliminal

      return  (letter + timestamp + fingerprint + counter + random);
    };

  window.cuid = cuid;
}());
<|endoftext|>


<commit_before>import React from 'react';
import request from 'superagent';
import { Link } from 'react-router';
import ReactDisqusThread from '../scripts/disqus-thread';

import bem from '../utils/bemClassNames';

import User from './user';
import { URL_NAMES, getUrl } from '../utils/urlGenerator';

import {API_HOST} from '../config'
import {getStore, addError, updateFollowStatus} from '../store';

class TagLine extends React.Component {
  render() {
    if (this.props.tags.length == 0) {
      return


<commit_before>'use strict';

import Fabric from '../';

const util = require('util');
const jade = require('jade');
const parse = require('xml2js').parseString;
const blessed = require('blessed');
const contrib = require('blessed-contrib');

//const Fabric = require('../');
const Viewer = require('wopr');

/**
 * Base class for a terminal-like interface to the Fabric network.
 * @param       {Object} configuration Configuration object for the CLI.
 * @constructor
 * @property storage {Storage} - Instance of {@link Storage}.
 */
function CLI (init) {
  this['@data'] = init || {};
  this.clock = 0;
  this.stack = [];
  this.known = {};

  this.init();
}

// all user interfaces begin with a "Vector"
util.inherits(CLI, require('../lib/vector'));

CLI.prototype.define = async function (xml) {
  var parsed = await parse(xml, function(err, doc) {

  });

  console.log('parsed:', parsed);
};

CLI.prototype._createInstance = function () {
  let self = this;

  self.screen = blessed.screen({
    smartCSR: true,
    dockBorders: true
  });

  self.screen.key(['escape'], function(ch, key) {
    process.exit();
  });

  self.oracle = new Fabric.HTTP({
    name: 'fabric'
  });

  self.oracle.define('Chat', {
    routes: {
      query: '/chats'
    }
  });

};

CLI.prototype.start = function () {
  let self = this;

  self._createInstance();

  self.controls = blessed.box({
    parent: self.screen,
    border: {
      type: 'line'
    },
    bottom: 0,
    height: 3
  });

  self.form = blessed.form({
    parent: self.screen,
    keys: true,
    //top: '100%-1',
    //height: '100%',
    //width: '100%'
  });

  self.textbox = blessed.textbox({
    parent: self.form,
    name: 'input',
    input: true,
    inputOnFocus: true,
    focused: true,
    value: '',
    bottom: 1,
    width: '80%',
    mouse: true,
    height: 3,
    width: '100%',
    border: {
      type: 'line'
    },
    keys: true
  });

  self.submit = blessed.button({
    parent: self.form,
    //parent: self.form,
    mouse: true,
    //keys: true,
    shrink: true,
    bottom: 0,
    right: 0,
    name: 'submit',
    content: '[ENTER] Send',
    style: {
      bg: 'blue'
    },
    padding: {
      left: 1,
      right: 1
    }
  });

  self.instructions = blessed.box({
    parent: self.screen,
    content: '[ESCAPE (2x)] exit]',
    bottom: 0,
    height: 1,
    width: '100%-20',
    padding: {
      left: 1,
      right: 1
    }
  });

  /*self.labels = blessed.box({
    parent: self.screen,
    content: 'Messaging as Anonymous:',
    detached: true,
    bottom: 5,
    style: {

    }
  }),*/

  self.history = blessed.box({
    parent: self.screen,
    label: 'History',
    scrollable: true,
    alwaysScroll: true,
    keys: true,
    mouse: true,
    height: '100%-3',
    border: {
      type: 'line'
    },
    scrollbar: {}
  });

  self.textbox.key(['enter'], function(ch, key) {
    self.form.submit();
    self.textbox.clearValue();
    self.textbox.readInput();
  });

  self.submit.on('press', function () {
    self.form.submit();
  });

  self.form.on('submit', async function (data) {
    var now = new Date();

    self.form.reset();

    let result = await self.oracle._POST('/chats', {
      input: data.input
    });

    self.history.pushLine(now.toString() + ': ' + JSON.stringify(result, '  ', '  '));
    self.history.setScrollPerc(100);

    self.screen.render();
  });

  self.screen.render();

  //self.form.focus();
  self.textbox.readInput();

}

CLI.prototype.inspect = function () {
  let self = this;

  self.screen = blessed.screen();
  self.screen.key(['q', 'escape'], function(ch, key) {
    process.exit();
  });

  self.grid = new contrib.grid({ rows: 12, cols: 12, screen: self.screen });

  self.log = self.grid.set(0, 0, 10, 9, contrib.log, {
    label: 'History',
    fg: 'green',
    selectedFg: 'green'
  });

  self.tree = self.grid.set(0, 9, 12, 3, contrib.tree, {
    label: 'Menu',
    fg: 'green'
  });

  /*self.form = self.grid.set(11, 2, 0, 9, blessed.form, {
    label: 'Input',
    fg: 'green'
  });*/

  self.tree.setData({
    extended: true,
    children: {
      'RPG': {
        children: []
      }
    }
  });

  self.screen.render();

  /*setInterval(function() {
    self.log.log(Math.random() + '');
  }, 100);*/
}

CLI.prototype.render = function (done) {
  const self = this;
  const render = jade.compileFile(this['@data'].ui);
  const xml = render(this['@data']);

  parse(xml, function(err, doc) {
    if (err) return console.error(err);
    //if (!doc || !doc.document) return console.error('Invalid UI definition.');

    console.debug('doc:', doc);

    self.screen = blessed.screen();
    self.viewer = new Viewer(doc, self.screen);

    self.screen.key(['q', 'escape'], function(ch, key) {
      process.exit()
    });

    for (var i in doc) {
      var item = doc[i];
      var name = Object.keys(item)[1];
      var element = contrib[i] || blessed[i];

      console.debug('loop:', item, name, element, opts);

      if (!element) throw new Error('Unexpected interface element: ' + name);

      var opts = self.viewer.readOptions(item, element);

      self.screen.append(element);
    }

    self.screen.render();
    //self.viewer.render();

    done();
  });

};

module.exports = CLI;
<commit_msg>Remove extraneous cruft from CLI<commit_after>'use strict';

import Fabric from '../';

const util = require('util');
const jade = require('jade');
const parse = require('xml2js').parseString;
const blessed = require('blessed');
const contrib = require('blessed-contrib');

//const Fabric = require('../');
const Viewer = require('wopr');

/**
 * Base class for a terminal-like interface to the Fabric network.
 * @param       {Object} configuration Configuration object for the CLI.
 * @constructor
 * @property storage {Storage} - Instance of {@link Storage}.
 */
function CLI (init) {
  this['@data'] = init || {};
  this.clock = 0;
  this.stack = [];
  this.known = {};

  this.init();
}

// all user interfaces begin with a "Vector"
util.inherits(CLI, require('../lib/vector'));

CLI.prototype.define = async function (xml) {
  var parsed = await parse(xml, function(err, doc) {

  });

  console.log('parsed:', parsed);
};

CLI.prototype._createInstance = function () {
  let self = this;

  self.screen = blessed.screen({
    smartCSR: true,
    dockBorders: true
  });

  self.screen.key(['escape'], function(ch, key) {
    process.exit();
  });

  self.oracle = new Fabric.HTTP({
    name: 'fabric'
  });

};

CLI.prototype.start = function () {
  let self = this;

  self._createInstance();

  self.controls = blessed.box({
    parent: self.screen,
    border: {
      type: 'line'
    },
    bottom: 0,
    height: 3
  });

  self.form = blessed.form({
    parent: self.screen,
    keys: true,
    //top: '100%-1',
    //height: '100%',
    //width: '100%'
  });

  self.textbox = blessed.textbox({
    parent: self.form,
    name: 'input',
    input: true,
    inputOnFocus: true,
    focused: true,
    value: '',
    bottom: 1,
    width: '80%',
    mouse: true,
    height: 3,
    width: '100%',
    border: {
      type: 'line'
    },
    keys: true
  });

  self.submit = blessed.button({
    parent: self.form,
    //parent: self.form,
    mouse: true,
    //keys: true,
    shrink: true,
    bottom: 0,
    right: 0,
    name: 'submit',
    content: '[ENTER] Send',
    style: {
      bg: 'blue'
    },
    padding: {
      left: 1,
      right: 1
    }
  });

  self.instructions = blessed.box({
    parent: self.screen,
    content: '[ESCAPE (2x)] exit]',
    bottom: 0,
    height: 1,
    width: '100%-20',
    padding: {
      left: 1,
      right: 1
    }
  });

  /*self.labels = blessed.box({
    parent: self.screen,
    content: 'Messaging as Anonymous:',
    detached: true,
    bottom: 5,
    style: {

    }
  }),*/

  self.history = blessed.box({
    parent: self.screen,
    label: 'History',
    scrollable: true,
    alwaysScroll: true,
    keys: true,
    mouse: true,
    height: '100%-3',
    border: {
      type: 'line'
    },
    scrollbar: {}
  });

  self.textbox.key(['enter'], function(ch, key) {
    self.form.submit();
    self.textbox.clearValue();
    self.textbox.readInput();
  });

  self.submit.on('press', function () {
    self.form.submit();
  });

  self.form.on('submit', async function (data) {
    var now = new Date();

    self.form.reset();

    let result = await self.oracle._POST('/chats', {
      input: data.input
    });

    self.history.pushLine(now.toString() + ': ' + JSON.stringify(result, '  ', '  '));
    self.history.setScrollPerc(100);

    self.screen.render();
  });

  self.screen.render();

  //self.form.focus();
  self.textbox.readInput();

}

CLI.prototype.inspect = function () {
  let self = this;

  self.screen = blessed.screen();
  self.screen.key(['q', 'escape'], function(ch, key) {
    process.exit();
  });

  self.grid = new contrib.grid({ rows: 12, cols: 12, screen: self.screen });

  self.log = self.grid.set(0, 0, 10, 9, contrib.log, {
    label: 'History',
    fg: 'green',
    selectedFg: 'green'
  });

  self.tree = self.grid.set(0, 9, 12, 3, contrib.tree, {
    label: 'Menu',
    fg: 'green'
  });

  /*self.form = self.grid.set(11, 2, 0, 9, blessed.form, {
    label: 'Input',
    fg: 'green'
  });*/

  self.tree.setData({
    extended: true,
    children: {
      'RPG': {
        children: []
      }
    }
  });

  self.screen.render();

  /*setInterval(function() {
    self.log.log(Math.random() + '');
  }, 100);*/
}

CLI.prototype.render = function (done) {
  const self = this;
  const render = jade.compileFile(this['@data'].ui);
  const xml = render(this['@data']);

  parse(xml, function(err, doc) {
    if (err) return console.error(err);
    //if (!doc || !doc.document) return console.error('Invalid UI definition.');

    console.debug('doc:', doc);

    self.screen = blessed.screen();
    self.viewer = new Viewer(doc, self.screen);

    self.screen.key(['q', 'escape'], function(ch, key) {
      process.exit()
    });

    for (var i in doc) {
      var item = doc[i];
      var name = Object.keys(item)[1];
      var element = contrib[i] || blessed[i];

      console.debug('loop:', item, name, element, opts);

      if (!element) throw new Error('Unexpected interface element: ' + name);

      var opts = self.viewer.readOptions(item, element);

      self.screen.append(element);
    }

    self.screen.render();
    //self.viewer.render();

    done();
  });

};

module.exports = CLI;
<|endoftext|>


<commit_before>#!/usr/bin/env node
var args = process.argv.slice(2)

if (!args.length && process.stdin.isTTY) {
  console.error(usage())
  process.exit(1)
}

// defaults
var nodeArgs = []

var timeout = process.env.TAP_TIMEOUT || 120
var color = require('supports-color')
var reporter
var files = []

for (var i = 0; i < args.length; i++) {
  var arg = args[i]
  if (arg.charAt(0) !== '-' || arg === '-') {
    files.push(arg)
    continue
  }

  // support -Rspec as well as --reporter=spec
  arg = arg.replace(/^-R/, '--reporter=')

  var key = arg
  var val
  if (key.match(/^--/) && arg.indexOf('=') !== -1) {
    var kv = arg.split('=')
    key = kv.shift()
    val = kv.join('=')
  }

  switch (key) {
    case '-h': case '--help': case '-?':
      return console.log(usage())

    case '-v': case '--version':
      return console.log(require('../package.json').version)

    case '--reporter':
      val = val || args[++i]
      reporter = val
      continue

    case '--gc': case '-gc': case '--expose-gc':
      nodeArgs.push('--expose-gc')
      continue

    case '--strict':
      nodeArgs.push('--strict')
      continue

    case '--debug':
      nodeArgs.push('--debug')
      continue

    case '--debug-brk':
      nodeArgs.push('--debug-brk')
      continue

    case '--harmony':
      nodeArgs.push('--harmony')
      continue

    case '-c': case '--color':
      color = true
      continue

    case '-C': case '--no-color':
      color = false
      continue

    case '-t': case '--timeout':
      val = val || args[++i]
      timeout = +val
      continue

    case '--':
      files = files.concat(args.slice(i + 1))
      i = args.length
      continue

    default:
      throw new Error('Unknown argument: ' + arg)
  }
}

// default to tap for non-tty envs
if (!reporter)
  reporter = color ? 'classic' : 'tap'

function usage () {
  return function () {/*
Usage:
  tap [options] <files>

Executes all the files and interprets their output as TAP
formatted test result data.

To parse TAP data from stdin, specify "-" as a filename.

Options:

  -c --color                  Force use of colors

  -C --no-color               Force no use of colors

  -R<type> --reporter=<type>  Use the specified reporter.  Defaults to
                              'classic' when colors are in use, or 'tap'
                              when colors are disabled.

                              Available reporters:
@@REPORTERS@@

  -gc --expose-gc             Expose the gc() function to Node tests

  --debug                     Run JavaScript tests with node --debug

  --debug-brk                 Run JavaScript tests with node --debug-brk

  --harmony                   Enable all Harmony flags in JavaScript tests

  --strict                    Run JS tests in 'use strict' mode

  -t<n> --timeout=<n>         Time out tests after this many seconds.
                              Defaults to 120, or the value of the
                              TAP_TIMEOUT environment variable.

  -h --help                   print this thing you're looking at

  -v --version                show the version of this program

  --                          Stop parsing flags, and treat any additional
                              command line arguments as filenames.
*/}.toString().split('\n').slice(1, -1).join('\n')
  .split('@@REPORTERS@@').join(getReporters())
}

function getReporters () {
  var types = require('tap-mocha-reporter').types
  types = types.reduce(function (str, t) {
    var ll = str.split('\n').pop().length + t.length
    if (ll < 40)
      return str + ' ' + t
    else
      return str + '\n' + t
  }, '').trim()
  var ind = '                              '
  return ind + types.split('\n').join('\n' + ind)
}

var isExe
if (process.platform == "win32") {
  // On windows, there is no good way to check that a file is executable
  isExe = function isExe () { return true }
} else {
  isExe = function isExe (stat) {
    var mod = stat.mode
    var uid = stat.uid
    var gid = stat.gid
    var u = parseInt('100', 8)
    var g = parseInt('010', 8)
    var o = parseInt('001', 8)
    var ug = u | g

    var ret = (mod & o)
        || (mod & g) && process.getgid && gid === process.getgid()
        || (mod & u) && process.getuid && uid === process.getuid()
        || (mod & ug) && process.getuid && 0 === process.getuid()

    return ret
  }
}

var fs = require('fs')
process.env.TAP_TIMEOUT = timeout
if (color)
  process.env.TAP_COLORS = 1
else
  process.env.TAP_COLORS = 0

if (files.length === 0) {
  console.error('Reading TAP data from stdin (use "-" argument to suppress)')
  files.push('-')
}

var TMR = require('tap-mocha-reporter')
if (files.length === 1 && files[0] === '-') {
  // if we didn't specify any files, then just passthrough
  // to the reporter, so we don't get '/dev/stdin' in the suite list.
  reporter = new TMR(reporter)
  process.stdin.pipe(reporter)
  return
}

// At this point, we know we need to use the tap root,
// because there are 1 or more files to spawn.
var tap = require('../lib/root.js')
if (reporter !== 'tap') {
  tap.unpipe(process.stdout)
  reporter = new TMR(reporter)
  tap.pipe(reporter)
}

for (var i = 0; i < files.length; i++) {
  var file = files[i]

  // Pick up stdin after all the other files are handled.
  if (file === '-') {
    tap.stdin()
    continue
  }

  var st = fs.statSync(files[i])

  if (file.match(/\.js$/))
    tap.spawn(process.execPath, nodeArgs.concat(file))
  else if (st.isDirectory()) {
    files.push.apply(files, fs.readdirSync(file).map(function (f) {
      return file + '/' + f
    }))
  }
  else if (isExe(st))
    tap.spawn(files[i], [])
}

tap.end()
<commit_msg>Ignore EPIPE errors, just quit<commit_after>#!/usr/bin/env node
var args = process.argv.slice(2)

if (!args.length && process.stdin.isTTY) {
  console.error(usage())
  process.exit(1)
}

process.stdout.on('error', function (er) {
  if (er.code === 'EPIPE')
    process.exit()
  else
    throw er
})

// defaults
var nodeArgs = []

var timeout = process.env.TAP_TIMEOUT || 120
var color = require('supports-color')
var reporter
var files = []

for (var i = 0; i < args.length; i++) {
  var arg = args[i]
  if (arg.charAt(0) !== '-' || arg === '-') {
    files.push(arg)
    continue
  }

  // support -Rspec as well as --reporter=spec
  arg = arg.replace(/^-R/, '--reporter=')

  var key = arg
  var val
  if (key.match(/^--/) && arg.indexOf('=') !== -1) {
    var kv = arg.split('=')
    key = kv.shift()
    val = kv.join('=')
  }

  switch (key) {
    case '-h': case '--help': case '-?':
      return console.log(usage())

    case '-v': case '--version':
      return console.log(require('../package.json').version)

    case '--reporter':
      val = val || args[++i]
      reporter = val
      continue

    case '--gc': case '-gc': case '--expose-gc':
      nodeArgs.push('--expose-gc')
      continue

    case '--strict':
      nodeArgs.push('--strict')
      continue

    case '--debug':
      nodeArgs.push('--debug')
      continue

    case '--debug-brk':
      nodeArgs.push('--debug-brk')
      continue

    case '--harmony':
      nodeArgs.push('--harmony')
      continue

    case '-c': case '--color':
      color = true
      continue

    case '-C': case '--no-color':
      color = false
      continue

    case '-t': case '--timeout':
      val = val || args[++i]
      timeout = +val
      continue

    case '--':
      files = files.concat(args.slice(i + 1))
      i = args.length
      continue

    default:
      throw new Error('Unknown argument: ' + arg)
  }
}

// default to tap for non-tty envs
if (!reporter)
  reporter = color ? 'classic' : 'tap'

function usage () {
  return function () {/*
Usage:
  tap [options] <files>

Executes all the files and interprets their output as TAP
formatted test result data.

To parse TAP data from stdin, specify "-" as a filename.

Options:

  -c --color                  Force use of colors

  -C --no-color               Force no use of colors

  -R<type> --reporter=<type>  Use the specified reporter.  Defaults to
                              'classic' when colors are in use, or 'tap'
                              when colors are disabled.

                              Available reporters:
@@REPORTERS@@

  -gc --expose-gc             Expose the gc() function to Node tests

  --debug                     Run JavaScript tests with node --debug

  --debug-brk                 Run JavaScript tests with node --debug-brk

  --harmony                   Enable all Harmony flags in JavaScript tests

  --strict                    Run JS tests in 'use strict' mode

  -t<n> --timeout=<n>         Time out tests after this many seconds.
                              Defaults to 120, or the value of the
                              TAP_TIMEOUT environment variable.

  -h --help                   print this thing you're looking at

  -v --version                show the version of this program

  --                          Stop parsing flags, and treat any additional
                              command line arguments as filenames.
*/}.toString().split('\n').slice(1, -1).join('\n')
  .split('@@REPORTERS@@').join(getReporters())
}

function getReporters () {
  var types = require('tap-mocha-reporter').types
  types = types.reduce(function (str, t) {
    var ll = str.split('\n').pop().length + t.length
    if (ll < 40)
      return str + ' ' + t
    else
      return str + '\n' + t
  }, '').trim()
  var ind = '                              '
  return ind + types.split('\n').join('\n' + ind)
}

var isExe
if (process.platform == "win32") {
  // On windows, there is no good way to check that a file is executable
  isExe = function isExe () { return true }
} else {
  isExe = function isExe (stat) {
    var mod = stat.mode
    var uid = stat.uid
    var gid = stat.gid
    var u = parseInt('100', 8)
    var g = parseInt('010', 8)
    var o = parseInt('001', 8)
    var ug = u | g

    var ret = (mod & o)
        || (mod & g) && process.getgid && gid === process.getgid()
        || (mod & u) && process.getuid && uid === process.getuid()
        || (mod & ug) && process.getuid && 0 === process.getuid()

    return ret
  }
}

var fs = require('fs')
process.env.TAP_TIMEOUT = timeout
if (color)
  process.env.TAP_COLORS = 1
else
  process.env.TAP_COLORS = 0

if (files.length === 0) {
  console.error('Reading TAP data from stdin (use "-" argument to suppress)')
  files.push('-')
}

var TMR = require('tap-mocha-reporter')
if (files.length === 1 && files[0] === '-') {
  // if we didn't specify any files, then just passthrough
  // to the reporter, so we don't get '/dev/stdin' in the suite list.
  reporter = new TMR(reporter)
  process.stdin.pipe(reporter)
  return
}

// At this point, we know we need to use the tap root,
// because there are 1 or more files to spawn.
var tap = require('../lib/root.js')
if (reporter !== 'tap') {
  tap.unpipe(process.stdout)
  reporter = new TMR(reporter)
  tap.pipe(reporter)
}

for (var i = 0; i < files.length; i++) {
  var file = files[i]

  // Pick up stdin after all the other files are handled.
  if (file === '-') {
    tap.stdin()
    continue
  }

  var st = fs.statSync(files[i])

  if (file.match(/\.js$/))
    tap.spawn(process.execPath, nodeArgs.concat(file))
  else if (st.isDirectory()) {
    files.push.apply(files, fs.readdirSync(file).map(function (f) {
      return file + '/' + f
    }))
  }
  else if (isExe(st))
    tap.spawn(files[i], [])
}

tap.end()
<|endoftext|>


<commit_before>Readium.TocManager = function(book) {
	var callback = function() {};
	var parser = window.DOMParser;
	var dom = parser.parseFromString()
};

(function() {
	var _paginator;
	var _fsPath;
	var _urlArgs;
	var _book;
	var _fontSize = 10; // 10 => 1.0em

	var fireRepaginateEvent = function() {
		$('#readium-content-container').trigger("content-size-changed");
	}

	var openCurrentSection = function() {
		_book.getSectionText(parseBookCallback, loadErrorHandler);

		var doneSwapping = function() {
			_paginator.goToFirstPage();
			$("#readium-content-container").css("visibility", "visible");
			$('#readium-content-container').unbind("content-size-changed", doneSwapping);
		}
		$('#readium-content-container').bind("content-size-changed", doneSwapping);
	}

	var flipTheSection = function() {
		if(_book.goToNextSection()) {
			openCurrentSection();
		}
	}

	var flipThePage = function() {
		if( !_paginator.pageForward() && !_book.isFixedLayout() ) {
			flipTheSection();
		}
	}

	var flipBackASection = function() {
		if(_book.goToPrevSection()) {
			_paginator.replaceContent("");
			_book.getSectionText(parseBookCallback, loadErrorHandler);
			var doneSwapping = function() {
				//$("#readium-content-container").hide();
				_paginator.goTolastPage();
				$("#readium-content-container").css("visibility", "visible");
				$('#readium-content-container').unbind("content-size-changed", doneSwapping);
			}
			$('#readium-content-container').bind("content-size-changed", doneSwapping);
		}
	}

	var flipBackAPage = function() {
		if(!_paginator.pageBack() && !_book.isFixedLayout() ) {
			flipBackASection();
		}
	}

	var setFontSize = function () {
		var size = ( _fontSize / 10 ).toString();
		$('#readium-content-container').css("font-size", size + "em");
		fireRepaginateEvent();
	}

	var increaseFont = function(e) {
		// TODO should there be some limit?
		_fontSize += 1;
		setFontSize();
	}

	var decreaseFont = function(e) {
		if(_fontSize > 1) {
			_fontSize -= 1;
			setFontSize();
		}
	}

	var addPageTurnHandlers = function(pagerObj) {
		var keydownHandler = function(e) {

			if(e.which == 39) {
				flipThePage();
			}

			if(e.which == 37) {
				flipBackAPage();
			}

		}

		$(document).keydown(keydownHandler);

		$('#page-fwd-button').click(function(e) {
			e.preventDefault();
			flipThePage();
		});
		$('#page-back-button').click(function(e) {
			e.preventDefault();
			flipBackAPage();
		});
		$('#increase-font-button').click(function(e) {
			e.preventDefault();
			increaseFont();
		});
		$('#decrease-font-button').click(function(e) {
			e.preventDefault();
			decreaseFont();
		});
		$('#two-up-button').click(function(e) {
			e.preventDefault();
			_paginator.toggleTwoUp();
		});

		$('#fullscreen-button').click(function(e) {
			e.preventDefault();
			if(document.webkitIsFullScreen) {
				document.webkitCancelFullScreen();
			}
			else {
				document.documentElement.webkitRequestFullScreen();
			}
		});

		if(!_book.isFixedLayout()) {
			// just prevent wheel scrolling for now, it's too buggy
			document.onmousewheel = function(e) {
				if(!document.getElementById('menu').contains(e.srcElement)) {
					e.preventDefault();
				}

			};
		}
	}

	var parseUrlArgs = function() {
		var hash;
		var args = [];
		var searchStr = window.location.search.substr(1);
		var hashes = searchStr.split('&');

		for(var i = 0; i < hashes.length; i++)
		{
			hash = hashes[i].split('=');
			args.push(hash[0]);
			args[hash[0]] = hash[1];
		}

		if(args["book"] && typeof args["book"] === "string") {
			_fsPath = args["book"].substr(0, args["book"].lastIndexOf("/") + 1);
		}

		return args;
	}

	var fixLinks = function() {
		if(_book.isFixedLayout() ) {
			$('#page-wrap a').click(linkClickHandler);
		}
		else {
			$('#readium-content-container a').click(linkClickHandler);
		}

	}

	var removeAddedStyleSheets = function() {
		$('.readium-dynamic-sh').remove();
	}

	var addStyleSheets = function(bookDom) {
		removeAddedStyleSheets();
		var links = bookDom.getElementsByTagName("link");
		var link; var href; var $link;
		for (var j = 0; j < links.length; j++) {
			link = links[j];
			if(typeof link.rel === "string" && link.rel.toUpperCase() === "STYLESHEET") {
				$link = $(link);
				$link.addClass('readium-dynamic-sh');
				$('head').prepend($link);
			}
		}
	}

	parseViewportTag = function(viewportTag) {
		// this is going to be ugly
		var str = viewportTag.getAttribute('content');
		str = str.replace(/\s/g, '');
		var valuePairs = str.split(',');
		var values = {};
		var pair;
		for(var i = 0; i < valuePairs.length; i++) {
			pair = valuePairs[i].split('=');
			if(pair.length === 2) {
				values[ pair[0] ] = pair[1];
			}
		}
		values['width'] = parseFloat(values['width']);
		values['height'] = parseFloat(values['height']);
		return values;
	}

	var addMetaHeadTags = function(bookDom) {
		// the desktop does not obey meta viewport tags so
		// dynamically add in some css
		var tag = bookDom.getElementsByName("viewport")[0];
		if(tag) {
			var pageSize = parseViewportTag(tag);
			document.head.appendChild(tag);
			_paginator.setPageSize(pageSize.width, pageSize.height);
		}

	}

	var showBook = function(bookDom) {

		addStyleSheets(bookDom);
		document.title = bookDom.title;
		_book.applyBindings(bookDom);
		if(_paginator) {
			$("#readium-content-container").css("visibility", "hidden");
			_paginator.replaceContent(bookDom.body.innerHTML);
		}
		else {
			var options = {
				pageAddCallback: function($newPage) {
					$newPage.click(toggleUi);
				}
			}
			_paginator = Readium.Paginator($('#container'), bookDom.body.innerHTML, options);
			if( shouldOpenInTwoUp() ) {
				_paginator.toggleTwoUp();
			}
			addPageTurnHandlers(_paginator);
		}
		fixLinks();

		// need to let the thread go for second so the css
		// is parsed before appending repaginating
		setTimeout(function() {
			fireRepaginateEvent();
		}, 8);

	};

	var addFixedLayoutCssFlag = function() {
		// just tack a class name on to the body
		$('body').addClass('apple-fixed-layout');
	};

	var showFixedLayoutBook = function() {
		addFixedLayoutCssFlag();

		var uris = _book.getAllSectionUris();
		// need to parse one viewport tag
		window.webkitResolveLocalFileSystemURL(uris[0], function(fileEntry) {
			Readium.FileSystemApi(function(fs) {
				fs.readEntry(fileEntry, function(content) {
					var parser = new window.DOMParser();
					var dom = parser.parseFromString(content, 'text/xml');
					var options = parseViewportTag(dom.getElementsByName("viewport")[0]);
					options.pageAddCallback = function($newPage) {
						$newPage.click(toggleUi);
						var iframe = $('iframe', $newPage)[0];
						if(iframe) {
							$('iframe', $newPage)[0].onload = function() {
								_book.applyBindings(this.contentDocument);
							}
						}

					};
					_paginator = Readium.FixedPaginator($('#container'), uris, options);
					_paginator.toggleTwoUp();
					fixLinks();
					addPageTurnHandlers(_paginator);

				}, function() {
					console.log('failed to load fixed layout book');
				})
			});
		});

	};

	var parseBookCallback = function(domString) {
		var parser = new window.DOMParser();
		var xmlDoc = parser.parseFromString(domString,"text/xml");
		showBook(xmlDoc);
	}

	var linkClickHandler = function(e) {
		var href = this.attributes["href"].value;
		e.preventDefault();
		if(href.match(/^http(s)?:/)) {
			chrome.tabs.create({"url":href});
		} else if( _book.goToHref(href) ) {
			openCurrentSection();
		} else {
			console.log('failed to navigate spine to ' + href);
		}
	}

	var addToc = function() {
		$('#top-bar').append(_book.getProperties().title);
		_book.getTocText(function(res) {
			var $tocArea = $('#menu');
			$tocArea.html(res);
			$('a', $tocArea).click(linkClickHandler);
		}, loadErrorHandler );
	};

	var openBook = function() {
		if(_urlArgs["book"] === undefined) {
			console.log("No book was specifiec to load");
			loadErrorHandler();
			return;
		}

		Lawnchair(function() {
			this.get(_urlArgs["book"], function(result) {
				if(result === null) {
					loadErrorHandler();
					return;
				}
				Readium.Ebook(result, function(book) {
					_book = book;
					if(_book.isFixedLayout()) {
						showFixedLayoutBook();
					}
					else {
						_book.getSectionText(parseBookCallback, loadErrorHandler);
					}
					addToc();
				}, function(e) {
					loadErrorHandler();
				});
			});
		});
	}

	var loadErrorHandler = function(e) {
		console.log("Error could not load book");
	}

	var displaySettingsAtFirstLoad = function() {
		var timeout = setTimeout(toggleUi, 2000);
	}

	// temp fix me
	var pos = "-44px";
	var toggleUi = function() {
		var style = $('#top-bar')[0].style;

		var settings = $('#settings');
		var temp = style.top;
		style.top = pos;
		pos = temp;
		settings.toggleClass('hover-fade');

	};

	var initTopBar = function() {
		$('#readium-content-container').click(toggleUi);
		$('.page-margin').click(toggleUi);
	};

	var initTocClick = function() {
		$('#show-toc-button').click(function(e) {
			$('body').toggleClass('show-toc');
			fireRepaginateEvent();
		});
	};

	// decide if should open in two up based on viewport
	// width
	var shouldOpenInTwoUp = function() {
		var width = document.documentElement.clientWidth;
		var height = document.documentElement.clientHeight;
		return width > 300 && width / height > 1.3;
	}

	$(function() {
		_urlArgs = parseUrlArgs();
		openBook();
		displaySettingsAtFirstLoad();
		initTopBar();
		initTocClick();
	});
})();
<commit_msg>fix css-broken page because of missing link tag<commit_after>Readium.TocManager = function(book) {
	var callback = function() {};
	var parser = window.DOMParser;
	var dom = parser.parseFromString()
};

(function() {
	var _paginator;
	var _fsPath;
	var _urlArgs;
	var _book;
	var _fontSize = 10; // 10 => 1.0em

	var fireRepaginateEvent = function() {
		$('#readium-content-container').trigger("content-size-changed");
	}

	var openCurrentSection = function() {
		_book.getSectionText(parseBookCallback, loadErrorHandler);

		var doneSwapping = function() {
			_paginator.goToFirstPage();
			$("#readium-content-container").css("visibility", "visible");
			$('#readium-content-container').unbind("content-size-changed", doneSwapping);
		}
		$('#readium-content-container').bind("content-size-changed", doneSwapping);
	}

	var flipTheSection = function() {
		if(_book.goToNextSection()) {
			openCurrentSection();
		}
	}

	var flipThePage = function() {
		if( !_paginator.pageForward() && !_book.isFixedLayout() ) {
			flipTheSection();
		}
	}

	var flipBackASection = function() {
		if(_book.goToPrevSection()) {
			_paginator.replaceContent("");
			_book.getSectionText(parseBookCallback, loadErrorHandler);
			var doneSwapping = function() {
				//$("#readium-content-container").hide();
				_paginator.goTolastPage();
				$("#readium-content-container").css("visibility", "visible");
				$('#readium-content-container').unbind("content-size-changed", doneSwapping);
			}
			$('#readium-content-container').bind("content-size-changed", doneSwapping);
		}
	}

	var flipBackAPage = function() {
		if(!_paginator.pageBack() && !_book.isFixedLayout() ) {
			flipBackASection();
		}
	}

	var setFontSize = function () {
		var size = ( _fontSize / 10 ).toString();
		$('#readium-content-container').css("font-size", size + "em");
		fireRepaginateEvent();
	}

	var increaseFont = function(e) {
		// TODO should there be some limit?
		_fontSize += 1;
		setFontSize();
	}

	var decreaseFont = function(e) {
		if(_fontSize > 1) {
			_fontSize -= 1;
			setFontSize();
		}
	}

	var addPageTurnHandlers = function(pagerObj) {
		var keydownHandler = function(e) {

			if(e.which == 39) {
				flipThePage();
			}

			if(e.which == 37) {
				flipBackAPage();
			}

		}

		$(document).keydown(keydownHandler);

		$('#page-fwd-button').click(function(e) {
			e.preventDefault();
			flipThePage();
		});
		$('#page-back-button').click(function(e) {
			e.preventDefault();
			flipBackAPage();
		});
		$('#increase-font-button').click(function(e) {
			e.preventDefault();
			increaseFont();
		});
		$('#decrease-font-button').click(function(e) {
			e.preventDefault();
			decreaseFont();
		});
		$('#two-up-button').click(function(e) {
			e.preventDefault();
			_paginator.toggleTwoUp();
		});

		$('#fullscreen-button').click(function(e) {
			e.preventDefault();
			if(document.webkitIsFullScreen) {
				document.webkitCancelFullScreen();
			}
			else {
				document.documentElement.webkitRequestFullScreen();
			}
		});

		if(!_book.isFixedLayout()) {
			// just prevent wheel scrolling for now, it's too buggy
			document.onmousewheel = function(e) {
				if(!document.getElementById('menu').contains(e.srcElement)) {
					e.preventDefault();
				}

			};
		}
	}

	var parseUrlArgs = function() {
		var hash;
		var args = [];
		var searchStr = window.location.search.substr(1);
		var hashes = searchStr.split('&');

		for(var i = 0; i < hashes.length; i++)
		{
			hash = hashes[i].split('=');
			args.push(hash[0]);
			args[hash[0]] = hash[1];
		}

		if(args["book"] && typeof args["book"] === "string") {
			_fsPath = args["book"].substr(0, args["book"].lastIndexOf("/") + 1);
		}

		return args;
	}

	var fixLinks = function() {
		if(_book.isFixedLayout() ) {
			$('#page-wrap a').click(linkClickHandler);
		}
		else {
			$('#readium-content-container a').click(linkClickHandler);
		}

	}

	var removeAddedStyleSheets = function() {
		$('.readium-dynamic-sh').remove();
	}

	var addStyleSheets = function(bookDom) {
		removeAddedStyleSheets();
		var links = $("link", bookDom);
		var link; var href; var $link;
		for (var j = 0; j < links.length; j++) {
			link = links[j];
			if(typeof link.rel === "string" && link.rel.toUpperCase() === "STYLESHEET") {
				$link = $(link);
				$link.addClass('readium-dynamic-sh');
				$('head').prepend($link);
			}
		}
	}

	parseViewportTag = function(viewportTag) {
		// this is going to be ugly
		var str = viewportTag.getAttribute('content');
		str = str.replace(/\s/g, '');
		var valuePairs = str.split(',');
		var values = {};
		var pair;
		for(var i = 0; i < valuePairs.length; i++) {
			pair = valuePairs[i].split('=');
			if(pair.length === 2) {
				values[ pair[0] ] = pair[1];
			}
		}
		values['width'] = parseFloat(values['width']);
		values['height'] = parseFloat(values['height']);
		return values;
	}

	var addMetaHeadTags = function(bookDom) {
		// the desktop does not obey meta viewport tags so
		// dynamically add in some css
		var tag = bookDom.getElementsByName("viewport")[0];
		if(tag) {
			var pageSize = parseViewportTag(tag);
			document.head.appendChild(tag);
			_paginator.setPageSize(pageSize.width, pageSize.height);
		}

	}

	var showBook = function(bookDom) {

		addStyleSheets(bookDom);
		document.title = bookDom.title;
		_book.applyBindings(bookDom);
		if(_paginator) {
			$("#readium-content-container").css("visibility", "hidden");
			_paginator.replaceContent(bookDom.body.innerHTML);
		}
		else {
			var options = {
				pageAddCallback: function($newPage) {
					$newPage.click(toggleUi);
				}
			}
			_paginator = Readium.Paginator($('#container'), bookDom.body.innerHTML, options);
			if( shouldOpenInTwoUp() ) {
				_paginator.toggleTwoUp();
			}
			addPageTurnHandlers(_paginator);
		}
		fixLinks();

		// need to let the thread go for second so the css
		// is parsed before appending repaginating
		setTimeout(function() {
			fireRepaginateEvent();
		}, 8);

	};

	var addFixedLayoutCssFlag = function() {
		// just tack a class name on to the body
		$('body').addClass('apple-fixed-layout');
	};

	var showFixedLayoutBook = function() {
		addFixedLayoutCssFlag();

		var uris = _book.getAllSectionUris();
		// need to parse one viewport tag
		window.webkitResolveLocalFileSystemURL(uris[0], function(fileEntry) {
			Readium.FileSystemApi(function(fs) {
				fs.readEntry(fileEntry, function(content) {
					var parser = new window.DOMParser();
					var dom = parser.parseFromString(content, 'text/xml');
					var options = parseViewportTag(dom.getElementsByName("viewport")[0]);
					options.pageAddCallback = function($newPage) {
						$newPage.click(toggleUi);
						var iframe = $('iframe', $newPage)[0];
						if(iframe) {
							$('iframe', $newPage)[0].onload = function() {
								_book.applyBindings(this.contentDocument);
							}
						}

					};
					_paginator = Readium.FixedPaginator($('#container'), uris, options);
					_paginator.toggleTwoUp();
					fixLinks();
					addPageTurnHandlers(_paginator);

				}, function() {
					console.log('failed to load fixed layout book');
				})
			});
		});

	};

	var parseBookCallback = function(domString) {
		var parser = new window.DOMParser();
		var xmlDoc = parser.parseFromString(domString,"text/xml");
		showBook(xmlDoc);
	}

	var linkClickHandler = function(e) {
		var href = this.attributes["href"].value;
		e.preventDefault();
		if(href.match(/^http(s)?:/)) {
			chrome.tabs.create({"url":href});
		} else if( _book.goToHref(href) ) {
			openCurrentSection();
		} else {
			console.log('failed to navigate spine to ' + href);
		}
	}

	var addToc = function() {
		$('#top-bar').append(_book.getProperties().title);
		_book.getTocText(function(res) {
			var $tocArea = $('#menu');
			$tocArea.html(res);
			$('a', $tocArea).click(linkClickHandler);
		}, loadErrorHandler );
	};

	var openBook = function() {
		if(_urlArgs["book"] === undefined) {
			console.log("No book was specifiec to load");
			loadErrorHandler();
			return;
		}

		Lawnchair(function() {
			this.get(_urlArgs["book"], function(result) {
				if(result === null) {
					loadErrorHandler();
					return;
				}
				Readium.Ebook(result, function(book) {
					_book = book;
					if(_book.isFixedLayout()) {
						showFixedLayoutBook();
					}
					else {
						_book.getSectionText(parseBookCallback, loadErrorHandler);
					}
					addToc();
				}, function(e) {
					loadErrorHandler();
				});
			});
		});
	}

	var loadErrorHandler = function(e) {
		console.log("Error could not load book");
	}

	var displaySettingsAtFirstLoad = function() {
		var timeout = setTimeout(toggleUi, 2000);
	}

	// temp fix me
	var pos = "-44px";
	var toggleUi = function() {
		var style = $('#top-bar')[0].style;

		var settings = $('#settings');
		var temp = style.top;
		style.top = pos;
		pos = temp;
		settings.toggleClass('hover-fade');

	};

	var initTopBar = function() {
		$('#readium-content-container').click(toggleUi);
		$('.page-margin').click(toggleUi);
	};

	var initTocClick = function() {
		$('#show-toc-button').click(function(e) {
			$('body').toggleClass('show-toc');
			fireRepaginateEvent();
		});
	};

	// decide if should open in two up based on viewport
	// width
	var shouldOpenInTwoUp = function() {
		var width = document.documentElement.clientWidth;
		var height = document.documentElement.clientHeight;
		return width > 300 && width / height > 1.3;
	}

	$(function() {
		_urlArgs = parseUrlArgs();
		openBook();
		displaySettingsAtFirstLoad();
		initTopBar();
		initTocClick();
	});
})();
<|endoftext|>