<commit_before>/* jshint maxlen:false */
define([
    'dojo/has',
    'dojo/request',
    'dojo/_base/lang',

    'esri/config',
    'esri/geometry/Extent',
    'esri/symbols/SimpleFillSymbol',
    'esri/symbols/SimpleLineSymbol',
    'esri/symbols/SimpleMarkerSymbol',

    'dojo/domReady!'
], function (
    has,
    request,
    lang,

    esriConfig,
    Extent,
    SimpleFillSymbol,
    SimpleLineSymbol,
    SimpleMarkerSymbol
) {
    // force api to use CORS on mapserv thus removing the test request on app load
    // e.g. http://mapserv.utah.gov/ArcGIS/rest/info?f=json
    esriConfig.defaults.io.corsEnabledServers.push('mapserv.utah.gov');
    esriConfig.defaults.io.corsEnabledServers.push('basemaps.utah.gov');
    esriConfig.defaults.io.corsEnabledServers.push('wrimaps.at.utah.gov');
    esriConfig.defaults.io.corsEnabledServers.push('wrimaps.utah.gov');
    esriConfig.defaults.io.corsEnabledServers.push('maps.ffsl.utah.gov');
    esriConfig.defaults.map.zoomSymbol.outline.color = [18, 192, 236, 255];

    var gisServerBaseUrl;
    var apiEndpoint;
    var serviceUrlTemplate = '/arcgis/rest/services/WRI/{name}/{type}Server';
    var googleImageryUrl = 'https://discover.agrc.utah.gov/login/path/delete-prefix-stretch-giant/';
    var plssUrl = 'https://wrimaps.at.utah.gov/arcgis/rest/services/UtahPLSS/MapServer';

    if (has('agrc-build') === 'prod') {
        gisServerBaseUrl = 'https://wrimaps.utah.gov';
        apiEndpoint = '';
        plssUrl = 'https://wrimaps.utah.gov/arcgis/rest/services/UtahPLSS/MapServer';
    } else if (has('agrc-build') === 'stage') {
        gisServerBaseUrl = 'https://wrimaps.at.utah.gov';
        apiEndpoint = '/__WRI_CONFIGURATION__';
        serviceUrlTemplate = '/arcgis/rest/services/__WRI_CONFIGURATION__/{name}/{type}Server';
    } else {
        gisServerBaseUrl = 'http://' + window.location.host;
        apiEndpoint = '/wri';
        googleImageryUrl = 'https://discover.agrc.utah.gov/login/path/alabama-anvil-picnic-sunset/';
    }
    esriConfig.defaults.io.corsEnabledServers.push(gisServerBaseUrl);
    esriConfig.defaults.io.corsEnabledServers.push('maps.dnr.utah.gov');
    esriConfig.defaults.io.corsEnabledServers.push('dwrapps.utah.gov');
    var selectionColor = [255, 220, 0];

    var config = {
        // app: app.App
        //      global reference to App
        app: null,

        // version.: String
        //      The version number.
        version: '0.12.2',

        // scaleTrigger: Number
        //      the basemap level to toggle centroids
        scaleTrigger: 13,

        // popupDelay: Number
        //      The delay (in milliseconds) that popups delay before showing
        popupDelay: 250,

        // switchToGoogleScale: Number
        //      The scale at which the base map switches to the google imagery
        switchToGoogleScale: 4000,

        // centerAndZoomLevel: Number
        //      The cache level to zoom to when zooming to a point
        centerAndZoomLevel: 18,

        // herbicideAction: String
        //      the name of the herbicide action
        herbicideActionName: 'HERBICIDE APPLICATION',

        // defaultExtent: Extent
        //      The default extent of the map. (The state of utah)
        defaultExtent: new Extent({
            xmax: -12010849.397533866,
            xmin: -12898741.918094235,
            ymax: 5224652.298632992,
            ymin: 4422369.249751998,
            spatialReference: {
                wkid: 3857
            }
        }),

        urls: {
            featuresService: gisServerBaseUrl + lang.replace(serviceUrlTemplate, { name: 'Features', type: 'Map' }),
            centroidService: gisServerBaseUrl + lang.replace(serviceUrlTemplate, { name: 'Projects', type: 'Map' }) + '/0',
            reference: gisServerBaseUrl + lang.replace(serviceUrlTemplate, { name: 'Reference', type: 'Map' }),
            api: gisServerBaseUrl + apiEndpoint + '/api',
            plss: plssUrl,
            fireRiskIndex: 'https://maps.ffsl.utah.gov/arcgis/rest/services/Fire/FireRiskIndex/MapServer',
            rangeTrendApp: 'https://dwrapps.utah.gov/rangetrend/rtstart?SiteID=${GlobalID}',
            esriImagery: 'https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer',
            esriLabels: 'https://services.arcgisonline.com/ArcGIS/rest/services/Reference/World_Boundaries_and_Places/MapServer',
            esriTransLabels: 'https://services.arcgisonline.com/ArcGIS/rest/services/Reference/World_Transportation/MapServer',
            googleImagery: googleImageryUrl,
            print: gisServerBaseUrl + lang.replace(serviceUrlTemplate, { name: 'Print', type: 'GP' }) + '/Export%20Web%20Map',
            upload: gisServerBaseUrl + lang.replace(serviceUrlTemplate, { name: 'Toolbox', type: 'GP'}) + '/uploads/upload',
            zipToGraphics: gisServerBaseUrl + lang.replace(serviceUrlTemplate, { name: 'Toolbox', type: 'GP'}) + '/ZipToGraphics',
            download: gisServerBaseUrl + lang.replace(serviceUrlTemplate, { name: 'ToolboxAsync', type: 'GP'}) + '/Download'
        },

        defaultXhrHeaders: {
            'Accept': 'application/json',
            'X-Requested-With': null
        },

        layerIndices: {
            point: 0,
            line: 1,
            poly: 2
        },

        fieldNames: {
            Project_ID: 'Project_ID',
            Status: 'Status',
            TypeCode: 'TypeCode',
            Title: 'Title',
            Name: 'Name',
            DWR_REGION: 'DWR_REGION',
            FO_NAME: 'FO_NAME',
            LABEL_FEDERAL: 'LABEL_FEDERAL',
            FeatureID: 'FeatureID',

            // range trend SiteInfo
            GlobalID: 'GlobalID',
            STUDY_NAME: 'STUDY_NAME'
        },

        featureTypesInTables: {
            1: 'POLY',
            2: 'POLY',
            3: 'POLY',
            4: 'POLY',
            5: 'POINT',
            6: 'POINT',
            7: 'POINT',
            8: 'POINT',
            9: 'POINT',
            10: 'LINE',
            11: 'LINE',
            12: 'LINE',
            13: 'POLY'
        },

        commentsFieldCategories: [
            'Other point feature',
            'Water control structure',
            'Trough'
        ],

        terrestrialAquaticCategories: [
            'Terrestrial Treatment Area',
            'Aquatic/Riparian Treatment Area'
        ],

        topics: {
            mapScaleChanged: 'wri/mapScaleChanged',
            projectIdsChanged: 'wri/projectIdsChanged',
            featureSelected: 'wri/featureSelected',
            selectionCleared: 'wri/selectionCleared',
            opacityChanged: 'wri/opacityChanged',
            filterQueryChanged: 'wri/filterQueryChanged',
            map: {
                extentChanged: 'wri/extentChanged',
                toggleCentroids: 'wri/toggle',
                setExtent: 'wri/setExtent',
                setMap: 'wri/setMap',
                rubberBandZoom: 'wri/rubberbanding',
                toggleAdjacent: 'wri/toggleAdjacent',
                featureSelected: 'wri/mapFeatureSelected',
                toggleWriProjects: 'wri/toggleWriProjects'
            },
            layer: {
                add: 'wri/add'
            },
            centroidController: {
                updateVisibility: 'wri/thisFeelsBad'
            },
            toggleReferenceLayer: 'wri/toggleReferenceLayer',
            toggleReferenceLayerLabels: 'wri/toggleReferenceLayerLabels',
            feature: {
                createFeature: 'wri/feature/createFeature',
                startDrawing: 'wri/feature/startDrawing',
                startEditing: 'wri/feature/startEditing',
                drawingComplete: 'wri/feature/drawingComplete',
                cutFeatures: 'wri/feature/cutFeatures',
                selectedForEditing: 'wri/feature/selectedForEditing',
                drawEditComplete: 'wri/feature/drawEditComplete',
                cancelDrawing: 'wri/feature/cancelDrawing',
                removeEditingGraphic: 'wri/feature/removeEditingGraphic',
                finishEditingCreating: 'wri/feature/finishEditingCreating'
            },
            toast: 'wri/toast',
            showProjectLoader: 'wri/showProjectLoader',
            hideProjectLoader: 'wri/hideProjectLoader'
        },

        symbols: {
            selected: {
                point: new SimpleMarkerSymbol({
                    type: 'esriSMS',
                    style: 'esriSMSCircle',
                    color: selectionColor,
                    size: 10,
                    angle: 0,
                    xoffset: 0,
                    yoffset: 0,
                    outline: {
                        color: [0, 0, 0, 255],
                        width: 1
                    }
                }),
                line: new SimpleLineSymbol({
                    type: 'esriSLS',
                    style: 'esriSLSSolid',
                    color: selectionColor,
                    width: 4
                }),
                poly: new SimpleFillSymbol({
                    type: 'esriSFS',
                    style: 'esriSFSSolid',
                    color: selectionColor,
                    outline: {
                        type: 'esriSLS',
                        style: 'esriSLSSolid',
                        color: [110, 110, 110, 255],
                        width: 0.5
                    }
                })
            },
            selectedPointForEditing: new SimpleMarkerSymbol({
                type: 'esriSMS',
                style: 'esriSMSCircle',
                color: [128, 128, 128, 128],
                size: 10,
                angle: 0,
                xoffset: 0,
                yoffset: 0,
                outline: {
                    color: [0, 0, 0, 255],
                    width: 1
                }
            })
        },

        referenceLayerOpacity: 0.75
    };
    var flds = config.fieldNames;
    config.supportLayers = [{
        name: 'Land Ownership',
        reference: true,
        url: config.urls.reference,
        layerIndex: 4,
        type: 'dynamic',
        legend: true
    }, {
        name: 'UWRI Regions',
        reference: true,
        search: true,
        url: config.urls.reference,
        layerIndex: 6,
        labelsIndex: 9,
        type: 'dynamic',
        searchFields: [flds.DWR_REGION],
        displayField: flds.DWR_REGION,
        highlightSymbol: config.symbols.selected.poly
    }, {
        name: 'UWRI Focus Areas',
        reference: true,
        url: config.urls.reference,
        layerIndex: 0,
        type: 'dynamic',
        legend: true
    }, {
        name: 'BLM Districts',
        reference: true,
        search: true,
        url: config.urls.reference,
        layerIndex: 1,
        labelsIndex: 10,
        type: 'dynamic',
        searchFields: [flds.FO_NAME],
        displayField: flds.FO_NAME,
        highlightSymbol: config.symbols.selected.poly,
        legend: true
    }, {
        name: 'Forest Service',
        reference: true,
        search: true,
        url: config.urls.reference,
        layerIndex: 2,
        labelsIndex: 11,
        type: 'dynamic',
        searchFields: [flds.LABEL_FEDERAL],
        displayField: flds.LABEL_FEDERAL,
        highlightSymbol: config.symbols.selected.poly
    }, {
        name: 'Sage Grouse Areas',
        reference: true,
        url: config.urls.reference,
        layerIndex: 5,
        labelsIndex: 5,
        type: 'dynamic'
    }, {
        name: 'PLSS Sections',
        reference: true,
        url: config.urls.plss,
        type: 'cached',
        minScale: 1000000
    }, {
        name: 'HUCs',
        reference: true,
        url: config.urls.reference,
        layerIndex: 3,
        labelsIndex: 13,
        type: 'dynamic'
    }, {
        name: 'Range Trend Sites',
        reference: true,
        url: config.urls.reference + '/8',
        type: 'range'
    }, {
        name: 'Fire Risk Index',
        reference: true,
        url: config.urls.fireRiskIndex,
        type: 'cached',
        legend: true,
        layerIndex: 0
    }, {
        name: 'NHD Streams',
        reference: true,
        url: config.urls.reference,
        layerIndex: 15,
        type: 'dynamic',
        minScale: 80000
    }, {
        name: 'WRI Project Name',
        search: true,
        url: config.urls.centroidService,
        searchFields: [flds.Title],
        highlightSymbol: config.symbols.selected.point
    },  {
        name: 'WRI Project ID',
        search: true,
        minCharacters: 1,
        url: config.urls.centroidService,
        searchFields: [flds.Project_ID],
        suggestionTemplate: '${' + flds.Project_ID + '}',
        highlightSymbol: config.symbols.selected.point
    }, {
        name: 'SGID Places',
        search: true,
        url: config.urls.reference,
        layerIndex: 7,
        searchFields: [flds.Name],
        displayField: flds.Name,
        highlightSymbol: config.symbols.selected.poly
    }];

    request(require.baseUrl + 'jsonconfig/config.json', {
        handleAs: 'json',
        sync: true
    }).then(function (response) {
        config.domains = response;
    }, function () {
        throw 'Error getting config.json!';
    });

    return config;
});
<commit_msg>add _WRI_BASEURL__ token for mapping dns<commit_after>/* jshint maxlen:false */
define([
    'dojo/has',
    'dojo/request',
    'dojo/_base/lang',

    'esri/config',
    'esri/geometry/Extent',
    'esri/symbols/SimpleFillSymbol',
    'esri/symbols/SimpleLineSymbol',
    'esri/symbols/SimpleMarkerSymbol',

    'dojo/domReady!'
], function (
    has,
    request,
    lang,

    esriConfig,
    Extent,
    SimpleFillSymbol,
    SimpleLineSymbol,
    SimpleMarkerSymbol
) {
    // force api to use CORS on mapserv thus removing the test request on app load
    // e.g. http://mapserv.utah.gov/ArcGIS/rest/info?f=json
    esriConfig.defaults.io.corsEnabledServers.push('mapserv.utah.gov');
    esriConfig.defaults.io.corsEnabledServers.push('basemaps.utah.gov');
    esriConfig.defaults.io.corsEnabledServers.push('wrimaps.at.utah.gov');
    esriConfig.defaults.io.corsEnabledServers.push('wrimaps.utah.gov');
    esriConfig.defaults.io.corsEnabledServers.push('maps.ffsl.utah.gov');
    esriConfig.defaults.io.corsEnabledServers.push('maps.dnr.utah.gov');
    esriConfig.defaults.io.corsEnabledServers.push('dwrapps.utah.gov');
    esriConfig.defaults.map.zoomSymbol.outline.color = [18, 192, 236, 255];

    var gisServerBaseUrl;
    var apiEndpoint;
    var serviceUrlTemplate = '/arcgis/rest/services/WRI/{name}/{type}Server';
    var googleImageryUrl = 'https://discover.agrc.utah.gov/login/path/delete-prefix-stretch-giant/';
    var plssUrl = 'https://__WRI_BASEURL__.utah.gov/arcgis/rest/services/UtahPLSS/MapServer';

    if (has('agrc-build') === 'prod') {
        gisServerBaseUrl = 'https://__WRI_BASEURL__.utah.gov';
        apiEndpoint = '/__WRI_CONFIGURATION__';
        serviceUrlTemplate = '/arcgis/rest/services/__WRI_CONFIGURATION__/{name}/{type}Server';
    } else {
        gisServerBaseUrl = 'http://' + window.location.host;
        apiEndpoint = '/wri';
        googleImageryUrl = 'https://discover.agrc.utah.gov/login/path/alabama-anvil-picnic-sunset/';
    }
    esriConfig.defaults.io.corsEnabledServers.push(gisServerBaseUrl);
    var selectionColor = [255, 220, 0];

    var config = {
        // app: app.App
        //      global reference to App
        app: null,

        // version.: String
        //      The version number.
        version: '0.12.2',

        // scaleTrigger: Number
        //      the basemap level to toggle centroids
        scaleTrigger: 13,

        // popupDelay: Number
        //      The delay (in milliseconds) that popups delay before showing
        popupDelay: 250,

        // switchToGoogleScale: Number
        //      The scale at which the base map switches to the google imagery
        switchToGoogleScale: 4000,

        // centerAndZoomLevel: Number
        //      The cache level to zoom to when zooming to a point
        centerAndZoomLevel: 18,

        // herbicideAction: String
        //      the name of the herbicide action
        herbicideActionName: 'HERBICIDE APPLICATION',

        // defaultExtent: Extent
        //      The default extent of the map. (The state of utah)
        defaultExtent: new Extent({
            xmax: -12010849.397533866,
            xmin: -12898741.918094235,
            ymax: 5224652.298632992,
            ymin: 4422369.249751998,
            spatialReference: {
                wkid: 3857
            }
        }),

        urls: {
            featuresService: gisServerBaseUrl + lang.replace(serviceUrlTemplate, { name: 'Features', type: 'Map' }),
            centroidService: gisServerBaseUrl + lang.replace(serviceUrlTemplate, { name: 'Projects', type: 'Map' }) + '/0',
            reference: gisServerBaseUrl + lang.replace(serviceUrlTemplate, { name: 'Reference', type: 'Map' }),
            api: gisServerBaseUrl + apiEndpoint + '/api',
            plss: plssUrl,
            fireRiskIndex: 'https://maps.ffsl.utah.gov/arcgis/rest/services/Fire/FireRiskIndex/MapServer',
            rangeTrendApp: 'https://dwrapps.utah.gov/rangetrend/rtstart?SiteID=${GlobalID}',
            esriImagery: 'https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer',
            esriLabels: 'https://services.arcgisonline.com/ArcGIS/rest/services/Reference/World_Boundaries_and_Places/MapServer',
            esriTransLabels: 'https://services.arcgisonline.com/ArcGIS/rest/services/Reference/World_Transportation/MapServer',
            googleImagery: googleImageryUrl,
            print: gisServerBaseUrl + lang.replace(serviceUrlTemplate, { name: 'Print', type: 'GP' }) + '/Export%20Web%20Map',
            upload: gisServerBaseUrl + lang.replace(serviceUrlTemplate, { name: 'Toolbox', type: 'GP'}) + '/uploads/upload',
            zipToGraphics: gisServerBaseUrl + lang.replace(serviceUrlTemplate, { name: 'Toolbox', type: 'GP'}) + '/ZipToGraphics',
            download: gisServerBaseUrl + lang.replace(serviceUrlTemplate, { name: 'ToolboxAsync', type: 'GP'}) + '/Download'
        },

        defaultXhrHeaders: {
            'Accept': 'application/json',
            'X-Requested-With': null
        },

        layerIndices: {
            point: 0,
            line: 1,
            poly: 2
        },

        fieldNames: {
            Project_ID: 'Project_ID',
            Status: 'Status',
            TypeCode: 'TypeCode',
            Title: 'Title',
            Name: 'Name',
            DWR_REGION: 'DWR_REGION',
            FO_NAME: 'FO_NAME',
            LABEL_FEDERAL: 'LABEL_FEDERAL',
            FeatureID: 'FeatureID',

            // range trend SiteInfo
            GlobalID: 'GlobalID',
            STUDY_NAME: 'STUDY_NAME'
        },

        featureTypesInTables: {
            1: 'POLY',
            2: 'POLY',
            3: 'POLY',
            4: 'POLY',
            5: 'POINT',
            6: 'POINT',
            7: 'POINT',
            8: 'POINT',
            9: 'POINT',
            10: 'LINE',
            11: 'LINE',
            12: 'LINE',
            13: 'POLY'
        },

        commentsFieldCategories: [
            'Other point feature',
            'Water control structure',
            'Trough'
        ],

        terrestrialAquaticCategories: [
            'Terrestrial Treatment Area',
            'Aquatic/Riparian Treatment Area'
        ],

        topics: {
            mapScaleChanged: 'wri/mapScaleChanged',
            projectIdsChanged: 'wri/projectIdsChanged',
            featureSelected: 'wri/featureSelected',
            selectionCleared: 'wri/selectionCleared',
            opacityChanged: 'wri/opacityChanged',
            filterQueryChanged: 'wri/filterQueryChanged',
            map: {
                extentChanged: 'wri/extentChanged',
                toggleCentroids: 'wri/toggle',
                setExtent: 'wri/setExtent',
                setMap: 'wri/setMap',
                rubberBandZoom: 'wri/rubberbanding',
                toggleAdjacent: 'wri/toggleAdjacent',
                featureSelected: 'wri/mapFeatureSelected',
                toggleWriProjects: 'wri/toggleWriProjects'
            },
            layer: {
                add: 'wri/add'
            },
            centroidController: {
                updateVisibility: 'wri/thisFeelsBad'
            },
            toggleReferenceLayer: 'wri/toggleReferenceLayer',
            toggleReferenceLayerLabels: 'wri/toggleReferenceLayerLabels',
            feature: {
                createFeature: 'wri/feature/createFeature',
                startDrawing: 'wri/feature/startDrawing',
                startEditing: 'wri/feature/startEditing',
                drawingComplete: 'wri/feature/drawingComplete',
                cutFeatures: 'wri/feature/cutFeatures',
                selectedForEditing: 'wri/feature/selectedForEditing',
                drawEditComplete: 'wri/feature/drawEditComplete',
                cancelDrawing: 'wri/feature/cancelDrawing',
                removeEditingGraphic: 'wri/feature/removeEditingGraphic',
                finishEditingCreating: 'wri/feature/finishEditingCreating'
            },
            toast: 'wri/toast',
            showProjectLoader: 'wri/showProjectLoader',
            hideProjectLoader: 'wri/hideProjectLoader'
        },

        symbols: {
            selected: {
                point: new SimpleMarkerSymbol({
                    type: 'esriSMS',
                    style: 'esriSMSCircle',
                    color: selectionColor,
                    size: 10,
                    angle: 0,
                    xoffset: 0,
                    yoffset: 0,
                    outline: {
                        color: [0, 0, 0, 255],
                        width: 1
                    }
                }),
                line: new SimpleLineSymbol({
                    type: 'esriSLS',
                    style: 'esriSLSSolid',
                    color: selectionColor,
                    width: 4
                }),
                poly: new SimpleFillSymbol({
                    type: 'esriSFS',
                    style: 'esriSFSSolid',
                    color: selectionColor,
                    outline: {
                        type: 'esriSLS',
                        style: 'esriSLSSolid',
                        color: [110, 110, 110, 255],
                        width: 0.5
                    }
                })
            },
            selectedPointForEditing: new SimpleMarkerSymbol({
                type: 'esriSMS',
                style: 'esriSMSCircle',
                color: [128, 128, 128, 128],
                size: 10,
                angle: 0,
                xoffset: 0,
                yoffset: 0,
                outline: {
                    color: [0, 0, 0, 255],
                    width: 1
                }
            })
        },

        referenceLayerOpacity: 0.75
    };
    var flds = config.fieldNames;
    config.supportLayers = [{
        name: 'Land Ownership',
        reference: true,
        url: config.urls.reference,
        layerIndex: 4,
        type: 'dynamic',
        legend: true
    }, {
        name: 'UWRI Regions',
        reference: true,
        search: true,
        url: config.urls.reference,
        layerIndex: 6,
        labelsIndex: 9,
        type: 'dynamic',
        searchFields: [flds.DWR_REGION],
        displayField: flds.DWR_REGION,
        highlightSymbol: config.symbols.selected.poly
    }, {
        name: 'UWRI Focus Areas',
        reference: true,
        url: config.urls.reference,
        layerIndex: 0,
        type: 'dynamic',
        legend: true
    }, {
        name: 'BLM Districts',
        reference: true,
        search: true,
        url: config.urls.reference,
        layerIndex: 1,
        labelsIndex: 10,
        type: 'dynamic',
        searchFields: [flds.FO_NAME],
        displayField: flds.FO_NAME,
        highlightSymbol: config.symbols.selected.poly,
        legend: true
    }, {
        name: 'Forest Service',
        reference: true,
        search: true,
        url: config.urls.reference,
        layerIndex: 2,
        labelsIndex: 11,
        type: 'dynamic',
        searchFields: [flds.LABEL_FEDERAL],
        displayField: flds.LABEL_FEDERAL,
        highlightSymbol: config.symbols.selected.poly
    }, {
        name: 'Sage Grouse Areas',
        reference: true,
        url: config.urls.reference,
        layerIndex: 5,
        labelsIndex: 5,
        type: 'dynamic'
    }, {
        name: 'PLSS Sections',
        reference: true,
        url: config.urls.plss,
        type: 'cached',
        minScale: 1000000
    }, {
        name: 'HUCs',
        reference: true,
        url: config.urls.reference,
        layerIndex: 3,
        labelsIndex: 13,
        type: 'dynamic'
    }, {
        name: 'Range Trend Sites',
        reference: true,
        url: config.urls.reference + '/8',
        type: 'range'
    }, {
        name: 'Fire Risk Index',
        reference: true,
        url: config.urls.fireRiskIndex,
        type: 'cached',
        legend: true,
        layerIndex: 0
    }, {
        name: 'NHD Streams',
        reference: true,
        url: config.urls.reference,
        layerIndex: 15,
        type: 'dynamic',
        minScale: 80000
    }, {
        name: 'WRI Project Name',
        search: true,
        url: config.urls.centroidService,
        searchFields: [flds.Title],
        highlightSymbol: config.symbols.selected.point
    },  {
        name: 'WRI Project ID',
        search: true,
        minCharacters: 1,
        url: config.urls.centroidService,
        searchFields: [flds.Project_ID],
        suggestionTemplate: '${' + flds.Project_ID + '}',
        highlightSymbol: config.symbols.selected.point
    }, {
        name: 'SGID Places',
        search: true,
        url: config.urls.reference,
        layerIndex: 7,
        searchFields: [flds.Name],
        displayField: flds.Name,
        highlightSymbol: config.symbols.selected.poly
    }];

    request(require.baseUrl + 'jsonconfig/config.json', {
        handleAs: 'json',
        sync: true
    }).then(function (response) {
        config.domains = response;
    }, function () {
        throw 'Error getting config.json!';
    });

    return config;
});
<|endoftext|>


<commit_before>/* jshint maxlen:false */
define([
    'dojo/_base/Color',
    'dojo/_base/array',
    'dojo/_base/lang',
    'dojo/request',
    'dojo/Deferred',
    'dojo/has',

    'esri/SpatialReference',
    'esri/symbols/SimpleFillSymbol',
    'esri/symbols/SimpleLineSymbol',
    'esri/symbols/SimpleMarkerSymbol',
    'esri/symbols/CartographicLineSymbol'
], function (
    Color,
    array,
    lang,
    request,
    Deferred,
    has,

    SpatialReference,
    SimpleFillSymbol,
    SimpleLineSymbol,
    SimpleMarkerSymbol,
    CartographicLineSymbol
    ) {

    var zoomColor = new Color([255, 255, 0]);
    var zoomFillColor = new Color(zoomColor.toRgb().concat([0.15]));
    var selectionColor = new Color([240, 18, 190]);
    var selectionFillColor = new Color(selectionColor.toRgb().concat([0.15]));
    window.AGRC = {
        // app: app.App
        //      global reference to App
        app: null,

        // appName: String
        //      name of the app used in permissionsproxy
        appName: 'deq',

        // version: String
        //      The version number.
        version: '0.7.0',

        // popupDelay: Number
        //      The delay (in milliseconds) before a popup is shown on hover.
        popupDelay: 250,

        gridIdentifyHeight: 237,

        // topics: Object
        //      The topic strings used in this app
        topics: {
            appMapReferenceLayerToggle: {
                addLayer: 'app/map/ReferenceLayerToggle.addLayer',
                toggleLayer: 'app/map/ReferenceLayerToggle.toggleLayer'
            },
            appQueryLayer: {
                addLayer: 'app/QueryLayer.addLayer',
                removeLayer: 'app/QueryLayer.removeLayer'
            },
            appMapMapController: {
                mapZoom: 'app/map/MapController.mapZoom',
                zoomToSearchGraphic: 'app/map/MapController.zoomToSearchGraphic',
                graphic: 'app/map/MapController.graphic',
                clearGraphics: 'app/map/MapController.clearGraphics',
                zoom: 'app/map/MapController.zoom'
            },
            appWizard: {
                requestAccess: 'app/Wizard.requestAccess',
                showSearch: 'app/Wizard.showSearch',
                showQueryLayers: 'app/Wizard.showQueryLayers',
                showResults: 'app/Wizard.showResults'
            },
            appSearch: {
                featuresFound: 'app/search/Search.featuresFound',
                searchStarted: 'app/search/Search.searchStarted',
                searchError: 'app/search/Search.searchError',
                clear: 'app/search/Search.clear',
                identify: 'app/search/identify'
            },
            appResultLayer: {
                addLayer: 'app/search/ResultLayer.addLayer',
                removeLayer: 'app/search/ResultLayer.removeLayer',
                highlightFeature: 'app/search/ResultLayer.highlightFeature',
                clearSelection: 'app/search/ResultLayer.clearSelection'
            },
            appSearchIdentifyPane: {
                backToResults: 'app/search/IdentifyPane.backToResults'
            },
            app: {
                hideGrid: 'app/App.hideGrid',
                showGrid: 'app/App.showGrid'
            }
        },

        // urls: Object
        //      Urls for the project
        urls: {
            UtahPLSS: 'http://mapserv.utah.gov/arcgis/rest/services/UtahPLSS/MapServer',
            DEQEnviro: '/arcgis/rest/services/DEQEnviro/MapServer',
            json: '/webdata/DEQEnviro.json',
            geometryService: '/arcgis/rest/services/Geometry/GeometryServer',
            terrain: 'http://mapserv.utah.gov/arcgis/rest/services/BaseMaps/Terrain/MapServer',
            securedServicesBaseUrl: '/none',
            api: {
                search: location.pathname.replace(/\/(src|dist)\/[^/]*$/, '') + '/api/search'
            }
        },

        // layerIndices: Object
        //      Indices of layers within map services.
        layerIndices: {
            landOwnership: 0,
            environmentalCovenants: 1,
            huc: 2,
            indianTribal: 3,
            city: 1 // Terrain service
        },

        // fieldNames: {}
        fieldNames: {
            cities: {
                NAME: 'NAME'
            },
            counties: {
                NAME: 'NAME'
            },
            utah: {
                STATE: 'STATE'
            },
            queryLayers: {
                ADDRESS: 'ADDRESS',
                CITY: 'CITY',
                ID: 'ID',
                NAME: 'NAME',
                TYPE: 'TYPE',
                UNIQUE_ID: 'UNIQUE_ID'
            }
        },

        // featureClassNames: {}
        featureClassNames: {
            counties: 'SGID10.BOUNDARIES.Counties',
            utah: 'SGID10.BOUNDARIES.Utah'
        },

        // TRSMinScaleLevel: Number
        //      The minimum scale level that the TRS Layer widget will appear disabled.
        TRSMinScaleLevel: 5,

        // appJson: Object
        //      Cache for data returned by getAppJson
        appJson: null,

        // queryLayerNames: Object
        //      Lookup for query layer name by layer index
        //      Populated in getAppJson below
        queryLayerNames: null,

        // spatialReference SpatialReference
        //      The spatial reference of the map
        spatialReference: new SpatialReference(26912),

        // symbols: Object
        //      Graphic symbols used in this app
        symbols: {
            zoom: {
                polygon: new SimpleFillSymbol(
                    SimpleFillSymbol.STYLE_SOLID,
                    new SimpleLineSymbol(
                        SimpleLineSymbol.STYLE_SOLID,
                        zoomColor,
                        2
                    ),
                    zoomFillColor),
                point: new SimpleMarkerSymbol(
                    SimpleMarkerSymbol.STYLE_CIRCLE,
                    13,
                    new SimpleLineSymbol(
                        SimpleLineSymbol.STYLE_SOLID,
                        zoomColor,
                        2),
                    zoomFillColor),
                polyline: new SimpleLineSymbol(
                    SimpleLineSymbol.STYLE_SOLID,
                    zoomColor,
                    4
                )
            },
            resultSymbolOpacity: 225,
            colors: [
                [31, 120, 180],
                [51, 160, 44],
                [227, 26, 28],
                [255, 127, 0],
                [106, 61, 154],
                [253, 191, 111],
                [251, 154, 153],
                [178, 223, 138],
                [166, 206, 227],
                [202, 178, 214],
                [255, 255, 153],
                [177, 89, 40]
            ],
            selection: {
                polygon: new SimpleFillSymbol(
                    SimpleFillSymbol.STYLE_SOLID,
                    new CartographicLineSymbol(
                        CartographicLineSymbol.STYLE_SOLID,
                        selectionColor,
                        3,
                        CartographicLineSymbol.CAP_ROUND,
                        CartographicLineSymbol.JOIN_ROUND),
                    selectionFillColor
                ),
                point: new SimpleMarkerSymbol(
                    SimpleMarkerSymbol.STYLE_CIRCLE,
                    15,
                    new SimpleLineSymbol(
                        SimpleLineSymbol.STYLE_SOLID,
                        selectionColor,
                        2),
                    selectionFillColor
                )
            }
        },

        // messages: Object
        //      Messages and text used throughout the app
        messages: {
            noFeaturesFound: 'No results'
        },

        getAppJson: function () {
            // summary:
            //      requests the DEQEnviro.json data and returns it, caches the results for future requests
            console.log('app.config::getAppJson', arguments);

            var def = new Deferred();
            var that = this;

            if (!this.appJson) {
                request(this.urls.json, {
                    handleAs: 'json'
                }).then(function (json) {
                    that.queryLayerNames = {};
                    array.forEach(json.queryLayers, function (ql) {
                        that.queryLayerNames[ql.index] = ql.name;
                    });
                    def.resolve(that.appJson = json);
                });
            } else {
                def.resolve(this.appJson);
            }

            return def.promise;
        },
        getQueryLayerByIndex: function (index) {
            // summary:
            //      description
            // index: String
            console.log('app/config:getQueryLayerByIndex', arguments);

            return this.getDatasetByIndex(this.appJson.queryLayers, index);
        },
        getRelatedTableByIndex: function (index) {
            // summary:
            //      description
            // index: String
            console.log('app/config:getRelatedTableByIndex', arguments);

            return this.getDatasetByIndex(this.appJson.relatedTables, index);
        },
        getDatasetByIndex: function (datasets, index) {
            // this could easily be done with one loop but I wanted to try
            // out memoization :)
            this._cached = this._cached || {};

            if (this._cached[index]) {
                return this._cached[index];
            }

            var returnLayer;
            array.some(datasets, function (ql) {
                if (ql.index + '' === index) {
                    returnLayer = ql;
                    return true;
                } else {
                    return false;
                }
            });

            this._cached[index] = returnLayer;

            return returnLayer;
        }
    };

    if (has('agrc-api-key') === 'prod') {
        // mapserv.utah.gov
        window.AGRC.apiKey = 'AGRC-A94B063C533889';
    } else if (has('agrc-api-key') === 'stage') {
        // test.mapserv.utah.gov
        window.AGRC.apiKey = 'AGRC-AC122FA9671436';
    } else {
        // localhost
        window.AGRC.apiKey = 'AGRC-E5B94F99865799';
    }

    return window.AGRC;
});<commit_msg>Adjusted transparency of results and selection graphics.<commit_after>/* jshint maxlen:false */
define([
    'dojo/_base/Color',
    'dojo/_base/array',
    'dojo/_base/lang',
    'dojo/request',
    'dojo/Deferred',
    'dojo/has',

    'esri/SpatialReference',
    'esri/symbols/SimpleFillSymbol',
    'esri/symbols/SimpleLineSymbol',
    'esri/symbols/SimpleMarkerSymbol',
    'esri/symbols/CartographicLineSymbol'
], function (
    Color,
    array,
    lang,
    request,
    Deferred,
    has,

    SpatialReference,
    SimpleFillSymbol,
    SimpleLineSymbol,
    SimpleMarkerSymbol,
    CartographicLineSymbol
    ) {

    var zoomColor = new Color([255, 255, 0]);
    var zoomFillColor = new Color(zoomColor.toRgb().concat([0.15]));
    var selectionColor = new Color([240, 18, 190]);
    var selectionFillColor = new Color(selectionColor.toRgb().concat([0.35]));
    window.AGRC = {
        // app: app.App
        //      global reference to App
        app: null,

        // appName: String
        //      name of the app used in permissionsproxy
        appName: 'deq',

        // version: String
        //      The version number.
        version: '0.7.0',

        // popupDelay: Number
        //      The delay (in milliseconds) before a popup is shown on hover.
        popupDelay: 250,

        gridIdentifyHeight: 237,

        // topics: Object
        //      The topic strings used in this app
        topics: {
            appMapReferenceLayerToggle: {
                addLayer: 'app/map/ReferenceLayerToggle.addLayer',
                toggleLayer: 'app/map/ReferenceLayerToggle.toggleLayer'
            },
            appQueryLayer: {
                addLayer: 'app/QueryLayer.addLayer',
                removeLayer: 'app/QueryLayer.removeLayer'
            },
            appMapMapController: {
                mapZoom: 'app/map/MapController.mapZoom',
                zoomToSearchGraphic: 'app/map/MapController.zoomToSearchGraphic',
                graphic: 'app/map/MapController.graphic',
                clearGraphics: 'app/map/MapController.clearGraphics',
                zoom: 'app/map/MapController.zoom'
            },
            appWizard: {
                requestAccess: 'app/Wizard.requestAccess',
                showSearch: 'app/Wizard.showSearch',
                showQueryLayers: 'app/Wizard.showQueryLayers',
                showResults: 'app/Wizard.showResults'
            },
            appSearch: {
                featuresFound: 'app/search/Search.featuresFound',
                searchStarted: 'app/search/Search.searchStarted',
                searchError: 'app/search/Search.searchError',
                clear: 'app/search/Search.clear',
                identify: 'app/search/identify'
            },
            appResultLayer: {
                addLayer: 'app/search/ResultLayer.addLayer',
                removeLayer: 'app/search/ResultLayer.removeLayer',
                highlightFeature: 'app/search/ResultLayer.highlightFeature',
                clearSelection: 'app/search/ResultLayer.clearSelection'
            },
            appSearchIdentifyPane: {
                backToResults: 'app/search/IdentifyPane.backToResults'
            },
            app: {
                hideGrid: 'app/App.hideGrid',
                showGrid: 'app/App.showGrid'
            }
        },

        // urls: Object
        //      Urls for the project
        urls: {
            UtahPLSS: 'http://mapserv.utah.gov/arcgis/rest/services/UtahPLSS/MapServer',
            DEQEnviro: '/arcgis/rest/services/DEQEnviro/MapServer',
            json: '/webdata/DEQEnviro.json',
            geometryService: '/arcgis/rest/services/Geometry/GeometryServer',
            terrain: 'http://mapserv.utah.gov/arcgis/rest/services/BaseMaps/Terrain/MapServer',
            securedServicesBaseUrl: '/none',
            api: {
                search: location.pathname.replace(/\/(src|dist)\/[^/]*$/, '') + '/api/search'
            }
        },

        // layerIndices: Object
        //      Indices of layers within map services.
        layerIndices: {
            landOwnership: 0,
            environmentalCovenants: 1,
            huc: 2,
            indianTribal: 3,
            city: 1 // Terrain service
        },

        // fieldNames: {}
        fieldNames: {
            cities: {
                NAME: 'NAME'
            },
            counties: {
                NAME: 'NAME'
            },
            utah: {
                STATE: 'STATE'
            },
            queryLayers: {
                ADDRESS: 'ADDRESS',
                CITY: 'CITY',
                ID: 'ID',
                NAME: 'NAME',
                TYPE: 'TYPE',
                UNIQUE_ID: 'UNIQUE_ID'
            }
        },

        // featureClassNames: {}
        featureClassNames: {
            counties: 'SGID10.BOUNDARIES.Counties',
            utah: 'SGID10.BOUNDARIES.Utah'
        },

        // TRSMinScaleLevel: Number
        //      The minimum scale level that the TRS Layer widget will appear disabled.
        TRSMinScaleLevel: 5,

        // appJson: Object
        //      Cache for data returned by getAppJson
        appJson: null,

        // queryLayerNames: Object
        //      Lookup for query layer name by layer index
        //      Populated in getAppJson below
        queryLayerNames: null,

        // spatialReference SpatialReference
        //      The spatial reference of the map
        spatialReference: new SpatialReference(26912),

        // symbols: Object
        //      Graphic symbols used in this app
        symbols: {
            zoom: {
                polygon: new SimpleFillSymbol(
                    SimpleFillSymbol.STYLE_SOLID,
                    new SimpleLineSymbol(
                        SimpleLineSymbol.STYLE_SOLID,
                        zoomColor,
                        2
                    ),
                    zoomFillColor),
                point: new SimpleMarkerSymbol(
                    SimpleMarkerSymbol.STYLE_CIRCLE,
                    13,
                    new SimpleLineSymbol(
                        SimpleLineSymbol.STYLE_SOLID,
                        zoomColor,
                        2),
                    zoomFillColor),
                polyline: new SimpleLineSymbol(
                    SimpleLineSymbol.STYLE_SOLID,
                    zoomColor,
                    4
                )
            },
            resultSymbolOpacity: 190,
            colors: [
                [31, 120, 180],
                [51, 160, 44],
                [227, 26, 28],
                [255, 127, 0],
                [106, 61, 154],
                [253, 191, 111],
                [251, 154, 153],
                [178, 223, 138],
                [166, 206, 227],
                [202, 178, 214],
                [255, 255, 153],
                [177, 89, 40]
            ],
            selection: {
                polygon: new SimpleFillSymbol(
                    SimpleFillSymbol.STYLE_SOLID,
                    new CartographicLineSymbol(
                        CartographicLineSymbol.STYLE_SOLID,
                        selectionColor,
                        3,
                        CartographicLineSymbol.CAP_ROUND,
                        CartographicLineSymbol.JOIN_ROUND),
                    selectionFillColor
                ),
                point: new SimpleMarkerSymbol(
                    SimpleMarkerSymbol.STYLE_CIRCLE,
                    15,
                    new SimpleLineSymbol(
                        SimpleLineSymbol.STYLE_SOLID,
                        selectionColor,
                        2),
                    selectionFillColor
                )
            }
        },

        // messages: Object
        //      Messages and text used throughout the app
        messages: {
            noFeaturesFound: 'No results'
        },

        getAppJson: function () {
            // summary:
            //      requests the DEQEnviro.json data and returns it, caches the results for future requests
            console.log('app.config::getAppJson', arguments);

            var def = new Deferred();
            var that = this;

            if (!this.appJson) {
                request(this.urls.json, {
                    handleAs: 'json'
                }).then(function (json) {
                    that.queryLayerNames = {};
                    array.forEach(json.queryLayers, function (ql) {
                        that.queryLayerNames[ql.index] = ql.name;
                    });
                    def.resolve(that.appJson = json);
                });
            } else {
                def.resolve(this.appJson);
            }

            return def.promise;
        },
        getQueryLayerByIndex: function (index) {
            // summary:
            //      description
            // index: String
            console.log('app/config:getQueryLayerByIndex', arguments);

            return this.getDatasetByIndex(this.appJson.queryLayers, index);
        },
        getRelatedTableByIndex: function (index) {
            // summary:
            //      description
            // index: String
            console.log('app/config:getRelatedTableByIndex', arguments);

            return this.getDatasetByIndex(this.appJson.relatedTables, index);
        },
        getDatasetByIndex: function (datasets, index) {
            // this could easily be done with one loop but I wanted to try
            // out memoization :)
            this._cached = this._cached || {};

            if (this._cached[index]) {
                return this._cached[index];
            }

            var returnLayer;
            array.some(datasets, function (ql) {
                if (ql.index + '' === index) {
                    returnLayer = ql;
                    return true;
                } else {
                    return false;
                }
            });

            this._cached[index] = returnLayer;

            return returnLayer;
        }
    };

    if (has('agrc-api-key') === 'prod') {
        // mapserv.utah.gov
        window.AGRC.apiKey = 'AGRC-A94B063C533889';
    } else if (has('agrc-api-key') === 'stage') {
        // test.mapserv.utah.gov
        window.AGRC.apiKey = 'AGRC-AC122FA9671436';
    } else {
        // localhost
        window.AGRC.apiKey = 'AGRC-E5B94F99865799';
    }

    return window.AGRC;
});<|endoftext|>


<commit_before><%= file 'failbacks/jDataView/src/jdataview.js' %>

<%= file 'LICENSE' %>

void function (global) {
	"use strict";

	var Aurora = {}

	Aurora.flow = {
		ok: 'ok',
		error: 'error'
	}

	Aurora.status = {
		success: 'success'
	}

	Aurora.utilitites = { }

	Aurora.sources = { }

	global.Aurora = Aurora

	if (!global.DataView) {
		global.DataView = global.jDataView
	}

	<%= file 'object/object.js' %>

	<%= file 'object/task.js' %>
	<%= file 'object/channel.js' %>
}(this || global)<commit_msg>Add additional flow conditions<commit_after><%= file 'failbacks/jDataView/src/jdataview.js' %>

<%= file 'LICENSE' %>

void function (global) {
	"use strict";

	var Aurora = {}

	Aurora.flow = {
		ok: 'ok',
		resend: 'resend',

		notLinked: 'not-linked',
		wrongState: 'wrong-state',

		error: 'error',
		unexpected: 'unexpected',
		notSupported: 'not-supported',
		notNegotiated: 'not-negotiated'
	}

	Aurora.status = {
		success: 'success'
	}

	Aurora.utilitites = { }

	Aurora.sources = { }

	global.Aurora = Aurora

	if (!global.DataView) {
		global.DataView = global.jDataView
	}

	<%= file 'object/object.js' %>

	<%= file 'object/task.js' %>
	<%= file 'object/channel.js' %>
}(this || global)<|endoftext|>


<commit_before>/* CONSTANTS */

const CONTEXT_MENU_CONFIG = {
  "title": "Export notes to JSON",
  "documentUrlPatterns": ["*://*.amazon.com/*"],
}

const REASONABLE_TIMEOUT_FOR_SCREEN_PARSE = 3000;

/*
 * void copyText(string jsonSerializationText)
 *
 * Adds the content of jsonSerializationText to the system clipboard
 *
 */
function copyText(text) {
  // Egregiously stolen from
  // https://stackoverflow.com/questions/3436102/copy-to-clipboard-in-chrome-extension

  // Create a temporary node with the converted content as a node
  let copyFrom = document.createElement("textarea");
  copyFrom.textContent = text;

  let body = document.getElementsByTagName('body')[0];
  body.appendChild(copyFrom);

  // Select the content and copy it to the clipboard
  copyFrom.select();
  document.execCommand('copy');

  // Cleanup
  body.removeChild(copyFrom);
}

/*
 *
 * Event handler for the context-click operation. The pure eventing is handled
 * in the call to `chrome.contextMenus.create` below. Given the event
 * execution, we enter this handler.
 *
 * In order to run a more "back-end" style JavaScript code payload, we need to
 * pass a message to the content scripts held in `amajson.js`. Therefore the
 * first step is to load `amajson.js`. Due to the security sandboxing we need
 * to load these contents (inject them into the page) using `executeScript`.
 *
 * This occurs asynchronously so we need to wait until the Promise
 * resolves. Upon resolution we can continue processing the event. In this
 * case, the action is to send the message to the listener defined in
 * `amajson.js`.
 *
 */

function exportToJsonClick(info, tab) {
  let processPageNodes = new Promise((resolve, reject) => {
    chrome.tabs.executeScript(tab.id, {
      "file": "amajson.js",
    }, () => resolve());
    setTimeout(() => reject(), REASONABLE_TIMEOUT_FOR_SCREEN_PARSE);
  })

  processPageNodes.then(() => {
    chrome.tabs.sendMessage(tab.id, info, function(result) {
      copyText(result.node);
    })
  })
}

// This code fires during the extension (re)load
chrome.contextMenus.create(Object.assign(CONTEXT_MENU_CONFIG, {
  "onclick": exportToJsonClick
}));
<commit_msg>Rename & async / await processPageNodes -> injectAmajsonHandler<commit_after>/* CONSTANTS */

const CONTEXT_MENU_CONFIG = {
  "title": "Export notes to JSON",
  "documentUrlPatterns": ["*://*.amazon.com/*"],
}

const REASONABLE_TIMEOUT_FOR_SCREEN_PARSE = 3000;

/*
 * void copyText(string jsonSerializationText)
 *
 * Adds the content of jsonSerializationText to the system clipboard
 *
 */
function copyText(text) {
  // Egregiously stolen from
  // https://stackoverflow.com/questions/3436102/copy-to-clipboard-in-chrome-extension

  // Create a temporary node with the converted content as a node
  let copyFrom = document.createElement("textarea");
  copyFrom.textContent = text;

  let body = document.getElementsByTagName('body')[0];
  body.appendChild(copyFrom);

  // Select the content and copy it to the clipboard
  copyFrom.select();
  document.execCommand('copy');

  // Cleanup
  body.removeChild(copyFrom);
}

/*
 *
 * Event handler for the context-click operation. The pure eventing is handled
 * in the call to `chrome.contextMenus.create` below. Given the event
 * execution, we enter this handler.
 *
 * In order to run a more "back-end" style JavaScript code payload, we need to
 * pass a message to the content scripts held in `amajson.js`. Therefore the
 * first step is to load `amajson.js`. Due to the security sandboxing we need
 * to load these contents (inject them into the page) using `executeScript`.
 *
 * This occurs asynchronously so we need to wait until the Promise
 * resolves. Upon resolution we can continue processing the event. In this
 * case, the action is to send the message to the listener defined in
 * `amajson.js`.
 *
 */

async function injectAmajsonHandler(tab) {
  return new Promise((resolve, reject) => {
    chrome.tabs.executeScript(tab.id, {
      "file": "amajson.js",
    }, () => {
      if (chrome.runtime.lastError) {
        reject(`Error: ${chrome.runtime.lastError.message}`)
      } else {
        resolve()
      }
      setTimeout(() => reject(), REASONABLE_TIMEOUT_FOR_SCREEN_PARSE);
    });
  });
}

async function exportToJsonClick(info, tab) {
  try {
    await injectAmajsonHandler(tab);
  } catch(err) {
    console.log(err)
  }

  chrome.tabs.sendMessage(tab.id, info, function(result) {
    copyText(result.node);
  })
}

// This code fires during the extension (re)load
chrome.contextMenus.create(Object.assign(CONTEXT_MENU_CONFIG, {
  "onclick": exportToJsonClick
}));
<|endoftext|>


<commit_before>/*
 * Paper.js
 *
 * This file is part of Paper.js, a JavaScript Vector Graphics Library,
 * based on Scriptographer.org and designed to be largely API compatible.
 * http://paperjs.org/
 * http://scriptographer.org/
 *
 * Distributed under the MIT license. See LICENSE file for details.
 *
 * Copyright (c) 2011, Juerg Lehni & Jonathan Puckey
 * http://lehni.org/ & http://jonathanpuckey.com/
 *
 * All rights reserved.
 */

var Size = this.Size = Base.extend({
	initialize: function(arg0, arg1) {
		if (arguments.length == 2) {
			this.width = arg0;
			this.height = arg1;
		} else if (arguments.length == 1) {
			if (arg0 == null) {
				this.width = this.height = 0;
			} else if (arg0.width !== undefined) {
				this.width = arg0.width;
				this.height = arg0.height;
			} else if (arg0.x !== undefined) {
				this.width = arg0.x;
				this.height = arg0.y;
			} else if (Array.isArray(arg0)) {
				this.width = arg0[0];
				this.height = arg0.length > 1 ? arg0[1] : arg0[0];
			} else if (typeof arg0 === 'number') {
				this.width = this.height = arg0;
			} else {
				this.width = this.height = 0;
			}
		} else {
			this.width = this.height = 0;
		}
	},

	set: function(width, height) {
		this.width = width;
		this.height = height;
		return this;
	},

	add: function(size) {
		size = Size.read(arguments);
		return Size.create(this.width + size.width, this.height + size.height);
	},

	subtract: function(size) {
		size = Size.read(arguments);
		return Size.create(this.width - size.width, this.height - size.height);
	},

	multiply: function(size) {
		size = Size.read(arguments);
		return Size.create(this.width * size.width, this.height * size.height);
	},

	divide: function(size) {
		size = Size.read(arguments);
		return Size.create(this.width / size.width, this.height / size.height);
	},

	modulo: function(size) {
		size = Size.read(arguments);
		return Size.create(this.width % size.width, this.height % size.height);
	},

	negate: function() {
		return Size.create(-this.width, -this.height);
	},

	equals: function(size) {
		size = Size.read(arguments);
		return this.width == size.width && this.height == size.height;
	},

	/**
	 * Checks if this size has both the width and height set to 0.
	 *
	 * @return true if both width and height are 0, false otherwise.
	 */
	isZero: function() {
		return this.width == 0 && this.width == 0;
	},

	isNaN: function() {
		return isNaN(this.width) || isNaN(this.height);
	},

	toString: function() {
		var format = Base.formatNumber;
		return '{ x: ' + format(this.width)
				+ ', y: ' + format(this.height) + ' }';
	},

	statics: {
		// See Point.create()
		create: function(width, height) {
			return new Size(Size.dont).set(width, height);
		},

		min: function(Size1, Size2) {
			return Size.create(
				Math.min(Size1.width, Size2.width),
				Math.min(Size1.height, Size2.height));
		},

		max: function(Size1, Size2) {
			return Size.create(
				Math.max(Size1.width, Size2.width),
				Math.max(Size1.height, Size2.height));
		},

		random: function() {
			return Size.create(Math.random(), Math.random());
		}
	}
}, new function() { // Scope for injecting round, ceil, floor, abs:
	return Base.each(['round', 'ceil', 'floor', 'abs'], function(name) {
		var op = Math[name];
		this[name] = function() {
			return Size.create(op(this.width), op(this.height));
		};
	}, {});
});

/**
 * An internal version of Size that notifies its owner of each change through
 * setting itself again on the setter that corresponds to the getter that
 * produced this LinkedSize. See uses of LinkedSize.create()
 * Note: This prototype is not exported.
 */
var LinkedSize = Size.extend({
	beans: true,

	set: function(width, height, dontNotify) {
		this._width = width;
		this._height = height;
		if (!dontNotify)
			this._owner[this._setter](this);
		return this;
	},

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

	setWidth: function(width) {
		this._width = width;
		this._owner[this._setter](this);
	},

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

	setHeight: function(height) {
		this._height = height;
		this._owner[this._setter](this);
	},

	statics: {
		create: function(owner, setter, width, height) {
			var point = new LinkedSize(LinkedSize.dont);
			point._width = width;
			point._height = height;
			point._owner = owner;
			point._setter = setter;
			return point;
		}
	}
});
<commit_msg>Fix Size#toString().<commit_after>/*
 * Paper.js
 *
 * This file is part of Paper.js, a JavaScript Vector Graphics Library,
 * based on Scriptographer.org and designed to be largely API compatible.
 * http://paperjs.org/
 * http://scriptographer.org/
 *
 * Distributed under the MIT license. See LICENSE file for details.
 *
 * Copyright (c) 2011, Juerg Lehni & Jonathan Puckey
 * http://lehni.org/ & http://jonathanpuckey.com/
 *
 * All rights reserved.
 */

var Size = this.Size = Base.extend({
	initialize: function(arg0, arg1) {
		if (arguments.length == 2) {
			this.width = arg0;
			this.height = arg1;
		} else if (arguments.length == 1) {
			if (arg0 == null) {
				this.width = this.height = 0;
			} else if (arg0.width !== undefined) {
				this.width = arg0.width;
				this.height = arg0.height;
			} else if (arg0.x !== undefined) {
				this.width = arg0.x;
				this.height = arg0.y;
			} else if (Array.isArray(arg0)) {
				this.width = arg0[0];
				this.height = arg0.length > 1 ? arg0[1] : arg0[0];
			} else if (typeof arg0 === 'number') {
				this.width = this.height = arg0;
			} else {
				this.width = this.height = 0;
			}
		} else {
			this.width = this.height = 0;
		}
	},

	set: function(width, height) {
		this.width = width;
		this.height = height;
		return this;
	},

	add: function(size) {
		size = Size.read(arguments);
		return Size.create(this.width + size.width, this.height + size.height);
	},

	subtract: function(size) {
		size = Size.read(arguments);
		return Size.create(this.width - size.width, this.height - size.height);
	},

	multiply: function(size) {
		size = Size.read(arguments);
		return Size.create(this.width * size.width, this.height * size.height);
	},

	divide: function(size) {
		size = Size.read(arguments);
		return Size.create(this.width / size.width, this.height / size.height);
	},

	modulo: function(size) {
		size = Size.read(arguments);
		return Size.create(this.width % size.width, this.height % size.height);
	},

	negate: function() {
		return Size.create(-this.width, -this.height);
	},

	equals: function(size) {
		size = Size.read(arguments);
		return this.width == size.width && this.height == size.height;
	},

	/**
	 * Checks if this size has both the width and height set to 0.
	 *
	 * @return true if both width and height are 0, false otherwise.
	 */
	isZero: function() {
		return this.width == 0 && this.width == 0;
	},

	isNaN: function() {
		return isNaN(this.width) || isNaN(this.height);
	},

	toString: function() {
		var format = Base.formatNumber;
		return '{ width: ' + format(this.width)
				+ ', height: ' + format(this.height) + ' }';
	},

	statics: {
		// See Point.create()
		create: function(width, height) {
			return new Size(Size.dont).set(width, height);
		},

		min: function(Size1, Size2) {
			return Size.create(
				Math.min(Size1.width, Size2.width),
				Math.min(Size1.height, Size2.height));
		},

		max: function(Size1, Size2) {
			return Size.create(
				Math.max(Size1.width, Size2.width),
				Math.max(Size1.height, Size2.height));
		},

		random: function() {
			return Size.create(Math.random(), Math.random());
		}
	}
}, new function() { // Scope for injecting round, ceil, floor, abs:
	return Base.each(['round', 'ceil', 'floor', 'abs'], function(name) {
		var op = Math[name];
		this[name] = function() {
			return Size.create(op(this.width), op(this.height));
		};
	}, {});
});

/**
 * An internal version of Size that notifies its owner of each change through
 * setting itself again on the setter that corresponds to the getter that
 * produced this LinkedSize. See uses of LinkedSize.create()
 * Note: This prototype is not exported.
 */
var LinkedSize = Size.extend({
	beans: true,

	set: function(width, height, dontNotify) {
		this._width = width;
		this._height = height;
		if (!dontNotify)
			this._owner[this._setter](this);
		return this;
	},

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

	setWidth: function(width) {
		this._width = width;
		this._owner[this._setter](this);
	},

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

	setHeight: function(height) {
		this._height = height;
		this._owner[this._setter](this);
	},

	statics: {
		create: function(owner, setter, width, height) {
			var point = new LinkedSize(LinkedSize.dont);
			point._width = width;
			point._height = height;
			point._owner = owner;
			point._setter = setter;
			return point;
		}
	}
});
<|endoftext|>


<commit_before>/*
	by default, the line is expect the data like this structure { x: 0.3434, y: 0.3242}
	but if the object data is rather different like { z: 0.3434, y: 0.3242}

	var line = this.mixin("Line", this.base.append('g').classed('lines', true), {
		info: containerInfo
	});

	line.line.x(function(d){
		return line.xScale(d.z);
	});

	Use this.line # this will be replaced with its current context like line here.
	context.xScale will access the this.xScale here.

	class:  dot

	this.path leave in transform, so that it could be extended by Area chart
 */
d3.chart('Base').extend('Line', {

	initialize: function(options) {
		options = options || {};

		this.layer('line', this.base, {
			dataBind: function(data) {
				var chart = this.chart();

				chart.line = d3.svg.line();

				// Setup the auto resize to handle the on resize event
				chart.dispatch.on('d3maSingleWindowResize', function(chart, single){
					single.attr({ 'd': chart.line });
				});

				chart.line
					.x(function(d) { return chart.xScale(d.x); })
					.y(function(d) { return chart.yScale(d.y);  });

				if(chart.onDataBind) { chart.onDataBind(chart, data,  (options.data) ? options.data : undefined ); }

				// data[options.data]  will return a single array, data will bind path element to each array index,
				// by pushing options array into an anonymous array, ONLY one path element will be created
				//return this.selectAll('path').data( (options.data) ? [ data[options.data] ]: data );
				return this.selectAll('path').data( [data] );
			},

			insert: function(){
				var chart = this.chart();
				if(chart.onInsert) { chart.onInsert(chart); }
				return this.append('path').classed('line', true);
			},

			events: {
				'enter': function() {
					var chart = this.chart();

					// chart  # refer to this context, used it to access xScale, yScale, width, height, etc. chart property
					// this   # refer to each individual group just appended by insert command
					if(chart.onEnter) { chart.onEnter(chart, this); }

					chart._onWindowResize(chart, this);

					this.attr({
						'd': chart.line,
						'opacity': 1e-6
					});
				},

				'enter:transition': function() {
					var chart = this.chart();
					return this
							.duration(1000)
							.style('opacity', 1);
				}
			}
		});
	}

	// 	this.linePath = this.base.append('path').attr({
	// 		'class': 'line',
	// 	});

	// 	if(this.onDataBind) { this.onDataBind(); }

	// 	this.linePath.datum(data).attr('d', this.line);

	// 	// Define this fn where the data is manipulated
	// 	// after all the data var has the correct value, then call it on Window resize
	// 	// Normally, after calling this fn, need to define the _update to handle the Scale change, box size changes, attr updates
	// 	this._onWindowResize();

	// 	return data;
	// }

	// Update Scale, Box Size, and attr values
	// _update: function(_width, _height) {

	// 	this.linePath.attr({
	// 		'd': this.line
	// 	});
	// }
});
<commit_msg>comment out the line transition since it did not work at this moment<commit_after>/*
	by default, the line is expect the data like this structure { x: 0.3434, y: 0.3242}
	but if the object data is rather different like { z: 0.3434, y: 0.3242}

	var line = this.mixin("Line", this.base.append('g').classed('lines', true), {
		info: containerInfo
	});

	line.line.x(function(d){
		return line.xScale(d.z);
	});

	Use this.line # this will be replaced with its current context like line here.
	context.xScale will access the this.xScale here.

	class:  dot

	this.path leave in transform, so that it could be extended by Area chart
 */
d3.chart('Base').extend('Line', {

	initialize: function(options) {
		options = options || {};

		this.layer('line', this.base, {
			dataBind: function(data) {
				var chart = this.chart();

				chart.line = d3.svg.line();

				// Setup the auto resize to handle the on resize event
				chart.dispatch.on('d3maSingleWindowResize', function(chart, single){
					single.attr({ 'd': chart.line });
				});

				chart.line
					.x(function(d) { return chart.xScale(d.x); })
					.y(function(d) { return chart.yScale(d.y);  });

				if(chart.onDataBind) { chart.onDataBind(chart, data,  (options.data) ? options.data : undefined ); }

				// data[options.data]  will return a single array, data will bind path element to each array index,
				// by pushing options array into an anonymous array, ONLY one path element will be created
				//return this.selectAll('path').data( (options.data) ? [ data[options.data] ]: data );
				return this.selectAll('path').data( [data] );
			},

			insert: function(){
				var chart = this.chart();
				if(chart.onInsert) { chart.onInsert(chart); }
				return this.append('path').classed('line', true);
			},

			events: {
				'enter': function() {
					var chart = this.chart();

					// chart  # refer to this context, used it to access xScale, yScale, width, height, etc. chart property
					// this   # refer to each individual group just appended by insert command
					if(chart.onEnter) { chart.onEnter(chart, this); }

					chart._onWindowResize(chart, this);

					this.attr({
						'd': chart.line,
						//'opacity': 1e-6
						'opacity': 0.9
					});
				}

				// 'enter:transition': function() {
				// 	var chart = this.chart();
				// 	return this
				// 			.duration(1000)
				// 			.style('opacity', 1);
				// }
			}
		});
	}

	// 	this.linePath = this.base.append('path').attr({
	// 		'class': 'line',
	// 	});

	// 	if(this.onDataBind) { this.onDataBind(); }

	// 	this.linePath.datum(data).attr('d', this.line);

	// 	// Define this fn where the data is manipulated
	// 	// after all the data var has the correct value, then call it on Window resize
	// 	// Normally, after calling this fn, need to define the _update to handle the Scale change, box size changes, attr updates
	// 	this._onWindowResize();

	// 	return data;
	// }

	// Update Scale, Box Size, and attr values
	// _update: function(_width, _height) {

	// 	this.linePath.attr({
	// 		'd': this.line
	// 	});
	// }
});
<|endoftext|>


<commit_before>//--------------------------------------------------------------------------------------------------

var spawn = require('child_process').spawn;
var colors = require('colors/safe');
var async = require('async');

//--------------------------------------------------------------------------------------------------

var streem = function(message, color) {
    process.stdout.write(colors[color](message.toString()));
};

//--------------------------------------------------------------------------------------------------

var exec = function(args, callback) {
    var command = args.shift();
    var ch = spawn(command, args);

    ch.stdout.on('data', function(data) {
        streem(data, 'green');
    });
    ch.stderr.on('data', function(data) {
        streem(data, 'red');
    });
    ch.on('close', function(code) {
        callback(null);
        console.log('close = '+ args);
    });
};

//--------------------------------------------------------------------------------------------------

var commands = [
    ['clear'],
    ['git', 'add', '.'],
    ['git', 'commit', '-m', '"update"'],
    ['ls', '-la'],
    ['git', 'push']
];

//--------------------------------------------------------------------------------------------------

var arr = [];

    for (var i = 0; i < commands.length; i++) {
        arr[i] = (function(com) {
            return function(callback) {
                exec(com, callback);
            };
        })(commands[i]);
    }

async.waterfall(arr);

//--------------------------------------------------------------------------------------------------
/*
var colors = require('colors/safe');
const exec = require('child_process').exec;
*/
/*--------------------------------------------------------------------------------------------------
|
| -> Загрузка на GitHub
|
|-------------------------------------------------------------------------------------------------*/
/*
//exec('clear && git add . && git commit -m "update" && git push', function(error, stdout, stderr) {
exec('git', function(error, stdout, stderr) {
    if (error) {
        process.stdout.write(colors.red(error));
        return;
    }
    process.stdout.write(colors.green(stdout.toString()));
    process.stdout.write(colors.red(stderr.toString()));
});
*/
//--------------------------------------------------------------------------------------------------<commit_msg>"update"<commit_after>//--------------------------------------------------------------------------------------------------

var spawn = require('child_process').spawn;
var colors = require('colors/safe');
var async = require('async');

//--------------------------------------------------------------------------------------------------

var streem = function(message, color) {
    process.stdout.write(colors[color](message.toString()));
};

//--------------------------------------------------------------------------------------------------

var exec = function(args, callback) {
    var command = args.shift();
    var ch = spawn(command, args);

    ch.stdout.on('data', function(data) {
        streem(data, 'green');
    });
    ch.stderr.on('data', function(data) {
        streem(data, 'red');
    });
    ch.on('close', function(code) {
        callback(null);
        console.log('close = '+ command);
    });
};

//--------------------------------------------------------------------------------------------------

var commands = [
    ['clear'],
    ['git', 'add', '.'],
    ['git', 'commit', '-m', '"update"'],
    ['ls', '-la'],
    ['git', 'push']
];

//--------------------------------------------------------------------------------------------------

var arr = [];

    for (var i = 0; i < commands.length; i++) {
        arr[i] = (function(com) {
            return function(callback) {
                exec(com, callback);
            };
        })(commands[i]);
    }

async.waterfall(arr);

//--------------------------------------------------------------------------------------------------
/*
var colors = require('colors/safe');
const exec = require('child_process').exec;
*/
/*--------------------------------------------------------------------------------------------------
|
| -> Загрузка на GitHub
|
|-------------------------------------------------------------------------------------------------*/
/*
//exec('clear && git add . && git commit -m "update" && git push', function(error, stdout, stderr) {
exec('git', function(error, stdout, stderr) {
    if (error) {
        process.stdout.write(colors.red(error));
        return;
    }
    process.stdout.write(colors.green(stdout.toString()));
    process.stdout.write(colors.red(stderr.toString()));
});
*/
//--------------------------------------------------------------------------------------------------<|endoftext|>