<commit_before>/**
 * @fileoverview Description of file, its uses and information
 * about its dependencies.
 */

'use strict';

/**
 *
 * @type {*|exports|module.exports}
 */
var draw;

/**
 *
 * @type {*|exports|module.exports}
 */
var measurements;

/**
 *
 * @type {*|exports|module.exports}
 */
var advancedInfo;

/**
 *
 * @type {*|exports|module.exports}
 */
var cloud;

/**
 *
 * @type {*|exports|module.exports}
 */
var print;

/**
 *
 * @type {*|exports|module.exports}
 */
var switchLayer;

/**
 *
 * @type {*|exports|module.exports}
 */
var setBaseLayer;

/**
 *
 * @type {*|exports|module.exports}
 */
var legend;

/**
 *
 * @type {*|exports|module.exports}
 */
var meta;

/**
 *
 * @type {array}
 */
var metaDataKeys;

/**
 *
 * @type {array}
 */
var reset;

/**
 *
 * @type {*|exports|module.exports}
 */
let APIBridgeSingletone = require('./api-bridge');

/**
 *
 * @type {APIBridge}
 */
var apiBridgeInstance = false;

/**
 *
 * @type {*|exports|module.exports}
 */
var urlparser = require('./urlparser');

/**
 *
 * @type {array}
 */
var urlVars = urlparser.urlVars;

/**
 *
 * @type {showdown.Converter}
 */
var showdown = require('showdown');
var converter = new showdown.Converter();

require('dom-shims');
require('arrive');

var backboneEvents;

var pushState;
var layerTree;
var layers;
var infoClick;
var setting;
var state;

var isStarted = false;

/**
 *
 * @type {{set: module.exports.set, init: module.exports.init}}
 */
module.exports = module.exports = {
    set: function (o) {
        draw = o.draw;
        measurements = o.measurements;
        advancedInfo = o.advancedInfo;
        cloud = o.cloud;
        print = o.print;
        switchLayer = o.switchLayer;
        setBaseLayer = o.setBaseLayer;
        legend = o.legend;
        meta = o.meta;
        pushState = o.pushState;
        layerTree = o.layerTree;
        layers = o.layers;
        infoClick = o.infoClick;
        backboneEvents = o.backboneEvents;
        reset = o.reset;
        setting = o.setting;
        state = o.state;
        return this;
    },
    init: function (str) {
        apiBridgeInstance = APIBridgeSingletone();

        var doneL, doneB, loadingL = false, loadingB = false;

        cloud.get().on("dragend", function () {
            pushState.init();
        });
        cloud.get().on("moveend", function () {
            pushState.init();
        });
        cloud.get().on("move", function () {
            $("#tail").fadeOut(100);
        });

        cloud.get().on("dragstart", function () {
            $(".fade-then-dragging").animate({opacity: "0.3"}, 200);
            $(".fade-then-dragging").css("pointer-events", "none");
        });

        cloud.get().on("dragend", function () {
            $(".fade-then-dragging").animate({opacity: "1"}, 200);
            $(".fade-then-dragging").css("pointer-events", "all");

        });

        // Linking the legend and layer tree
        $(document).arrive('[data-gc2-id]', function () {
            $(this).on("change", function (e) {
              switchLayer.init($(this).data('gc2-id'), $(this).context.checked);
              e.stopPropagation();
            });
        });

        // Advanced info
        // =============

        $("#advanced-info-btn").on("click", function () {
            advancedInfo.control();
        });

        // Reset
        // =====

        $("#btn-reset").on("click", function () {
            reset.init();
        });

        $("#info-modal button").on("click", function () {
            if (!$(this).data("extraClickHandlerIsEnabled")) {
                $("#info-modal").animate({
                    right: "-" + $("#myNavmenu").width() + "px"
                }, 200, ()=>{
                    $("#info-modal.slide-right").hide();
                });
            }
        });

        $("#searchclear").on("click", function () {
            backboneEvents.get().trigger("clear:search");
        });

        backboneEvents.get().on("ready:meta", function () {
            metaDataKeys = meta.getMetaDataKeys();

            if (!isStarted) {
                isStarted = true;
                setTimeout(
                    function () {
                        // HACK! Important to actual open the menu and when close it again
                        // This will set the width of the pane the right way
                        $("#navbar-fixed-top .navbar-toggle").trigger("click");
                        if ($(document).width() < 767) {
                            setTimeout(
                                function () {
                                    $("#navbar-fixed-top .navbar-toggle").trigger("click");
                                    $("#myNavmenu").offcanvas('hide'); // Hide it also, in case of the toogle button is hidden
                                }, 200
                            );
                        }
                    }, 200
                );

                setTimeout(
                    function () {
                        if (!window.vidiConfig.doNotCloseLoadScreen) {
                            $("#loadscreen").fadeOut(200);
                        }
                    }, 600
                );
            }

        });

        // When reset:all is triggered, we rwe reset all modules.
        // Extensions must implement a listener for the reset:all event
        // and clean up
        // ============================================================
        backboneEvents.get().on("reset:all", function (ignoredModules = []) {
            console.info("Resets all", ignoredModules);

            // Should be enabled by default
            backboneEvents.get().trigger("on:infoClick");

            // Should be disabled by default
            let modulesToReset = [`advancedInfo`, `drawing`, `measurements`, `print`];
            modulesToReset.map(moduleToReset => {
                if (ignoredModules.indexOf(moduleToReset) === -1) {
                    backboneEvents.get().trigger(`off:${moduleToReset}`);
                }
            });
        });

        backboneEvents.get().on("off:measurements", function () {
            console.info("Stopping measurements");
            measurements.off();
        });

        backboneEvents.get().on("off:drawing", function () {
            console.info("Stopping drawing");
            draw.off();
        });

        backboneEvents.get().on("off:advancedInfo", function () {
            console.info("Stopping advanced info");
            advancedInfo.off();
        });

        /**
         * Processing turn on/off events for modules
         */
        let modulesToReactOnEachOtherChanges = [`measurements`, `drawing`, `advancedInfo`];
        modulesToReactOnEachOtherChanges.map(module => {
            backboneEvents.get().on(`${module}:turnedOn`, function () {
                console.info(`${module} was turned on`);
                // Reset all modules except caller
                backboneEvents.get().trigger(`reset:all`, [module]);
                // Disable the infoClick
                backboneEvents.get().trigger(`off:infoClick`);
            });

            // Drawing was turned off
            backboneEvents.get().on(`${module}:turnedOff`, function () {
                console.info(`${module} was turned off`);
                // Reset all modules except caller
                backboneEvents.get().trigger(`reset:all`, [module]);
            });
        });

        // Info click
        // ==========
        backboneEvents.get().on("on:infoClick", function () {
            console.info("Activating infoClick");
            infoClick.active(true);
        });

        backboneEvents.get().on("off:infoClick", function () {
            console.info("Deactivating infoClick");
            infoClick.active(false);
        });

        backboneEvents.get().on("reset:infoClick", function () {
            console.info("Resetting infoClick");
            infoClick.reset();
        });

        // Layer loading
        // =============
        backboneEvents.get().on("startLoading:layers", function (e) {
            console.log("Start loading: " + e);
            doneB = doneL = false;
            loadingL = true;
            $(".loadingIndicator").fadeIn(200);
        });

        backboneEvents.get().on("startLoading:setBaselayer", function (e) {
            console.log("Start loading: " + e);
            doneB = doneL = false;
            loadingB = true;
            $(".loadingIndicator").fadeIn(200);
        });

        backboneEvents.get().on("doneLoading:layers", function (e) {
            console.log("Done loading: " + e);
            if (layers.getCountLoading() === 0) {
                layers.resetCount();
                doneL = true;
                loadingL = false;
                if ((doneL && doneB) || loadingB === false) {
                    console.log("Setting timeout to " + window.vidiTimeout + "ms");
                    setTimeout(function () {
                        console.info("Layers all loaded L");
                        backboneEvents.get().trigger("allDoneLoading:layers");
                        doneB = doneL = false;
                        $(".loadingIndicator").fadeOut(200);
                    }, window.vidiTimeout)
                }
            }
        });

        backboneEvents.get().on("doneLoading:setBaselayer", function (e) {
            console.log("Done loading: " + e);
            doneB = true;
            loadingB = false;
            if ((doneL && doneB) || loadingL === false) {
                console.log("Setting timeout to " + window.vidiTimeout + "ms");
                setTimeout(function () {
                    console.info("Layers all loaded B");
                    backboneEvents.get().trigger("allDoneLoading:layers");
                    doneB = doneL = false;
                    $(".loadingIndicator").fadeOut(200);
                }, window.vidiTimeout)
            }
        });

        $(document).bind('mousemove', function (e) {
            $('#tail').css({
                left: e.pageX + 20,
                top: e.pageY
            });
        });

        // Print
        // =====
        $("#print-btn").on("click", function () {
            print.activate();
            $("#get-print-fieldset").prop("disabled", true);
        });

        $("#start-print-btn").on("click", function () {
            if (print.print()) {
                $(this).button('loading');
                $("#get-print-fieldset").prop("disabled", true);
            }

        });

        backboneEvents.get().on("off:print", function () {
            print.off();
        });

        backboneEvents.get().on("end:print", function (response) {
            $("#get-print-fieldset").prop("disabled", false);
            $("#download-pdf, #open-pdf").attr("href", "/tmp/print/pdf/" + response.key + ".pdf");
            $("#download-pdf").attr("download", response.key);
            $("#open-html").attr("href", response.url);
            $("#start-print-btn").button('reset');
            console.log("GEMessage:LaunchURL:" + urlparser.uriObj.protocol() + "://" +  urlparser.uriObj.host() + "/tmp/print/pdf/" + response.key + ".pdf");
        });

        backboneEvents.get().on("refresh:auth", function (response) {
            apiBridgeInstance.resubmitSkippedFeatures();
        });

        // Refresh browser state. E.g. after a session start
        // =================================================
        backboneEvents.get().on("refresh:meta", function (response) {

            meta.init()

                .then(function () {
                        return setting.init();
                    },

                    function (error) {
                        console.log(error); // Stacktrace
                        alert("Vidi is loaded without schema. Can't set extent or add layers");
                        backboneEvents.get().trigger("ready:meta");
                        state.init();
                    })

                .then(function () {
                    layerTree.create();
                    state.init();
                });

        });

        // HACK. Arrive.js seems to mess up Wkhtmltopdf,
        // so we don't bind events on print HTML page.
        // =============================================

        if (!urlVars.px && !urlVars.py) {
            $(document).arrive('[data-toggle="tooltip"]', function () {
                $(this).tooltip()
            });

            $(document).arrive('.info-label', function () {
                $(this).on("click", function (e) {
                    var t = ($(this).data('gc2-id')), html,
                        meta = metaDataKeys[t] ? $.parseJSON(metaDataKeys[t].meta) : null,
                        name = metaDataKeys[t] ? metaDataKeys[t].f_table_name : null,
                        title = metaDataKeys[t] ? metaDataKeys[t].f_table_title : null,
                        abstract = metaDataKeys[t] ? metaDataKeys[t].f_table_abstract : null;

                    html = (meta !== null
                        && typeof meta.meta_desc !== "undefined"
                        && meta.meta_desc !== "") ?
                        converter.makeHtml(meta.meta_desc) : abstract;

                    moment.locale('da');

                    for (var key in  metaDataKeys[t]) {
                        if (metaDataKeys[t].hasOwnProperty(key)) {
                            console.log(key + " -> " + metaDataKeys[t][key]);
                            if (key === "lastmodified") {
                                metaDataKeys[t][key] = moment(metaDataKeys[t][key]).format('LLLL');
                            }
                        }
                    }

                    html = html ? Mustache.render(html, metaDataKeys[t]) : "";

                    $("#info-modal.slide-right").show();
                    $("#info-modal.slide-right").animate({right: "0"}, 200);
                    $("#info-modal .modal-title").html(title || name);
                    $("#info-modal .modal-body").html(html + '

');
                    legend.init([t], "#info-modal-legend");
                    e.stopPropagation();
                });
            });

            $(document).arrive('[data-scale-ul]', function () {
                $(this).on("click", function (e) {
                    $("#select-scale").val($(this).data('scale-ul')).trigger("change");
                });
            });

            //************************//
            var searchPanelOpen
            var searchShow = function () {
                $("#search-ribbon").animate({
                    right: '0'
                }, 500, function () {
                    $("#pane").animate({
                        right: '550px'
                    }, 500);

                    $('#map').animate({ "width": "-=275px" }, 500);
                });

                searchPanelOpen = true;
            };

            var searchHide = function () {
                $("#pane").animate({
                    right: '40px'
                }, 500);
                $("#map").animate({
                    width: '100%'
                }, 500, function () {
                    $("#search-ribbon").animate({
                        right: '-510px'
                    }, 500);
                });

                searchPanelOpen = false
            };
            $('#search-border').click(function () {
                if (searchPanelOpen) {
                    searchHide();
                } else {
                    searchShow()
                }
            });
        }
    }
};<commit_msg>Correctly managing the legend control changes<commit_after>/**
 * @fileoverview Description of file, its uses and information
 * about its dependencies.
 */

'use strict';

/**
 *
 * @type {*|exports|module.exports}
 */
var draw;

/**
 *
 * @type {*|exports|module.exports}
 */
var measurements;

/**
 *
 * @type {*|exports|module.exports}
 */
var advancedInfo;

/**
 *
 * @type {*|exports|module.exports}
 */
var cloud;

/**
 *
 * @type {*|exports|module.exports}
 */
var print;

/**
 *
 * @type {*|exports|module.exports}
 */
var switchLayer;

/**
 *
 * @type {*|exports|module.exports}
 */
var setBaseLayer;

/**
 *
 * @type {*|exports|module.exports}
 */
var legend;

/**
 *
 * @type {*|exports|module.exports}
 */
var meta;

/**
 *
 * @type {array}
 */
var metaDataKeys;

/**
 *
 * @type {array}
 */
var reset;

/**
 *
 * @type {*|exports|module.exports}
 */
let APIBridgeSingletone = require('./api-bridge');

/**
 *
 * @type {APIBridge}
 */
var apiBridgeInstance = false;

/**
 *
 * @type {*|exports|module.exports}
 */
var urlparser = require('./urlparser');

/**
 *
 * @type {array}
 */
var urlVars = urlparser.urlVars;

/**
 *
 * @type {showdown.Converter}
 */
var showdown = require('showdown');
var converter = new showdown.Converter();

require('dom-shims');
require('arrive');

var backboneEvents;

var pushState;
var layerTree;
var layers;
var infoClick;
var setting;
var state;

var isStarted = false;

/**
 *
 * @type {{set: module.exports.set, init: module.exports.init}}
 */
module.exports = module.exports = {
    set: function (o) {
        draw = o.draw;
        measurements = o.measurements;
        advancedInfo = o.advancedInfo;
        cloud = o.cloud;
        print = o.print;
        switchLayer = o.switchLayer;
        setBaseLayer = o.setBaseLayer;
        legend = o.legend;
        meta = o.meta;
        pushState = o.pushState;
        layerTree = o.layerTree;
        layers = o.layers;
        infoClick = o.infoClick;
        backboneEvents = o.backboneEvents;
        reset = o.reset;
        setting = o.setting;
        state = o.state;
        return this;
    },
    init: function (str) {
        apiBridgeInstance = APIBridgeSingletone();

        var doneL, doneB, loadingL = false, loadingB = false;

        cloud.get().on("dragend", function () {
            pushState.init();
        });
        cloud.get().on("moveend", function () {
            pushState.init();
        });
        cloud.get().on("move", function () {
            $("#tail").fadeOut(100);
        });

        cloud.get().on("dragstart", function () {
            $(".fade-then-dragging").animate({opacity: "0.3"}, 200);
            $(".fade-then-dragging").css("pointer-events", "none");
        });

        cloud.get().on("dragend", function () {
            $(".fade-then-dragging").animate({opacity: "1"}, 200);
            $(".fade-then-dragging").css("pointer-events", "all");

        });

        // Linking the legend and layer tree
        $(document).arrive('[data-gc2-id]', function () {
            $(this).on("change", function (e) {
                if (!$(this).data(`gc2-layer-type`)) {
                    // legend control was changed, so the corresponding layerTree control has to be changed
                    e.stopPropagation();
                    $(`#layers`).find(`input[data-gc2-id="${$(this).data('gc2-id')}"]`).trigger('click');
                }
            });
        });

        // Advanced info
        // =============

        $("#advanced-info-btn").on("click", function () {
            advancedInfo.control();
        });

        // Reset
        // =====

        $("#btn-reset").on("click", function () {
            reset.init();
        });

        $("#info-modal button").on("click", function () {
            if (!$(this).data("extraClickHandlerIsEnabled")) {
                $("#info-modal").animate({
                    right: "-" + $("#myNavmenu").width() + "px"
                }, 200, ()=>{
                    $("#info-modal.slide-right").hide();
                });
            }
        });

        $("#searchclear").on("click", function () {
            backboneEvents.get().trigger("clear:search");
        });

        backboneEvents.get().on("ready:meta", function () {
            metaDataKeys = meta.getMetaDataKeys();

            if (!isStarted) {
                isStarted = true;
                setTimeout(
                    function () {
                        // HACK! Important to actual open the menu and when close it again
                        // This will set the width of the pane the right way
                        $("#navbar-fixed-top .navbar-toggle").trigger("click");
                        if ($(document).width() < 767) {
                            setTimeout(
                                function () {
                                    $("#navbar-fixed-top .navbar-toggle").trigger("click");
                                    $("#myNavmenu").offcanvas('hide'); // Hide it also, in case of the toogle button is hidden
                                }, 200
                            );
                        }
                    }, 200
                );

                setTimeout(
                    function () {
                        if (!window.vidiConfig.doNotCloseLoadScreen) {
                            $("#loadscreen").fadeOut(200);
                        }
                    }, 600
                );
            }

        });

        // When reset:all is triggered, we rwe reset all modules.
        // Extensions must implement a listener for the reset:all event
        // and clean up
        // ============================================================
        backboneEvents.get().on("reset:all", function (ignoredModules = []) {
            console.info("Resets all", ignoredModules);

            // Should be enabled by default
            backboneEvents.get().trigger("on:infoClick");

            // Should be disabled by default
            let modulesToReset = [`advancedInfo`, `drawing`, `measurements`, `print`];
            modulesToReset.map(moduleToReset => {
                if (ignoredModules.indexOf(moduleToReset) === -1) {
                    backboneEvents.get().trigger(`off:${moduleToReset}`);
                }
            });
        });

        backboneEvents.get().on("off:measurements", function () {
            console.info("Stopping measurements");
            measurements.off();
        });

        backboneEvents.get().on("off:drawing", function () {
            console.info("Stopping drawing");
            draw.off();
        });

        backboneEvents.get().on("off:advancedInfo", function () {
            console.info("Stopping advanced info");
            advancedInfo.off();
        });

        /**
         * Processing turn on/off events for modules
         */
        let modulesToReactOnEachOtherChanges = [`measurements`, `drawing`, `advancedInfo`];
        modulesToReactOnEachOtherChanges.map(module => {
            backboneEvents.get().on(`${module}:turnedOn`, function () {
                console.info(`${module} was turned on`);
                // Reset all modules except caller
                backboneEvents.get().trigger(`reset:all`, [module]);
                // Disable the infoClick
                backboneEvents.get().trigger(`off:infoClick`);
            });

            // Drawing was turned off
            backboneEvents.get().on(`${module}:turnedOff`, function () {
                console.info(`${module} was turned off`);
                // Reset all modules except caller
                backboneEvents.get().trigger(`reset:all`, [module]);
            });
        });

        // Info click
        // ==========
        backboneEvents.get().on("on:infoClick", function () {
            console.info("Activating infoClick");
            infoClick.active(true);
        });

        backboneEvents.get().on("off:infoClick", function () {
            console.info("Deactivating infoClick");
            infoClick.active(false);
        });

        backboneEvents.get().on("reset:infoClick", function () {
            console.info("Resetting infoClick");
            infoClick.reset();
        });

        // Layer loading
        // =============
        backboneEvents.get().on("startLoading:layers", function (e) {
            console.log("Start loading: " + e);
            doneL = false;
            loadingL = true;
            $(".loadingIndicator").fadeIn(200);
        });

        backboneEvents.get().on("startLoading:setBaselayer", function (e) {
            console.log("Start loading: " + e);
            doneB = false;
            loadingB = true;
            $(".loadingIndicator").fadeIn(200);
        });

        backboneEvents.get().on("doneLoading:layers", function (e) {
            console.log("Done loading: " + e, doneL, doneB, loadingL, loadingB);
            if (layers.getCountLoading() === 0) {
                layers.resetCount();
                doneL = true;
                loadingL = false;
                if ((doneL && doneB) || loadingB === false) {
                    console.log("Setting timeout to " + window.vidiTimeout + "ms");
                    setTimeout(function () {
                        console.info("Layers all loaded L");
                        backboneEvents.get().trigger("allDoneLoading:layers");
                        doneB = doneL = false;
                        $(".loadingIndicator").fadeOut(200);
                    }, window.vidiTimeout)
                }
            }
        });

        backboneEvents.get().on("doneLoading:setBaselayer", function (e) {
            console.log("Done loading: " + e, doneL, doneB, loadingL, loadingB);
            doneB = true;
            loadingB = false;
            if ((doneL && doneB) || loadingL === false) {
                console.log("Setting timeout to " + window.vidiTimeout + "ms");
                setTimeout(function () {
                    console.info("Layers all loaded B");
                    backboneEvents.get().trigger("allDoneLoading:layers");
                    doneB = doneL = false;
                    $(".loadingIndicator").fadeOut(200);
                }, window.vidiTimeout)
            }
        });

        $(document).bind('mousemove', function (e) {
            $('#tail').css({
                left: e.pageX + 20,
                top: e.pageY
            });
        });

        // Print
        // =====
        $("#print-btn").on("click", function () {
            print.activate();
            $("#get-print-fieldset").prop("disabled", true);
        });

        $("#start-print-btn").on("click", function () {
            if (print.print()) {
                $(this).button('loading');
                $("#get-print-fieldset").prop("disabled", true);
            }

        });

        backboneEvents.get().on("off:print", function () {
            print.off();
        });

        backboneEvents.get().on("end:print", function (response) {
            $("#get-print-fieldset").prop("disabled", false);
            $("#download-pdf, #open-pdf").attr("href", "/tmp/print/pdf/" + response.key + ".pdf");
            $("#download-pdf").attr("download", response.key);
            $("#open-html").attr("href", response.url);
            $("#start-print-btn").button('reset');
            console.log("GEMessage:LaunchURL:" + urlparser.uriObj.protocol() + "://" +  urlparser.uriObj.host() + "/tmp/print/pdf/" + response.key + ".pdf");
        });

        backboneEvents.get().on("refresh:auth", function (response) {
            apiBridgeInstance.resubmitSkippedFeatures();
        });

        // Refresh browser state. E.g. after a session start
        // =================================================
        backboneEvents.get().on("refresh:meta", function (response) {

            meta.init()

                .then(function () {
                        return setting.init();
                    },

                    function (error) {
                        console.log(error); // Stacktrace
                        alert("Vidi is loaded without schema. Can't set extent or add layers");
                        backboneEvents.get().trigger("ready:meta");
                        state.init();
                    })

                .then(function () {
                    layerTree.create();
                    state.init();
                });

        });

        // HACK. Arrive.js seems to mess up Wkhtmltopdf,
        // so we don't bind events on print HTML page.
        // =============================================

        if (!urlVars.px && !urlVars.py) {
            $(document).arrive('[data-toggle="tooltip"]', function () {
                $(this).tooltip()
            });

            $(document).arrive('.info-label', function () {
                $(this).on("click", function (e) {
                    var t = ($(this).data('gc2-id')), html,
                        meta = metaDataKeys[t] ? $.parseJSON(metaDataKeys[t].meta) : null,
                        name = metaDataKeys[t] ? metaDataKeys[t].f_table_name : null,
                        title = metaDataKeys[t] ? metaDataKeys[t].f_table_title : null,
                        abstract = metaDataKeys[t] ? metaDataKeys[t].f_table_abstract : null;

                    html = (meta !== null
                        && typeof meta.meta_desc !== "undefined"
                        && meta.meta_desc !== "") ?
                        converter.makeHtml(meta.meta_desc) : abstract;

                    moment.locale('da');

                    for (var key in  metaDataKeys[t]) {
                        if (metaDataKeys[t].hasOwnProperty(key)) {
                            console.log(key + " -> " + metaDataKeys[t][key]);
                            if (key === "lastmodified") {
                                metaDataKeys[t][key] = moment(metaDataKeys[t][key]).format('LLLL');
                            }
                        }
                    }

                    html = html ? Mustache.render(html, metaDataKeys[t]) : "";

                    $("#info-modal.slide-right").show();
                    $("#info-modal.slide-right").animate({right: "0"}, 200);
                    $("#info-modal .modal-title").html(title || name);
                    $("#info-modal .modal-body").html(html + '

');
                    legend.init([t], "#info-modal-legend");
                    e.stopPropagation();
                });
            });

            $(document).arrive('[data-scale-ul]', function () {
                $(this).on("click", function (e) {
                    $("#select-scale").val($(this).data('scale-ul')).trigger("change");
                });
            });

            //************************//
            var searchPanelOpen
            var searchShow = function () {
                $("#search-ribbon").animate({
                    right: '0'
                }, 500, function () {
                    $("#pane").animate({
                        right: '550px'
                    }, 500);

                    $('#map').animate({ "width": "-=275px" }, 500);
                });

                searchPanelOpen = true;
            };

            var searchHide = function () {
                $("#pane").animate({
                    right: '40px'
                }, 500);
                $("#map").animate({
                    width: '100%'
                }, 500, function () {
                    $("#search-ribbon").animate({
                        right: '-510px'
                    }, 500);
                });

                searchPanelOpen = false
            };
            $('#search-border').click(function () {
                if (searchPanelOpen) {
                    searchHide();
                } else {
                    searchShow()
                }
            });
        }
    }
};<|endoftext|>


<commit_before>#! /usr/bin/env node
var shell = require('shelljs');
var path = require('path');

function exec(command, afterCb) {
shell.exec(command, function (code) {
    console.log('Exit code:', code);
    if (afterCb && typeof afterCb === 'function') {
        afterCb();
    }
});
}

exec('npm run docs:build', function () {
    exec('git add --all && git commit -m "Deploying documentation" && git push', function () {
        console.log('\x1b[32m%s\x1b[0m', 'Documentation was deployed successfully');
    });
});<commit_msg>cubbles/cubbles#38 remove uneeded code<commit_after>#! /usr/bin/env node
var shell = require('shelljs');

function exec(command, afterCb) {
shell.exec(command, function (code) {
    console.log('Exit code:', code);
    if (afterCb && typeof afterCb === 'function') {
        afterCb();
    }
});
}

exec('npm run docs:build', function () {
    exec('git add --all && git commit -m "Deploying documentation" && git push', function () {
        console.log('\x1b[32m%s\x1b[0m', 'Documentation was deployed successfully');
    });
});<|endoftext|>


<commit_before>import Ember from 'ember';
import layout from '../templates/components/search-flow';

export default Ember.Component.extend({
  layout,
  classNames: ['search-flow'],
  defaultParameterValues: {
    allowMultiple: true,
    remoteOptions: false,
    contains: false
  },
  init() {
    this._super(...arguments);
    this.processQueries();
    this.set('isSelectingParameter', false);
  },
  getParameter(parameter) {
    return this.get('parameters').find(param => {
      return parameter.toLowerCase() === param.name.toLowerCase();
    });
  },
  processQueries: Ember.observer('query,parameters', function () {
    if (this.get('queryGeneretedByComponent')) {
      this.set('queryGeneretedByComponent', false);
      return;
    }
    let filters = this.set('filters', Ember.A([]));
    Object.keys(this.get('query')).forEach(key => {
      let keys = [key];
      let isContains = false;
      if (key === 'contains') {
        keys = Object.keys(this.get('query.contains'));
        isContains = true;
      }

      keys.forEach(key => {
        let values = this.get('query');
        if (isContains){
          values = values['contains'];
        }
        values = values[key];
        if (!Ember.isArray(values)) {
          values = [values];
        }
        values.forEach(value => {
          let parameter = this.getParameter(key);
          if (parameter && (!isContains || (isContains && parameter.contains))) {
            let filter = Ember.Object.create({
              parameter: Ember.Object.create(parameter),
              value
            });
            if (isContains){
              filter.set('isContains', true);
            }
            filter.parameters = Ember.assign({}, this.get('defaultParameterValues'), filter.parameters);
            filters.pushObject(filter);
          }
        });
      });
    });
  }),
  availableParameters: Ember.computed('parameters,filters.[],filters.@each.parameter', function () {
    return this.get('parameters').reject(parameter => {
      return parameter.allowMultiple === false && this.get('filters').find(filter => {
        return filter.get('parameter.name') === parameter.name;
      });
    });
  }),
  isParameterAvailable(parameter) {
    if (!parameter) {
      return true;
    }
    return this.get('availableParameters').findBy('name', parameter.name);
  },
  setOnQuery(isContains, query, path, value){
    if (isContains){
      query.contains[path] = value;
    }
    else {
      query[path] = value;
    }
  },
  getOnQuery(isContains, query, path){
    if (isContains){
      return query.contains[path];
    }
    return query[path];
  },
  generateQuery() {
    let query = {};
    this.get('filters').forEach(filter => {
      let queryPath = filter.parameter.name;
      if (filter.get('isContains') && !query.contains) {
          query.contains = {};
      }
      let queryItem = this.getOnQuery(filter.get('isContains'), query, queryPath);
      if (queryItem) {
        if (!Ember.isArray(queryItem)) {
          if (queryItem === filter.value) {
            return;
          }
          queryItem = [queryItem];
        }
        if (queryItem.includes(filter.value)) {
          return;
        }
        queryItem.push(filter.value);
        this.setOnQuery(filter.get('isContains'), query, queryPath, queryItem);
      }
      else {
        this.setOnQuery(filter.get('isContains'), query, queryPath, filter.value);
      }
    });

    this.set('queryGeneretedByComponent', true);
    this.set('query', query);
    if (this.get('onQueryUpdated')) {
      this.get('onQueryUpdated')(query);
    }
  },
  canAddNewFilter: Ember.computed('isSelectingParameter,filters.[],filters.@each.isFocused', function () {
    if (this.get('isSelectingParameter')) {
      return false;
    }
    return !this.get('filters').isAny('isFocused');
  }),
  actions: {
    newFilter() {
      if (event.which === 13) { // Enter key
        // Must prevent the filter from auto selecting an option
        this.set('didHitEnter', true);
      }
      this.set('isSelectingParameter', true);
    },
    newFilterWithParameter(parameter) {
      if (!this.isParameterAvailable(parameter)) {
        return;
      }
      let filter = Ember.Object.create({
        parameter: Ember.Object.create(parameter),
        value: '',
      });
      filter.parameter = Ember.assign({}, this.get('defaultParameterValues'), filter.parameter);
      this.get('filters').pushObject(filter);
      this.set('isSelectingParameter', false);
    },
    setParameterToFilter(parameter, filter) {
      filter.set('parameter', Ember.Object.create(parameter));
    },
    removeFilter(query) {
      this.get('filters').removeObject(query);
      this.generateQuery();
    },
    inputBlurred(isNewParameter, filter, shouldRemoveFilter) {
      if (isNewParameter) {
        this.set('isSelectingParameter', false);
        return;
      }

      if (!filter.value || shouldRemoveFilter) {
        this.get('filters').removeObject(filter);
      }
      this.set('addingNewfilter', false);
      this.generateQuery();
    },
  }
});<commit_msg>ensure name and title are defined on the parameters list<commit_after>import Ember from 'ember';
import layout from '../templates/components/search-flow';

export default Ember.Component.extend({
  layout,
  classNames: ['search-flow'],
  defaultParameterValues: {
    allowMultiple: true,
    remoteOptions: false,
    contains: false
  },
  init() {
    this._super(...arguments);
    this.processQueries();
    this.set('isSelectingParameter', false);
  },
  getParameter(parameter) {
    return this.get('parameters').find(param => {
      return parameter.toLowerCase() === param.name.toLowerCase();
    });
  },
  processQueries: Ember.observer('query,parameters', function () {
    if (this.get('queryGeneretedByComponent')) {
      this.set('queryGeneretedByComponent', false);
      return;
    }
    let filters = this.set('filters', Ember.A([]));
    Object.keys(this.get('query')).forEach(key => {
      let keys = [key];
      let isContains = false;
      if (key === 'contains') {
        keys = Object.keys(this.get('query.contains'));
        isContains = true;
      }

      keys.forEach(key => {
        let values = this.get('query');
        if (isContains){
          values = values['contains'];
        }
        values = values[key];
        if (!Ember.isArray(values)) {
          values = [values];
        }
        values.forEach(value => {
          let parameter = this.getParameter(key);
          if (parameter && (!isContains || (isContains && parameter.contains))) {
            let filter = Ember.Object.create({
              parameter: Ember.Object.create(parameter),
              value
            });
            if (isContains){
              filter.set('isContains', true);
            }
            filter.parameters = Ember.assign({}, this.get('defaultParameterValues'), filter.parameters);
            filters.pushObject(filter);
          }
        });
      });
    });
  }),
  availableParameters: Ember.computed('parameters,filters.[],filters.@each.parameter', function () {
    return this.get('parameters').reject(parameter => {
      return parameter.name || parameter.title || (parameter.allowMultiple === false && this.get('filters').find(filter => {
        return filter.get('parameter.name') === parameter.name;
      }));
    });
  }),
  isParameterAvailable(parameter) {
    if (!parameter) {
      return true;
    }
    return this.get('availableParameters').findBy('name', parameter.name);
  },
  setOnQuery(isContains, query, path, value){
    if (isContains){
      query.contains[path] = value;
    }
    else {
      query[path] = value;
    }
  },
  getOnQuery(isContains, query, path){
    if (isContains){
      return query.contains[path];
    }
    return query[path];
  },
  generateQuery() {
    let query = {};
    this.get('filters').forEach(filter => {
      let queryPath = filter.parameter.name;
      if (filter.get('isContains') && !query.contains) {
          query.contains = {};
      }
      let queryItem = this.getOnQuery(filter.get('isContains'), query, queryPath);
      if (queryItem) {
        if (!Ember.isArray(queryItem)) {
          if (queryItem === filter.value) {
            return;
          }
          queryItem = [queryItem];
        }
        if (queryItem.includes(filter.value)) {
          return;
        }
        queryItem.push(filter.value);
        this.setOnQuery(filter.get('isContains'), query, queryPath, queryItem);
      }
      else {
        this.setOnQuery(filter.get('isContains'), query, queryPath, filter.value);
      }
    });

    this.set('queryGeneretedByComponent', true);
    this.set('query', query);
    if (this.get('onQueryUpdated')) {
      this.get('onQueryUpdated')(query);
    }
  },
  canAddNewFilter: Ember.computed('isSelectingParameter,filters.[],filters.@each.isFocused', function () {
    if (this.get('isSelectingParameter')) {
      return false;
    }
    return !this.get('filters').isAny('isFocused');
  }),
  actions: {
    newFilter() {
      if (event.which === 13) { // Enter key
        // Must prevent the filter from auto selecting an option
        this.set('didHitEnter', true);
      }
      this.set('isSelectingParameter', true);
    },
    newFilterWithParameter(parameter) {
      if (!this.isParameterAvailable(parameter)) {
        return;
      }
      let filter = Ember.Object.create({
        parameter: Ember.Object.create(parameter),
        value: '',
      });
      filter.parameter = Ember.assign({}, this.get('defaultParameterValues'), filter.parameter);
      this.get('filters').pushObject(filter);
      this.set('isSelectingParameter', false);
    },
    setParameterToFilter(parameter, filter) {
      filter.set('parameter', Ember.Object.create(parameter));
    },
    removeFilter(query) {
      this.get('filters').removeObject(query);
      this.generateQuery();
    },
    inputBlurred(isNewParameter, filter, shouldRemoveFilter) {
      if (isNewParameter) {
        this.set('isSelectingParameter', false);
        return;
      }

      if (!filter.value || shouldRemoveFilter) {
        this.get('filters').removeObject(filter);
      }
      this.set('addingNewfilter', false);
      this.generateQuery();
    },
  }
});<|endoftext|>


<commit_before>/* See license.txt for terms of usage */

FBL.ns(function() { with (FBL) {

// ************************************************************************************************
// Constants

const Cc = Components.classes;
const Ci = Components.interfaces;

// ************************************************************************************************

/**
 * @class Implements Firebug activation logic.
 *
 * 1) Part of the logic is based on annotation service (see components/firebug-annotations.js)
 *    in order to remember whether Firebug is activated for given site or not.
 *    If there is "firebugged.showFirebug" annotation for a given site Firbug is activated.
 *    If there is "firebugged.closed" annotation for a given site Firbug is not activated.
 *
 * 2) Othe part is based on extensions.firebug.allPagesActivation option. This option
 *    can be set to the following values:
 *    none: The option isn't used (default value)
 *    on:   Firebug is activated for all URLs.
 *    off:  Firebug is never activated.
 *
 *    This logic has higher priority over the URL annotations.
 *    If "off" options is selected, all existing URL annotations are removed.
 */
Firebug.Activation = extend(Firebug.Module,
{
    dispatchName: "activation",

    initializeUI: function()  // called once
    {
        Firebug.Module.initializeUI.apply(this, arguments);

        TabWatcher.addListener(this.TabWatcherListener);

        // Create annotation service.
        this.annotationSvc = Cc["@joehewitt.com/firebug-annotation-service;1"]
            .getService(Ci.nsISupports).wrappedJSObject;

        // Update option menu item.
        this.updateAllPagesActivation();
    },

    shutdown: function()
    {
        Firebug.Module.shutdown.apply(this, arguments);

        TabWatcher.removeListener(this.TabWatcherListener);

        this.annotationSvc.flush();
    },

    convertToURIKey: function(url, sameOrigin)  // process the URL to canonicalize it. Need not be reversible.
    {
        var uri = makeURI(normalizeURL(url));

        if (Firebug.filterSystemURLs && isSystemURL(url))
            return uri;

        if (url == "about:blank")  // avoid exceptions.
            return uri;

        if (uri && sameOrigin)
        {
            try
            {
                var prePath = uri.prePath; // returns the string before the path (such as "scheme://user:password@host:port").
                var shortURI = makeURI(prePath);
                if (!shortURI)
                    return uri;

                var host = shortURI.host;
                if (host)
                {
                    var crossDomain = host.split('.').slice(-2)
                    shortURI.host = crossDomain.join('.');
                    return shortURI
                }
            }
            catch (exc)
            {
                if (FBTrace.DBG_ERRORS)
                    FBTrace.sysout("activation.convertToURIKey returning full URI, activateSameOrigin FAILS for shortURI "+shortURI+" because: "+exc, exc);
                return uri;
            }
        }
        return uri;
    },

    shouldCreateContext: function(browser, url, userCommands)  // true if the Places annotation the URI "firebugged"
    {
        if (FBTrace.DBG_ACTIVATION)
            FBTrace.sysout("shouldCreateContext allPagesActivation " + Firebug.allPagesActivation);

        if (Firebug.allPagesActivation == "off")
            return false;

        if (Firebug.allPagesActivation == "on")
            return true;

        if (Firebug.filterSystemURLs && isSystemURL(url)) // if about:blank gets thru, 1483 fails
            return false;

        if (userCommands)
            return true;

        try
        {
            var uri = this.convertToURIKey(url, Firebug.activateSameOrigin);
            if (!uri)
                return false;

            var hasAnnotation = this.annotationSvc.pageHasAnnotation(uri);

            if (FBTrace.DBG_ACTIVATION)
                FBTrace.sysout("shouldCreateContext hasAnnotation "+hasAnnotation +
                    " for "+uri.spec+" in "+browser.contentWindow.location +
                    " using activateSameOrigin: "+Firebug.activateSameOrigin);

            // Annotated so, return the value.
            if (hasAnnotation)
                return this.checkAnnotation(browser, uri);

            if (browser.FirebugLink) // then TabWatcher found a connection
            {
                var dst = browser.FirebugLink.dst;
                var dstURI = this.convertToURIKey(dst.spec, Firebug.activateSameOrigin);
                if (FBTrace.DBG_ACTIVATION)
                    FBTrace.sysout("shouldCreateContext found FirebugLink pointing to " +
                        dstURI.spec, browser.FirebugLink);

                if (dstURI && dstURI.equals(uri)) // and it matches us now
                {
                    var srcURI = this.convertToURIKey(browser.FirebugLink.src.spec, Firebug.activateSameOrigin);
                    if (srcURI)
                    {
                        if (FBTrace.DBG_ACTIVATION)
                            FBTrace.sysout("shouldCreateContext found FirebugLink pointing from " +
                                srcURI.spec, browser.FirebugLink);

                        if (srcURI.schemeIs("file") || (dstURI.host == srcURI.host) ) // and it's on the same domain
                        {
                            hasAnnotation = this.annotationSvc.pageHasAnnotation(srcURI);
                            if (hasAnnotation) // and the source page was annotated.
                            {
                                var srcShow = this.checkAnnotation(browser, srcURI);
                                if (srcShow)  // and the source annotation said show it
                                    this.watchBrowser(browser);  // so we show dst as well.
                                return srcShow;
                            }
                        }
                    }
                }
                else
                {
                    if (FBTrace.DBG_ACTIVATION)
                        FBTrace.sysout("shouldCreateContext FirebugLink does not match "+uri.spec, browser.FirebugLink);
                }
            }
            else if (browser.contentWindow.opener)
            {
                var openerContext = TabWatcher.getContextByWindow(browser.contentWindow.opener);

                if (FBTrace.DBG_ACTIVATION)
                    FBTrace.sysout("shouldCreateContext opener found, has "+
                        (openerContext?"a ":"no ")+" context: "+
                        browser.contentWindow.opener.location);

                if (openerContext)
                    return true;  // popup windows of Firebugged windows are Firebugged
            }

            return false;   // don't createContext
        }
        catch (exc)
        {
            if (FBTrace.DBG_ERRORS)
                FBTrace.sysout("pageHasAnnoation FAILS for url: "+url+" which gave uri "+(uri?uri.spec:"null"), exc);
        }
    },

    checkAnnotation: function(browser, uri)
    {
        var annotation = this.annotationSvc.getPageAnnotation(uri);

        if (FBTrace.DBG_ACTIVATION)
            FBTrace.sysout("shouldCreateContext read back annotation "+annotation+" for uri "+uri.spec);

        // then the user closed Firebug on this page last time
        if ((Firebug.allPagesActivation != "on") && (annotation.indexOf("closed") > 0))
            return false; // annotated as 'closed', don't create
        else
            return true;    // annotated, createContext
    },

    shouldShowContext: function(context)
    {
        return this.shouldCreateContext(context.browser, context.getWindowLocation().toString());
    },

    watchBrowser: function(browser)  // Firebug is opened in browser
    {
        var annotation = "firebugged.showFirebug";
        this.setPageAnnotation(browser.currentURI.spec, annotation);
    },

    unwatchBrowser: function(browser, userCommands)  // Firebug closes in browser
    {
        if (userCommands)  // then mark to not open virally.
            this.setPageAnnotation(uri, "firebugged.closed");
        else
            this.removePageAnnotation(uri); // unmark this URI
    },

    clearAnnotations: function()
    {
        this.annotationSvc.clear();
    },

    setPageAnnotation: function(currentURI, annotation)
    {
        var uri = this.convertToURIKey(currentURI, Firebug.activateSameOrigin);
        if (uri)
            this.annotationSvc.setPageAnnotation(uri, annotation);

        if (Firebug.activateSameOrigin)
        {
            uri = this.convertToURIKey(currentURI, false);
            if (uri)
                this.annotationSvc.setPageAnnotation(uri, annotation);
        }
    },

    removePageAnnotation: function(currentURI)
    {
        var uri = this.convertToURIKey(currentURI, Firebug.activateSameOrigin);
        if (uri)
            this.annotationSvc.removePageAnnotation(uri);

        if (Firebug.activateSameOrigin)
        {
            uri = this.convertToURIKey(currentURI, false);
            if (uri)
                this.annotationSvc.removePageAnnotation(uri);
        }

        if (FBTrace.DBG_ACTIVATION)
            FBTrace.sysout("Firebug.Activation.unwatchBrowser untagged "+uri.spec);
    },

    iterateAnnotations: function(fn)  // stops at the first fn(uri) that returns a true value
    {
        var annotations = this.annotationSvc.getAnnotations(this.annotationName);
        for (var uri in annotations)
        {
            var rc = fn(uri, annotations[uri]);
            if (rc)
                return rc;
        }
    },

    toggleAll: function(offOrOn)
    {
        if (FBTrace.DBG_ACTIVATION)
            FBTrace.sysout("Firebug.toggleAll("+offOrOn+") with allPagesActivation: " +
                Firebug.allPagesActivation);

        if (offOrOn == "on" || offOrOn == "off")
        {
            if (Firebug.allPagesActivation == offOrOn) // then we were armed
                Firebug.allPagesActivation = "none";
            else
                (offOrOn == "off") ? this.allOff() : this.allOn();

            // don't show Off if we are always on
            Firebug.chrome.disableOff(Firebug.allPagesActivation == "on");
        }
        else
        {
            Firebug.allPagesActivation = "none";
        }

        Firebug.setPref(Firebug.prefDomain, "allPagesActivation", Firebug.allPagesActivation);
        this.updateAllPagesActivation();
    },

    updateOption: function(name, value)
    {
        if (name = "allPagesActivation")
            this.updateAllPagesActivation();
    },

    updateAllPagesActivation: function()
    {
        $('menu_AllOff').setAttribute("checked", (Firebug.allPagesActivation=="off"));
        $('menu_AllOn').setAttribute("checked", (Firebug.allPagesActivation=="on"));
    },

    allOn: function()
    {
        Firebug.allPagesActivation = "on";  // In future we always create contexts,
        Firebug.toggleBar(true);  // and we turn on for the current page
    },

    allOff: function()
    {
        Firebug.allPagesActivation = "off";  // In future we don't create contexts,

        TabWatcher.iterateContexts(function turnOff(context)  // we close the current contexts,
        {
            if (!context.browser)
            {
                if (FBTrace.DBG_ERRORS)
                    FBTrace.sysout("context with no browser??!! "+context.getName());
                return;
            }
            if (context != FirebugContext)
                TabWatcher.unwatchBrowser(context.browser);
        });

        if (Firebug.isDetached())
        {
            // The current detached chrome object is Firebug.chrome.
            Firebug.chrome.close();  // should call unwatchBrowser
            detachCommand.setAttribute("checked", false);
            return;
        }

        if (Firebug.isInBrowser())
        {
            Firebug.chrome.hidePanel();
            Firebug.showBar(false);
        }

        Firebug.closeFirebug();
        this.clearAnnotations();  // and the past pages with contexts are forgotten.
    },
});

// ************************************************************************************************

Firebug.Activation.TabWatcherListener =
{
    watchBrowser: function(browser)
    {
        Firebug.Activation.watchBrowser(browser);
    },

    unwatchBrowser: function(browser, userCommands)
    {
        Firebug.Activation.unwatchBrowser(browser, userCommands);
    }
};

// ************************************************************************************************

Firebug.registerModule(Firebug.Activation);

// ************************************************************************************************
}});
<commit_msg>Use a getter for this.annotationSvc, fix watchBrowser<commit_after>/* See license.txt for terms of usage */

FBL.ns(function() { with (FBL) {

// ************************************************************************************************
// Constants

const Cc = Components.classes;
const Ci = Components.interfaces;

// ************************************************************************************************

/**
 * @class Implements Firebug activation logic.
 *
 * 1) Part of the logic is based on annotation service (see components/firebug-annotations.js)
 *    in order to remember whether Firebug is activated for given site or not.
 *    If there is "firebugged.showFirebug" annotation for a given site Firbug is activated.
 *    If there is "firebugged.closed" annotation for a given site Firbug is not activated.
 *
 * 2) Othe part is based on extensions.firebug.allPagesActivation option. This option
 *    can be set to the following values:
 *    none: The option isn't used (default value)
 *    on:   Firebug is activated for all URLs.
 *    off:  Firebug is never activated.
 *
 *    This logic has higher priority over the URL annotations.
 *    If "off" options is selected, all existing URL annotations are removed.
 */
Firebug.Activation = extend(Firebug.Module,
{
    dispatchName: "activation",

    initializeUI: function()  // called once
    {
        Firebug.Module.initializeUI.apply(this, arguments);

        TabWatcher.addListener(this.TabWatcherListener);

        // Update option menu item.
        this.updateAllPagesActivation();
    },

    getAnnotationService: function()
    {
        if(!this.annotationSvc)
        {
            // Create annotation service.
            this.annotationSvc = Cc["@joehewitt.com/firebug-annotation-service;1"]
                                    .getService(Ci.nsISupports).wrappedJSObject;
        }
        return this.annotationSvc;
    },

    shutdown: function()
    {
        Firebug.Module.shutdown.apply(this, arguments);

        TabWatcher.removeListener(this.TabWatcherListener);

        this.getAnnotationService().flush();
    },

    convertToURIKey: function(url, sameOrigin)  // process the URL to canonicalize it. Need not be reversible.
    {
        var uri = makeURI(normalizeURL(url));

        if (Firebug.filterSystemURLs && isSystemURL(url))
            return uri;

        if (url == "about:blank")  // avoid exceptions.
            return uri;

        if (uri && sameOrigin)
        {
            try
            {
                var prePath = uri.prePath; // returns the string before the path (such as "scheme://user:password@host:port").
                var shortURI = makeURI(prePath);
                if (!shortURI)
                    return uri;

                var host = shortURI.host;
                if (host)
                {
                    var crossDomain = host.split('.').slice(-2)
                    shortURI.host = crossDomain.join('.');
                    return shortURI
                }
            }
            catch (exc)
            {
                if (FBTrace.DBG_ERRORS)
                    FBTrace.sysout("activation.convertToURIKey returning full URI, activateSameOrigin FAILS for shortURI "+shortURI+" because: "+exc, exc);
                return uri;
            }
        }
        return uri;
    },

    shouldCreateContext: function(browser, url, userCommands)  // true if the Places annotation the URI "firebugged"
    {
        if (FBTrace.DBG_ACTIVATION)
            FBTrace.sysout("shouldCreateContext allPagesActivation " + Firebug.allPagesActivation);

        if (Firebug.allPagesActivation == "off")
            return false;

        if (Firebug.allPagesActivation == "on")
            return true;

        if (Firebug.filterSystemURLs && isSystemURL(url)) // if about:blank gets thru, 1483 fails
            return false;

        if (userCommands)
            return true;

        try
        {
            var uri = this.convertToURIKey(url, Firebug.activateSameOrigin);
            if (!uri)
                return false;

            var hasAnnotation = this.getAnnotationService().pageHasAnnotation(uri);

            if (FBTrace.DBG_ACTIVATION)
                FBTrace.sysout("shouldCreateContext hasAnnotation "+hasAnnotation +
                    " for "+uri.spec+" in "+browser.contentWindow.location +
                    " using activateSameOrigin: "+Firebug.activateSameOrigin);

            // Annotated so, return the value.
            if (hasAnnotation)
                return this.checkAnnotation(browser, uri);

            if (browser.FirebugLink) // then TabWatcher found a connection
            {
                var dst = browser.FirebugLink.dst;
                var dstURI = this.convertToURIKey(dst.spec, Firebug.activateSameOrigin);
                if (FBTrace.DBG_ACTIVATION)
                    FBTrace.sysout("shouldCreateContext found FirebugLink pointing to " +
                        dstURI.spec, browser.FirebugLink);

                if (dstURI && dstURI.equals(uri)) // and it matches us now
                {
                    var srcURI = this.convertToURIKey(browser.FirebugLink.src.spec, Firebug.activateSameOrigin);
                    if (srcURI)
                    {
                        if (FBTrace.DBG_ACTIVATION)
                            FBTrace.sysout("shouldCreateContext found FirebugLink pointing from " +
                                srcURI.spec, browser.FirebugLink);

                        if (srcURI.schemeIs("file") || (dstURI.host == srcURI.host) ) // and it's on the same domain
                        {
                            hasAnnotation = this.getAnnotationService().pageHasAnnotation(srcURI);
                            if (hasAnnotation) // and the source page was annotated.
                            {
                                var srcShow = this.checkAnnotation(browser, srcURI);
                                if (srcShow)  // and the source annotation said show it
                                    this.watchBrowser(browser);  // so we show dst as well.
                                return srcShow;
                            }
                        }
                    }
                }
                else
                {
                    if (FBTrace.DBG_ACTIVATION)
                        FBTrace.sysout("shouldCreateContext FirebugLink does not match "+uri.spec, browser.FirebugLink);
                }
            }
            else if (browser.contentWindow.opener)
            {
                var openerContext = TabWatcher.getContextByWindow(browser.contentWindow.opener);

                if (FBTrace.DBG_ACTIVATION)
                    FBTrace.sysout("shouldCreateContext opener found, has "+
                        (openerContext?"a ":"no ")+" context: "+
                        browser.contentWindow.opener.location);

                if (openerContext)
                    return true;  // popup windows of Firebugged windows are Firebugged
            }

            return false;   // don't createContext
        }
        catch (exc)
        {
            if (FBTrace.DBG_ERRORS)
                FBTrace.sysout("pageHasAnnoation FAILS for url: "+url+" which gave uri "+(uri?uri.spec:"null"), exc);
        }
    },

    checkAnnotation: function(browser, uri)
    {
        var annotation = this.getAnnotationService().getPageAnnotation(uri);

        if (FBTrace.DBG_ACTIVATION)
            FBTrace.sysout("shouldCreateContext read back annotation "+annotation+" for uri "+uri.spec);

        // then the user closed Firebug on this page last time
        if ((Firebug.allPagesActivation != "on") && (annotation.indexOf("closed") > 0))
            return false; // annotated as 'closed', don't create
        else
            return true;    // annotated, createContext
    },

    shouldShowContext: function(context)
    {
        return this.shouldCreateContext(context.browser, context.getWindowLocation().toString());
    },

    watchBrowser: function(browser)  // Firebug is opened in browser
    {
        var annotation = "firebugged.showFirebug";
        this.setPageAnnotation(browser.currentURI.spec, annotation);
    },

    unwatchBrowser: function(browser, userCommands)  // Firebug closes in browser
    {
    	var uri = browser.currentURI.spec;
        if (userCommands)  // then mark to not open virally.
            this.setPageAnnotation(uri, "firebugged.closed");
        else
            this.removePageAnnotation(uri); // unmark this URI
    },

    clearAnnotations: function()
    {
        this.getAnnotationService().clear();
    },

    setPageAnnotation: function(currentURI, annotation)
    {
        var uri = this.convertToURIKey(currentURI, Firebug.activateSameOrigin);
        if (uri)
            this.getAnnotationService().setPageAnnotation(uri, annotation);

        if (Firebug.activateSameOrigin)
        {
            uri = this.convertToURIKey(currentURI, false);
            if (uri)
                this.getAnnotationService().setPageAnnotation(uri, annotation);
        }
    },

    removePageAnnotation: function(currentURI)
    {
        var uri = this.convertToURIKey(currentURI, Firebug.activateSameOrigin);
        if (uri)
            this.getAnnotationService().removePageAnnotation(uri);

        if (Firebug.activateSameOrigin)
        {
            uri = this.convertToURIKey(currentURI, false);
            if (uri)
                this.getAnnotationService().removePageAnnotation(uri);
        }

        if (FBTrace.DBG_ACTIVATION)
            FBTrace.sysout("Firebug.Activation.unwatchBrowser untagged "+uri.spec);
    },

    iterateAnnotations: function(fn)  // stops at the first fn(uri) that returns a true value
    {
        var annotations = this.getAnnotationService().getAnnotations(this.annotationName);
        for (var uri in annotations)
        {
            var rc = fn(uri, annotations[uri]);
            if (rc)
                return rc;
        }
    },

    toggleAll: function(offOrOn)
    {
        if (FBTrace.DBG_ACTIVATION)
            FBTrace.sysout("Firebug.toggleAll("+offOrOn+") with allPagesActivation: " +
                Firebug.allPagesActivation);

        if (offOrOn == "on" || offOrOn == "off")
        {
            if (Firebug.allPagesActivation == offOrOn) // then we were armed
                Firebug.allPagesActivation = "none";
            else
                (offOrOn == "off") ? this.allOff() : this.allOn();

            // don't show Off if we are always on
            Firebug.chrome.disableOff(Firebug.allPagesActivation == "on");
        }
        else
        {
            Firebug.allPagesActivation = "none";
        }

        Firebug.setPref(Firebug.prefDomain, "allPagesActivation", Firebug.allPagesActivation);
        this.updateAllPagesActivation();
    },

    updateOption: function(name, value)
    {
        if (name = "allPagesActivation")
            this.updateAllPagesActivation();
    },

    updateAllPagesActivation: function()
    {
        $('menu_AllOff').setAttribute("checked", (Firebug.allPagesActivation=="off"));
        $('menu_AllOn').setAttribute("checked", (Firebug.allPagesActivation=="on"));
    },

    allOn: function()
    {
        Firebug.allPagesActivation = "on";  // In future we always create contexts,
        Firebug.toggleBar(true);  // and we turn on for the current page
    },

    allOff: function()
    {
        Firebug.allPagesActivation = "off";  // In future we don't create contexts,

        TabWatcher.iterateContexts(function turnOff(context)  // we close the current contexts,
        {
            if (!context.browser)
            {
                if (FBTrace.DBG_ERRORS)
                    FBTrace.sysout("context with no browser??!! "+context.getName());
                return;
            }
            if (context != FirebugContext)
                TabWatcher.unwatchBrowser(context.browser);
        });

        if (Firebug.isDetached())
        {
            // The current detached chrome object is Firebug.chrome.
            Firebug.chrome.close();  // should call unwatchBrowser
            detachCommand.setAttribute("checked", false);
            return;
        }

        if (Firebug.isInBrowser())
        {
            Firebug.chrome.hidePanel();
            Firebug.showBar(false);
        }

        Firebug.closeFirebug();
        this.clearAnnotations();  // and the past pages with contexts are forgotten.
    },
});

// ************************************************************************************************

Firebug.Activation.TabWatcherListener =
{
    watchBrowser: function(browser)
    {
        Firebug.Activation.watchBrowser(browser);
    },

    unwatchBrowser: function(browser, userCommands)
    {
        Firebug.Activation.unwatchBrowser(browser, userCommands);
    }
};

// ************************************************************************************************

Firebug.registerModule(Firebug.Activation);

// ************************************************************************************************
}});
<|endoftext|>


<commit_before>var passport       = require('passport')
  , GoogleStrategy = require('passport-google-oauth').OAuth2Strategy
  , config         = require('../../config')
  , User           = require('../../models').User
;

function register(app) {
  var secret      = process.env.GOOGLE_OAUTH_SECRET || config('auth.google.secret');
  var clientId    = process.env.GOOGLE_OAUTH_ID     || config('auth.google.id');
  var callbackUrl = process.env.GOOGLE_OAUTH_FQDN   || config('auth.google.fqdn');
  callbackUrl = callbackUrl + '/auth/google/callback'

  passport.use(
    new GoogleStrategy(
      {
        clientSecret:  secret
        , clientID:    clientId
        , callbackURL: callbackUrl
      }
      , function(accessToken, refreshToken, profile, done) {
        User.findOrCreateFromOAUTH(profile, done);
      }
    )
  );

  app.namespace('/auth', function(){
    app.namespace('/google', function(){
      app.get(
        '/'
        , passport.authenticate(
          'google'
          , {
            scope: [
              'https://www.googleapis.com/auth/userinfo.profile'
              , 'https://www.googleapis.com/auth/userinfo.email'
            ]
          }
        )
      );

      app.get(
        '/callback'
        , passport.authenticate(
          'google'
          , {
            failureRedirect: '/login'
          }
        ),
        function(req, res) {
          res.redirect('/');
        }
      );
    });
  });
};

module.exports = register;
<commit_msg>Test coverage pays off<commit_after>var passport       = require('passport')
  , GoogleStrategy = require('passport-google-oauth').OAuth2Strategy
  , config         = require('../../config')
  , User           = require('../../models').User
;

function register(app) {
  var secret      = process.env.GOOGLE_OAUTH_SECRET || config.auth.google.secret;
  var clientId    = process.env.GOOGLE_OAUTH_ID     || config.auth.google.id;
  var callbackUrl = process.env.GOOGLE_OAUTH_FQDN   || config.auth.google.fqdn;
  callbackUrl = callbackUrl + '/auth/google/callback'

  passport.use(
    new GoogleStrategy(
      {
        clientSecret:  secret
        , clientID:    clientId
        , callbackURL: callbackUrl
      }
      , function(accessToken, refreshToken, profile, done) {
        User.findOrCreateFromOAUTH(profile, done);
      }
    )
  );

  app.namespace('/auth', function(){
    app.namespace('/google', function(){
      app.get(
        '/'
        , passport.authenticate(
          'google'
          , {
            scope: [
              'https://www.googleapis.com/auth/userinfo.profile'
              , 'https://www.googleapis.com/auth/userinfo.email'
            ]
          }
        )
      );

      app.get(
        '/callback'
        , passport.authenticate(
          'google'
          , {
            failureRedirect: '/login'
          }
        ),
        function(req, res) {
          res.redirect('/');
        }
      );
    });
  });
};

module.exports = register;
<|endoftext|>


<commit_before>var helper = require("../../helper");
var Manager = require("../../../src/etl/fact-finishing-printing-sales-contract-etl-manager");
var instanceManager = null;
var should = require("should");
var sqlHelper = require("../../sql-helper");

before("#00. connect db", function (done) {
    Promise.all([helper, sqlHelper])
        .then((result) => {
            var db = result[0];
            var sql = result[1];
            db.getDb().then((db) => {
                instanceManager = new Manager(db, {
                    username: "unit-test"
                }, sql);
                done();
            })
                .catch((e) => {
                    done(e);
                })
        });
});

it("#01. should success when create etl fact-finishing-printing-sales-contract", function (done) {
    instanceManager.run()
        .then((a) => {
            console.log(a);
            done();
        })
        .catch((e) => {
            console.log(e);
            done(e);
        });
});

it("#02. should success when transforming data", function (done) {
    var data = [
        {
            uom: {
                unit: "yds"
            },
            orderQuantity: 1,
            material: {
                name: ""
            },
            materialConstruction: {
                name: ""
            },
            yarnMaterial: {
                name: ""
            },
            materialWidth: 1
        },
        {
            uom: {
                unit: "mtr"
            },
            orderQuantity: 1
        }
    ];
    instanceManager.transform(data)
        .then(() => {
            done();
        })
        .catch((e) => {
            done(e);
        });
});

it("#03. should error when load empty data", function (done) {
    instanceManager.load({})
        .then(id => {
            done("should error when create with empty data");
        })
        .catch(e => {
            try {
                done();
            }
            catch (ex) {
                done(ex);
            }
        });
});

it("#04. should error when insert empty data", function (done) {
    instanceManager.insertQuery(this.sql, "")
        .then((id) => {
            done("should error when create with empty data");
        })
        .catch((e) => {
            try {
                done();
            }
            catch (ex) {
                done(ex);
            }
        });
});<commit_msg>update unit test for finishing printing etl<commit_after>var helper = require("../../helper");
var Manager = require("../../../src/etl/fact-finishing-printing-sales-contract-etl-manager");
var instanceManager = null;
var should = require("should");
var sqlHelper = require("../../sql-helper");

before("#00. connect db", function (done) {
    Promise.all([helper, sqlHelper])
        .then((result) => {
            var db = result[0];
            var sql = result[1];
            db.getDb().then((db) => {
                instanceManager = new Manager(db, {
                    username: "unit-test"
                }, sql);
                done();
            })
                .catch((e) => {
                    done(e);
                })
        });
});

it("#01. should success when create etl fact-finishing-printing-sales-contract", function (done) {
    instanceManager.run()
        .then((a) => {
            console.log(a);
            done();
        })
        .catch((e) => {
            console.log(e);
            done(e);
        });
});

it("#02. should success when transforming data", function (done) {
    var data = [
        {
            uom: {
                unit: "yds"
            },
            orderQuantity: 1,
            material: {
                name: ""
            },
            materialConstruction: {
                name: ""
            },
            yarnMaterial: {
                name: ""
            },
            materialWidth: ""
        },
        {
            uom: {
                unit: "mtr"
            },
            orderQuantity: 1
        }
    ];
    instanceManager.transform(data)
        .then(() => {
            done();
        })
        .catch((e) => {
            done(e);
        });
});

it("#03. should error when load empty data", function (done) {
    instanceManager.load({})
        .then(id => {
            done("should error when create with empty data");
        })
        .catch(e => {
            try {
                done();
            }
            catch (ex) {
                done(ex);
            }
        });
});

it("#04. should error when insert empty data", function (done) {
    instanceManager.insertQuery(this.sql, "")
        .then((id) => {
            done("should error when create with empty data");
        })
        .catch((e) => {
            try {
                done();
            }
            catch (ex) {
                done(ex);
            }
        });
});<|endoftext|>


<commit_before>/* exported snapping */
const snapping = (function () { // eslint-disable-line no-unused-vars
  let exports = {};

  let xSnaps = [];
  let ySnaps = [];

  // Calculate x/ySnaps:
  exports.init = function () {
    var xFound = {};
    var yFound = {};
    var scrollX = window.scrollX;
    var scrollY = window.scrollY;
    var allTags = document.getElementsByTagName("*");
    var allTagsLength = allTags.length;

    for (var i=0; i<allTagsLength; i++) {
      var tag = allTags[i];
      var rect = tag.getBoundingClientRect();
      // FIXME: some objects aren't visible, and should be excluded
      var top = Math.floor(rect.top + scrollY);
      var bottom = Math.floor(rect.bottom + scrollY);
      var left = Math.floor(rect.left + scrollX);
      var right = Math.floor(rect.right + scrollX);
      if (! yFound[top]) {
        ySnaps.push(top);
        yFound[top] = true;
      }
      if (! yFound[bottom]) {
        ySnaps.push(bottom);
        yFound[bottom] = true;
      }
      if (! xFound[left]) {
        xSnaps.push(left);
        xFound[left] = true;
      }
      if (! xFound[right]) {
        xSnaps.push(right);
        xFound[right] = true;
      }
    }
    // FIXME: should probably make sure all page edges are in the list
    xSnaps.sort(function (a, b) {
      if (a > b) {
        return 1;
      }
      return -1;
    });
    ySnaps.sort(function (a, b) {
      if (a > b) {
        return 1;
      }
      return -1;
    });
  };

  var _lastClosestX = {};
  exports.guessX = function (x) {
    return _guess(x, findClosest(x, xSnaps, xSnaps.length, _lastClosestX));
  };

  var _lastClosestY = {};
  exports.guessY = function (y) {
    return _guess(y, findClosest(y, ySnaps, ySnaps.length, _lastClosestY));
  };

  var MIN_SNAP = 15;

  function _guess(pos, range) {
    if (pos-range[0] < range[1]-pos &&
        pos-range[0] < MIN_SNAP) {
      return range[0];
    } else if (range[1]-pos < MIN_SNAP) {
      return range[1];
    }
    return pos;
  }

  function findClosest(pos, snaps, snapsLength, memo) {
    if (memo.last && pos >= memo.last[0] && pos <= memo.last[1]) {
      return memo.last;
    }
    if (pos > snaps[snapsLength-1] || pos < snaps[0]) {
      console.warn("Got out of range position for snapping:", pos, snaps[0], snaps[snapsLength-1]);
      return pos;
    }
    var index = Math.floor(snapsLength/2);
    var less = 0;
    var more = snapsLength;
    while (true) { // eslint-disable-line no-constant-condition
      if (snaps[index] <= pos && snaps[index+1] >= pos) {
        break;
      }
      if (snaps[index] > pos) {
        more = index;
      } else {
        less = index;
      }
      index = Math.floor((less + more) / 2);
    }
    var result = [snaps[index], snaps[index+1]];
    //memo.last = result;
    return result;
  }

  return exports;
})();
<commit_msg>Fixing a FIXME (#1229): eliminate non-visible elements from snapping coordinates<commit_after>/* exported snapping */
const snapping = (function () { // eslint-disable-line no-unused-vars
  let exports = {};

  let xSnaps = [];
  let ySnaps = [];

  // Calculate x/ySnaps:
  exports.init = function () {
    var xFound = {};
    var yFound = {};
    var scrollX = window.scrollX;
    var scrollY = window.scrollY;
    var allTags = document.getElementsByTagName("*");
    var allTagsLength = allTags.length;

    for (var i=0; i<allTagsLength; i++) {
      var tag = allTags[i];
      var rect = tag.getBoundingClientRect();
      if (rect.height === 0 && rect.width === 0) {
        // Probably not a visible element
        continue;
      }
      var top = Math.floor(rect.top + scrollY);
      var bottom = Math.floor(rect.bottom + scrollY);
      var left = Math.floor(rect.left + scrollX);
      var right = Math.floor(rect.right + scrollX);
      if (! yFound[top]) {
        ySnaps.push(top);
        yFound[top] = true;
      }
      if (! yFound[bottom]) {
        ySnaps.push(bottom);
        yFound[bottom] = true;
      }
      if (! xFound[left]) {
        xSnaps.push(left);
        xFound[left] = true;
      }
      if (! xFound[right]) {
        xSnaps.push(right);
        xFound[right] = true;
      }
    }
    // FIXME: should probably make sure all page edges are in the list
    xSnaps.sort(function (a, b) {
      if (a > b) {
        return 1;
      }
      return -1;
    });
    ySnaps.sort(function (a, b) {
      if (a > b) {
        return 1;
      }
      return -1;
    });
  };

  var _lastClosestX = {};
  exports.guessX = function (x) {
    return _guess(x, findClosest(x, xSnaps, xSnaps.length, _lastClosestX));
  };

  var _lastClosestY = {};
  exports.guessY = function (y) {
    return _guess(y, findClosest(y, ySnaps, ySnaps.length, _lastClosestY));
  };

  var MIN_SNAP = 15;

  function _guess(pos, range) {
    if (pos-range[0] < range[1]-pos &&
        pos-range[0] < MIN_SNAP) {
      return range[0];
    } else if (range[1]-pos < MIN_SNAP) {
      return range[1];
    }
    return pos;
  }

  function findClosest(pos, snaps, snapsLength, memo) {
    if (memo.last && pos >= memo.last[0] && pos <= memo.last[1]) {
      return memo.last;
    }
    if (pos > snaps[snapsLength-1] || pos < snaps[0]) {
      console.warn("Got out of range position for snapping:", pos, snaps[0], snaps[snapsLength-1]);
      return pos;
    }
    var index = Math.floor(snapsLength/2);
    var less = 0;
    var more = snapsLength;
    while (true) { // eslint-disable-line no-constant-condition
      if (snaps[index] <= pos && snaps[index+1] >= pos) {
        break;
      }
      if (snaps[index] > pos) {
        more = index;
      } else {
        less = index;
      }
      index = Math.floor((less + more) / 2);
    }
    var result = [snaps[index], snaps[index+1]];
    //memo.last = result;
    return result;
  }

  return exports;
})();
<|endoftext|>


<commit_before><commit_msg>updated AddTrial.js<commit_after><|endoftext|>