<commit_before>/* The MIT License (MIT)
Copyright (c) 2016 The MITRE Corporation

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

/* National Weather Service Icons */
/* Makes use of Leaflet JS: http://leafletjs.com/ */
/* SVG Icons courtesy of GEOHuntsville: http://geohuntsville.org/page/geoq */

/* Dependent on L.Marker.AutoResizeSVG found at
   http://github.com/john-kilgo/L.Marker.AutoResizeSVG
   Include marker-resize-svg.js in your HTML document */

L.NWSIconsLayer = L.GeoJSON.extend({
    // Options are JSON object found in database
    options: {
        debug: true
    },

    // Boolean to see if should parse locations via SAME codes
    _isParse: false,

    // NOTE: A possible way to organize (possible list) of icons?
    _icons: {
        "Emergency Action Notification" : ["PAWS_WARNING_RED_Local-Area-Emergency.svg"],
        "Avalanche Warning" : ["PAWS_WARNING_RED_Avalanche.svg"],
        "Avalanche Watch" : ["PAWS_WATCH_YELLOW_Avalanche.svg"],
        "Blizzard Warning" : ["PAWS_WARNING_RED_Blizzard.svg"],
        "Child Abduction Emergency" : ["PAWS_STATEMENT_BLUE_Child-Abduction-Emergency.svg"],
        "Civil Danger Warning" : ["PAWS_WARNING_RED_CivilDanger.svg"],
        "Coastal Flood Warning" : ["PAWS_WARNING_RED_Coastal-Flood.svg"],
        "Coastal Flood Watch" : ["PAWS_WATCH_YELLOW_Coastal-Flood.svg"],
        "Dust Storm Warning" : ["PAWS_WARNING_RED_Dust-Storm.svg"],
        "Earthquake Warning" : ["PAWS_WARNING_RED_Earthquake.svg"],
        "Evacuation Immediate" : ["PAWS_WARNING_RED_Evacuate-Immediately.svg"],
        "Fire Warning" : ["PAWS_WARNING_RED_Fire.svg"],
        "Flash Flood Warning" : ["PAWS_WARNING_RED_Flash-Flood.svg"],
        "Flash Flood Watch" : ["PAWS_WATCH_YELLOW_Flash-Flood.svg"],
        "Flash Flood Statement" : ["PAWS_STATEMENT_BLUE_Flash-Flood.svg"],
        "Flood Warning" : ["PAWS_WARNING_RED_Flood.svg"],
        "Flood Watch" : ["PAWS_WATCH_YELLOW_Flood.svg"],
        "Flood Statement" : ["PAWS_STATEMENT_BLUE_Flood.svg"],
        "Flood Advisory" : ["PAWS_STATEMENT_BLUE_Flood.svg"],
        "Hazardous Materials Warning" : ["PAWS_WARNING_RED_Hazardous-Materials-Warning.svg"],
        "High Wind Warning" : ["PAWS_WARNING_RED_High-Wind.svg"],
        "High Wind Watch" : ["PAWS_WATCH_YELLOW_High-Wind.svg"],
        "Hurricane Warning" : ["PAWS_WARNING_RED_Hurricane.svg"],
        "Hurricane Watch" : ["PAWS_WATCH_YELLOW_Hurricane.svg"],
        "Hurricane Statement" : ["PAWS_STATEMENT_BLUE_Hurricane.svg"],
        "Law Enforcement Warning" : ["PAWS_WARNING_RED_Law-Enforcement.svg"],
        "Local Area Emergency" : ["PAWS_WARNING_RED_Local-Area-Emergency.svg"],
        "911 Telephone Outage Emergency" : ["PAWS_WARNING_RED_911TelephoneOutageEmergency.svg"],
        "Nuclear Power Plant Warning" : ["PAWS_WARNING_RED_Nuclear_Powerplant-Warning.svg"],
        "Radiological Hazard Warning" : ["PAWS_WARNING_RED_Radiological-Hazard-Warning.svg"],
        "Severe Thunderstorm Warning" : ["PAWS_WARNING_RED_Severe-Thunderstorm.svg"],
        "Severe Thunderstorm Watch" : ["PAWS_WATCH_YELLOW_Severe-Thunderstorm.svg"],
        "Severe Weather Statement" : ["PAWS_STATEMENT_BLUE_Severe-Weather.svg"],
        "Shelter in Place Warning" : ["PAWS_WARNING_RED_Shelter-In-Place.svg"],
        "Special Marine Warning" : ["PAWS_WARNING_RED_SpecialMarine.svg"],
        "Special Weather Statement" : ["PAWS_STATEMENT_BLUE_Special-Weather.svg"],
        "Tornado Warning" : ["PAWS_WARNING_RED_Tornado.svg"],
        "Tornado Watch" : ["PAWS_WATCH_YELLOW_Tornado.svg"],
        "Tropical Storm Warning" : ["PAWS_WARNING_RED_Tropical-Storm.svg"],
        "Tropical Storm Watch" : ["PAWS_WATCH_YELLOW_Tropical-Storm.svg"],
        "Tsunami Warning" : ["PAWS_WARNING_RED_Tsunami.svg"],
        "Tsunami Watch" : ["PAWS_WATCH_YELLOW_Tsunami.svg"],
        "Volcano Warning" : ["PAWS_WARNING_RED_Volcano.svg"],
        "Winter Storm Warning" : ["PAWS_WARNING_RED_Winter-Storm.svg"],
        "Winter Storm Watch" : ["PAWS_WATCH_YELLOW_Winter-Storm.svg"],
    },

    initialize: function (load, map, options) {
        // Note: load is unused at this time

        // Merge options together
        L.Util.setOptions(this, options);

        if (site_settings.FEMA_IPAWS) {
            L.Util.setOptions(this, site_settings.FEMA_IPAWS);
            //console.log(this.options);
        } else {
            console.error("NWS Icons: Fatal Error. site_settings missing. Please visit GeoQ Admin site and add FEMA_IPAWS json settings object.")
            return;
        }

        // Markers to add to map
        this._layers = {};
        // Our map
        this._map = map;

        if (this._map) {
            this.NWSLayerGroup.addTo(this._map);

            // When map moves update bounds
            var _this = this; // Set the context of the event handler
            //this._map.on('moveend', function(e) {
                //console.log(e)
                //_this.geocode();
                _this.load(_this.parseIPAWS);
                //_this.createMarkers();
            //});

            setInterval(function(){
                _this.load(_this.parseIPAWS);
            }, 600000)
        }

    },

    // Gets the bounds of the Workcell and calls for GeoCode info
    geocode: function() {
        var map = this._map;
        var bounds = map.getBounds();

        var ringObject = '{"rings":[[[' +
                bounds._southWest.lng + ',' + bounds._northEast.lat + '],[' +
                bounds._northEast.lng + ',' + bounds._northEast.lat + '],[' +
                bounds._northEast.lng + ',' + bounds._southWest.lat + '],[' +
                bounds._southWest.lng + ',' + bounds._southWest.lat + '],[' +
                bounds._southWest.lng + ',' + bounds._northEast.lat + ']]],' +
                '"spatialReference":{"wkid":4326}}';

        var url = "/geoq/proxy/https://tigerweb.geo.census.gov/arcgis/rest/services/Generalized_ACS2015/State_County/MapServer/11/query?where=&text=&objectIds=&time=&geometry=" + ringObject + "&geometryType=esriGeometryPolygon&inSR=&spatialRel=esriSpatialRelIntersects&relationParam=&outFields=GEOID&returnGeometry=false&returnTrueCurves=false&maxAllowableOffset=&geometryPrecision=&outSR=&returnIdsOnly=false&returnCountOnly=false&orderByFields=&groupByFieldsForStatistics=&outStatistics=&returnZ=false&returnM=false&gdbVersion=&returnDistinctValues=false&resultOffset=&resultRecordCount=&f=pjson";

        $.ajax({
            type: 'GET',
            context: this,
            url: url,
            dataType: 'json',
        })
        .done(this._geocode)
        .fail(this.ajaxError)
    },

    // Finds and saves SAME codes
    _geocode: function(data) {
        var features = data.features;
        this._sameCodes = [];

        for (var i=0; i < features.length; i++) {
            var tmp = features[i]["attributes"]["GEOID"];
            tmp = tmp.toString();
            // Prepend '0' in order to convert FIPS 5-1 to NWS SAME code
            tmp = '0' + tmp;
            this._sameCodes.push(tmp);
        }
    },

    // Loads the FEMA list server
    load: function(callback) {
        var options = this.options;

        if (!options.FEMAkey) {
            log.error("No key set for NWS Cap messages");
            console.error("No key set for NWS Cap messages");
            return;
        }

        $.ajax({
            type: "POST",
            url: "/geoq/api/geo/ipaws",
            context: this,
            data: {develop: true, key: this.options.FEMAkey}
        }).done(callback)
        .fail(this.ajaxError);
    },

    // NWS Callback IPAWS Parse
    parseIPAWS: function(data) {
        this._jsonData = [];
        var control,
            alerts = data.getElementsByTagName("alert"),
            searchCoordinates = new YouTubeSearch();
        console.log(alerts);
        console.log(data);

        for (var i = 0; i < alerts.length; i++) {
            control = false;
            var info = alerts[i].getElementsByTagName("info"),
                area = info[0].getElementsByTagName("area"),
                geocodes = area[0].getElementsByTagName("geocode"),
                polygon = area[0].getElementsByTagName("polygon");

            if (!this._isParse && (polygon[0])) {
            	control = true;
            } else {
            	if (info && area && geocodes && (polygon[0]) && this._sameCodes && alerts[i].getElementsByTagName("status")[0].innerHTML != "Cancelled") {
	                for (var j = 0; j < geocodes.length; j++) {
	                    if (geocodes[j].childNodes[0].innerHTML == "SAME" && control != true) {
	                        for (var k = 0; k < this._sameCodes.length; k++) {
	                            if (this._sameCodes[k] == geocodes[j].childNodes[1].innerHTML) {
	                                control = true;
	                            }
	                        }

	                    }
	                }
	            }
            }

            if (control) {
                var tmpJson = {};
                tmpJson["identifier"] = String(alerts[i].getElementsByTagName("identifier")[0].innerHTML);
                tmpJson["sent"] = alerts[i].getElementsByTagName("sent")[0].innerHTML;
                tmpJson["status"] = alerts[i].getElementsByTagName("status")[0].innerHTML;
                tmpJson["event"] = info[0].getElementsByTagName("event")[0].innerHTML;
                tmpJson["severity"] = info[0].getElementsByTagName("severity")[0].innerHTML;
                tmpJson["certainty"] = info[0].getElementsByTagName("certainty")[0].innerHTML;
                tmpJson["effective"] = info[0].getElementsByTagName("effective")[0].innerHTML;
                tmpJson["onset"] = info[0].getElementsByTagName("onset")[0].innerHTML;
                tmpJson["expires"] = info[0].getElementsByTagName("expires")[0].innerHTML;
                tmpJson["headline"] = info[0].getElementsByTagName("headline")[0].innerHTML;
                tmpJson["description"] = info[0].getElementsByTagName("description")[0].innerHTML;
                tmpJson["instruction"] = info[0].getElementsByTagName("instruction")[0].innerHTML;

                var mapData, jsonMapData = [];
                //console.log(polygon);
                var rawData = polygon[0].innerHTML;
                mapData = rawData.split(" ");

                for (var j = 0; j < mapData.length; j++) {
                    var latlong = mapData[j].split(",");
                    var jsonLatLong = {};
                    jsonLatLong["lat"] = latlong[0];
                    jsonLatLong["lon"] = latlong[1];

                    jsonMapData.push(jsonLatLong);
                }

                var boundingPoints = [];
                for (var j = 0; j < jsonMapData.length; j++) {
                    boundingPoints.push(new Point(jsonMapData[j].lat,jsonMapData[j].lon));
                }

                var center = searchCoordinates.generateCircle(boundingPoints);

                tmpJson["center"] = {"lat": center.currentCenterPoint.x, "lon": center.currentCenterPoint.y};
                //tmpJson["msgtype"] = alerts[i].getElementsByTagName("msgtype")[0].innerHTML;

                tmpJson["coordinates"] = jsonMapData;

                this._jsonData.push(tmpJson);

            }

            this.createMarkers();
        }
    },

    // If an ajax error occurs
    ajaxError: function (resultobj) {
        console.error("Ajax error.");
        console.log(resultobj);
        log.error("Request called for, but no valid response was received from the server, result:", resultobj);
    },

    // provide a way to hide layer
    setStyle: function (style) {
        this.NWSLayerGroup.eachLayer(function(lyr_group) {
            lyr_group.eachLayer(function(layer) {
                if (layer.setStyle){
                    layer.setStyle(style);
                } else if (layer.setOpacity){
                    layer.setOpacity(style.opacity);
                }
            });
        });
    },

    // Where icons/paths are stored
    NWSLayerGroup: L.layerGroup(),

    // Create markers and add layers to map
    createMarkers: function (){
        this.NWSLayerGroup.clearLayers();

        var _this = this;

        this._iconsTmp = null;
        this._iconsTmp = [];

        for (var i = 0; i < this._jsonData.length; i++){
            var tmpMarker, tmpPolygon, polyArr = [];
            var tmpLayer = L.layerGroup();

            // Polygon points array
            for (var j = 0; j < this._jsonData[i].coordinates.length; j++){
                var tmpArr = [];
                tmpArr.push(Number(this._jsonData[i].coordinates[j].lat));
                tmpArr.push(Number(this._jsonData[i].coordinates[j].lon));
                polyArr.push(tmpArr);
            }

            tmpPolygon = L.polygon(polyArr);

            this._iconsTmp.push(L.icon({
                iconUrl: this.options.iconPath + this._icons[this._jsonData[i].event][0],
                iconSize: [32,32],
                iconAnchor: [16, 32],
                popupAnchor: [0, -32],
                /*iconSizeArray: // For use when Leaflet 1.0 Implemented
                [
                    [32, 32], [96, 96], [256, 256]
                ],
                iconAnchorArray:
                [
                    [16, 32], [48, 96], [128, 256]
                ] */
            }));
            //console.log("icons:" + this._icons[this._jsonData[i].event][0])

            var center = this._jsonData[i].center;
            var lat = center.lat;
            var lon = center.lon;

            tmpMarker = L.marker([lat, lon], {icon: _this._iconsTmp[i]});

            var popupContent = 'Event: ' + this._jsonData[i].event +
                                '
Description: ' +
                                this._jsonData[i].description + '
' +
                                'Onset: ' + this._jsonData[i].onset + '';
            var popup = L.popup().setContent(popupContent);

            tmpMarker.bindPopup(popup);
            tmpLayer.addLayer(tmpPolygon);
            tmpLayer.addLayer(tmpMarker);

            this.NWSLayerGroup.addLayer(tmpLayer);
        }
    }
});
<commit_msg>temp update<commit_after>/* The MIT License (MIT)
Copyright (c) 2016 The MITRE Corporation

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

/* National Weather Service Icons */
/* Makes use of Leaflet JS: http://leafletjs.com/ */
/* SVG Icons courtesy of GEOHuntsville: http://geohuntsville.org/page/geoq */

/* Dependent on L.Marker.AutoResizeSVG found at
   http://github.com/john-kilgo/L.Marker.AutoResizeSVG
   Include marker-resize-svg.js in your HTML document */

L.NWSIconsLayer = L.GeoJSON.extend({
    // Options are JSON object found in database
    options: {
        debug: true
    },

    // Boolean to see if should parse locations via SAME codes
    _isParse: false,

    // NOTE: A possible way to organize (possible list) of icons?
    _icons: {
        "Emergency Action Notification" : ["PAWS_WARNING_RED_Local-Area-Emergency.svg"],
        "Avalanche Warning" : ["PAWS_WARNING_RED_Avalanche.svg"],
        "Avalanche Watch" : ["PAWS_WATCH_YELLOW_Avalanche.svg"],
        "Blizzard Warning" : ["PAWS_WARNING_RED_Blizzard.svg"],
        "Child Abduction Emergency" : ["PAWS_STATEMENT_BLUE_Child-Abduction-Emergency.svg"],
        "Civil Danger Warning" : ["PAWS_WARNING_RED_CivilDanger.svg"],
        "Coastal Flood Warning" : ["PAWS_WARNING_RED_Coastal-Flood.svg"],
        "Coastal Flood Watch" : ["PAWS_WATCH_YELLOW_Coastal-Flood.svg"],
        "Dust Storm Warning" : ["PAWS_WARNING_RED_Dust-Storm.svg"],
        "Earthquake Warning" : ["PAWS_WARNING_RED_Earthquake.svg"],
        "Evacuation Immediate" : ["PAWS_WARNING_RED_Evacuate-Immediately.svg"],
        "Fire Warning" : ["PAWS_WARNING_RED_Fire.svg"],
        "Flash Flood Warning" : ["PAWS_WARNING_RED_Flash-Flood.svg"],
        "Flash Flood Watch" : ["PAWS_WATCH_YELLOW_Flash-Flood.svg"],
        "Flash Flood Statement" : ["PAWS_STATEMENT_BLUE_Flash-Flood.svg"],
        "Flood Warning" : ["PAWS_WARNING_RED_Flood.svg"],
        "Flood Watch" : ["PAWS_WATCH_YELLOW_Flood.svg"],
        "Flood Statement" : ["PAWS_STATEMENT_BLUE_Flood.svg"],
        "Flood Advisory" : ["PAWS_STATEMENT_BLUE_Flood.svg"],
        "Hazardous Materials Warning" : ["PAWS_WARNING_RED_Hazardous-Materials-Warning.svg"],
        "High Wind Warning" : ["PAWS_WARNING_RED_High-Wind.svg"],
        "High Wind Watch" : ["PAWS_WATCH_YELLOW_High-Wind.svg"],
        "Hurricane Warning" : ["PAWS_WARNING_RED_Hurricane.svg"],
        "Hurricane Watch" : ["PAWS_WATCH_YELLOW_Hurricane.svg"],
        "Hurricane Statement" : ["PAWS_STATEMENT_BLUE_Hurricane.svg"],
        "Law Enforcement Warning" : ["PAWS_WARNING_RED_Law-Enforcement.svg"],
        "Local Area Emergency" : ["PAWS_WARNING_RED_Local-Area-Emergency.svg"],
        "911 Telephone Outage Emergency" : ["PAWS_WARNING_RED_911TelephoneOutageEmergency.svg"],
        "Nuclear Power Plant Warning" : ["PAWS_WARNING_RED_Nuclear_Powerplant-Warning.svg"],
        "Radiological Hazard Warning" : ["PAWS_WARNING_RED_Radiological-Hazard-Warning.svg"],
        "Severe Thunderstorm Warning" : ["PAWS_WARNING_RED_Severe-Thunderstorm.svg"],
        "Severe Thunderstorm Watch" : ["PAWS_WATCH_YELLOW_Severe-Thunderstorm.svg"],
        "Severe Weather Statement" : ["PAWS_STATEMENT_BLUE_Severe-Weather.svg"],
        "Shelter in Place Warning" : ["PAWS_WARNING_RED_Shelter-In-Place.svg"],
        "Special Marine Warning" : ["PAWS_WARNING_RED_SpecialMarine.svg"],
        "Special Weather Statement" : ["PAWS_STATEMENT_BLUE_Special-Weather.svg"],
        "Tornado Warning" : ["PAWS_WARNING_RED_Tornado.svg"],
        "Tornado Watch" : ["PAWS_WATCH_YELLOW_Tornado.svg"],
        "Tropical Storm Warning" : ["PAWS_WARNING_RED_Tropical-Storm.svg"],
        "Tropical Storm Watch" : ["PAWS_WATCH_YELLOW_Tropical-Storm.svg"],
        "Tsunami Warning" : ["PAWS_WARNING_RED_Tsunami.svg"],
        "Tsunami Watch" : ["PAWS_WATCH_YELLOW_Tsunami.svg"],
        "Volcano Warning" : ["PAWS_WARNING_RED_Volcano.svg"],
        "Winter Storm Warning" : ["PAWS_WARNING_RED_Winter-Storm.svg"],
        "Winter Storm Watch" : ["PAWS_WATCH_YELLOW_Winter-Storm.svg"],
    },

    initialize: function (load, map, options) {
        // Note: load is unused at this time

        // Merge options together
        L.Util.setOptions(this, options);

        if (site_settings.FEMA_IPAWS) {
            L.Util.setOptions(this, site_settings.FEMA_IPAWS);
            //console.log(this.options);
        } else {
            console.error("NWS Icons: Fatal Error. site_settings missing. Please visit GeoQ Admin site and add FEMA_IPAWS json settings object.")
            return;
        }

        // Markers to add to map
        this._layers = {};
        // Our map
        this._map = map;

        if (this._map) {
            this.NWSLayerGroup.addTo(this._map);

            // When map moves update bounds
            var _this = this; // Set the context of the event handler
            //this._map.on('moveend', function(e) {
                //console.log(e)
                //_this.geocode();
                _this.load(_this.parseIPAWS);
                //_this.createMarkers();
            //});

            setInterval(function(){
                _this.load(_this.parseIPAWS);
            }, 600000)
        }

    },

    // Gets the bounds of the Workcell and calls for GeoCode info
    geocode: function() {
        var map = this._map;
        var bounds = map.getBounds();

        var ringObject = '{"rings":[[[' +
                bounds._southWest.lng + ',' + bounds._northEast.lat + '],[' +
                bounds._northEast.lng + ',' + bounds._northEast.lat + '],[' +
                bounds._northEast.lng + ',' + bounds._southWest.lat + '],[' +
                bounds._southWest.lng + ',' + bounds._southWest.lat + '],[' +
                bounds._southWest.lng + ',' + bounds._northEast.lat + ']]],' +
                '"spatialReference":{"wkid":4326}}';

        var url = "/geoq/proxy/https://tigerweb.geo.census.gov/arcgis/rest/services/Generalized_ACS2015/State_County/MapServer/11/query?where=&text=&objectIds=&time=&geometry=" + ringObject + "&geometryType=esriGeometryPolygon&inSR=&spatialRel=esriSpatialRelIntersects&relationParam=&outFields=GEOID&returnGeometry=false&returnTrueCurves=false&maxAllowableOffset=&geometryPrecision=&outSR=&returnIdsOnly=false&returnCountOnly=false&orderByFields=&groupByFieldsForStatistics=&outStatistics=&returnZ=false&returnM=false&gdbVersion=&returnDistinctValues=false&resultOffset=&resultRecordCount=&f=pjson";

        $.ajax({
            type: 'GET',
            context: this,
            url: url,
            dataType: 'json',
        })
        .done(this._geocode)
        .fail(this.ajaxError)
    },

    // Finds and saves SAME codes
    _geocode: function(data) {
        var features = data.features;
        this._sameCodes = [];

        for (var i=0; i < features.length; i++) {
            var tmp = features[i]["attributes"]["GEOID"];
            tmp = tmp.toString();
            // Prepend '0' in order to convert FIPS 5-1 to NWS SAME code
            tmp = '0' + tmp;
            this._sameCodes.push(tmp);
        }
    },

    // Loads the FEMA list server
    load: function(callback) {
        var options = this.options;

        if (!options.FEMAkey) {
            log.error("No key set for NWS Cap messages");
            console.error("No key set for NWS Cap messages");
            return;
        }

        $.ajax({
            type: "POST",
            url: "/geoq/api/geo/ipaws",
            context: this,
            data: {develop: true, key: this.options.FEMAkey}
        }).done(callback)
        .fail(this.ajaxError);
    },

    // NWS Callback IPAWS Parse
    parseIPAWS: function(data) {
        this._jsonData = [];
        var control,
            alerts = data.getElementsByTagName("alert"),
            searchCoordinates = new YouTubeSearch();
        //console.log(alerts);
        //console.log(data);

        for (var i = 0; i < alerts.length; i++) {
            control = false;
            var info = alerts[i].getElementsByTagName("info"),
                area = info[0].getElementsByTagName("area"),
                geocodes = area[0].getElementsByTagName("geocode"),
                polygon = area[0].getElementsByTagName("polygon");

            if (!this._isParse && (polygon[0])) {
            	control = true;
            } else {
            	if (info && area && geocodes && (polygon[0]) && this._sameCodes && alerts[i].getElementsByTagName("status")[0].innerHTML != "Cancelled") {
	                for (var j = 0; j < geocodes.length; j++) {
	                    if (geocodes[j].childNodes[0].innerHTML == "SAME" && control != true) {
	                        for (var k = 0; k < this._sameCodes.length; k++) {
	                            if (this._sameCodes[k] == geocodes[j].childNodes[1].innerHTML) {
	                                control = true;
	                            }
	                        }

	                    }
	                }
	            }
            }

            if (control) {
                var tmpJson = {};
                tmpJson["identifier"] = String(alerts[i].getElementsByTagName("identifier")[0].innerHTML);
                tmpJson["sent"] = alerts[i].getElementsByTagName("sent")[0].innerHTML;
                tmpJson["status"] = alerts[i].getElementsByTagName("status")[0].innerHTML;
                tmpJson["event"] = info[0].getElementsByTagName("event")[0].innerHTML;
                tmpJson["severity"] = info[0].getElementsByTagName("severity")[0].innerHTML;
                tmpJson["certainty"] = info[0].getElementsByTagName("certainty")[0].innerHTML;
                tmpJson["effective"] = info[0].getElementsByTagName("effective")[0].innerHTML;
                tmpJson["onset"] = info[0].getElementsByTagName("onset")[0].innerHTML;
                tmpJson["expires"] = info[0].getElementsByTagName("expires")[0].innerHTML;
                tmpJson["headline"] = info[0].getElementsByTagName("headline")[0].innerHTML;
                tmpJson["description"] = info[0].getElementsByTagName("description")[0].innerHTML;
                tmpJson["instruction"] = info[0].getElementsByTagName("instruction")[0].innerHTML;

                var mapData, jsonMapData = [];
                //console.log(polygon);
                var rawData = polygon[0].innerHTML;
                mapData = rawData.split(" ");

                for (var j = 0; j < mapData.length; j++) {
                    var latlong = mapData[j].split(",");
                    var jsonLatLong = {};
                    jsonLatLong["lat"] = latlong[0];
                    jsonLatLong["lon"] = latlong[1];

                    jsonMapData.push(jsonLatLong);
                }

                var boundingPoints = [];
                for (var j = 0; j < jsonMapData.length; j++) {
                    boundingPoints.push(new Point(jsonMapData[j].lat,jsonMapData[j].lon));
                }

                var center = searchCoordinates.generateCircle(boundingPoints);

                tmpJson["center"] = {"lat": center.currentCenterPoint.x, "lon": center.currentCenterPoint.y};
                //tmpJson["msgtype"] = alerts[i].getElementsByTagName("msgtype")[0].innerHTML;

                tmpJson["coordinates"] = jsonMapData;

                this._jsonData.push(tmpJson);

            }

            this.createMarkers();
        }
    },

    // If an ajax error occurs
    ajaxError: function (resultobj) {
        console.error("Ajax error.");
        console.log(resultobj);
        log.error("Request called for, but no valid response was received from the server, result:", resultobj);
    },

    // provide a way to hide layer
    setStyle: function (style) {
        this.NWSLayerGroup.eachLayer(function(lyr_group) {
            lyr_group.eachLayer(function(layer) {
                if (layer.setStyle){
                    layer.setStyle(style);
                } else if (layer.setOpacity){
                    layer.setOpacity(style.opacity);
                }
            });
        });
    },

    // Where icons/paths are stored
    NWSLayerGroup: L.layerGroup(),

    // Point to Layer http://leafletjs.com/reference.html#geojson-pointtolayer
    pointToLayer: function(feature, latlng) {
        return L.marker(latlng);

    },

    onEachFeature: function(feature, layer) {
        var popup = L.popup().setContent("test content");

        layer.bindPopup(popup);
    },

    // Create markers and add layers to map
    createMarkers: function (){
        this.NWSLayerGroup.clearLayers();

        var _this = this;

        this._iconsTmp = null;
        this._iconsTmp = [];

        for (var i = 0; i < this._jsonData.length; i++){
            var tmpMarker, tmpPolygon, polyArr = [];
            var tmpLayer = L.layerGroup();

            // Polygon points array
            for (var j = 0; j < this._jsonData[i].coordinates.length; j++){
                var tmpArr = [];
                tmpArr.push(Number(this._jsonData[i].coordinates[j].lat));
                tmpArr.push(Number(this._jsonData[i].coordinates[j].lon));
                polyArr.push(tmpArr);
            }

            tmpPolygon = L.polygon(polyArr);

            this._iconsTmp.push(L.icon({
                iconUrl: this.options.iconPath + this._icons[this._jsonData[i].event][0],
                iconSize: [32,32],
                iconAnchor: [16, 32],
                popupAnchor: [0, -32],
                /*iconSizeArray: // For use when Leaflet 1.0 Implemented
                [
                    [32, 32], [96, 96], [256, 256]
                ],
                iconAnchorArray:
                [
                    [16, 32], [48, 96], [128, 256]
                ] */
            }));
            //console.log("icons:" + this._icons[this._jsonData[i].event][0])

            var center = this._jsonData[i].center;
            var lat = center.lat;
            var lon = center.lon;

            tmpMarker = L.marker([lat, lon], {icon: _this._iconsTmp[i]});

            var popupContent = 'Event: ' + this._jsonData[i].event +
                                '
Description: ' +
                                this._jsonData[i].description + '
' +
                                'Onset: ' + this._jsonData[i].onset + '';
            var popup = L.popup().setContent(popupContent);

            tmpMarker.bindPopup(popup);
            tmpLayer.addLayer(tmpPolygon);
            tmpLayer.addLayer(tmpMarker);

            this.NWSLayerGroup.addLayer(tmpLayer);
        }
    }
});
<|endoftext|>


<commit_before>'use strict';
//var angular;
/*jslint nomen: true regexp: true*/

angular.module('app').controller('nrgiAssessmentAdminDetailCtrl', function ($scope, $route, $routeParams, $location, mgaIdentitySrvc, mgaNotifier, mgaAssessmentSrvc, mgaAssessmentMethodSrvc, mgaUserListSrvc, mgaIntervieweeSrvc, mgaAnswerSrvc) {
    // filtering options
    $scope.sort_options = [
        {value: "question_order", text: "Sort by question number"},
        {value: "question_flow_order", text: "Sort by question order"},
        {value: "question_indicator_ID", text: "Sort by indicator"},
        {value: "question_mode", text: "Sorty by question mode"},
        {value: "question_data_type", text: "Sort by data type"},
        //{value: "status", text: "Sort by status"},
        {value: "status", text: "Sort by status"}
    ];
    $scope.sort_order = $scope.sort_options[0].value;

    $scope.current_user = mgaIdentitySrvc.currentUser;

    // pull assessment data and add
    mgaAssessmentSrvc.get({assessment_ID: $routeParams.assessment_ID}, function (data) {
        $scope.answer_list = [];
        mgaAnswerSrvc.query({assessment_ID: $routeParams.assessment_ID}, function (answers) {

            $scope.getArray = [{
                question_order: 'question_order',
                question_text: 'question_text',
                question_data_type: 'question_data_type',
                question_mode: 'question_mode',
                question_indicator_ID: 'question_indicator_ID',
                question_indicator: 'question_indicator',
                question_theme_ID: 'question_theme_ID',
                question_value_chain_ID: 'question_value_chain_ID',
                status: 'status',
                score_value: 'score_value',
                score_text: 'score_text',
                answer_text: 'answer_text',
                comments: 'comments',
                flags: 'flags',
                interviewee_name: 'interviewee_name',
                interviewee_email: 'interviewee_email',
                interviewee_phone: 'interviewee_phone',
                interviewee_role: 'interviewee_role'
            }];

            $scope.edited_by = mgaUserListSrvc.get({_id: data.modified[data.modified.length - 1].modified_by});
            $scope.user_list = [];
            data.users.forEach(function (el) {
                var u = mgaUserListSrvc.get({_id: el});
                $scope.user_list.push(u);
            });
            answers.forEach(function (el) {
                var answer_row;
                $scope.answer_list.push(el);
                if (el.question_data_type === 'text') {
                    $scope.answer_list[$scope.answer_list.length - 1].summary_score = 'Text';
                } else if (el.answer_score === undefined) {
                    $scope.answer_list[$scope.answer_list.length - 1].summary_score = 'None';
                } else {
                    $scope.answer_list[$scope.answer_list.length - 1].summary_score = el.answer_score.value;
                }

                //TODO extract this into a function that is only called on export load or cache
                switch (el.question_mode) {
                    case 'interview':
                        console.log(el.interview_score.length);
                        if (el.interview_score.length > 0) {
                            el.interview_score.forEach(function (interview) {
                                mgaIntervieweeSrvc.get({_id: interview.interviewee_ID}, function (interviewee) {

                                    answer_row = {
                                        question_order: el.question_order,
                                        question_text: el.question_text,
                                        question_data_type: el.question_data_type,
                                        question_mode: el.question_mode,
                                        question_indicator_ID: el.question_indicator_ID,
                                        question_indicator: el.question_indicator,
                                        question_theme_ID: el.question_theme_ID,
                                        question_value_chain_ID: el.question_value_chain_ID,
                                        status: el.status,
                                        score_value: '',
                                        score_text: '',
                                        answer_text: '',
                                        comments: '',
                                        flags: '',
                                        interviewee_name: '',
                                        interviewee_email: '',
                                        interviewee_phone: '',
                                        interviewee_role: ''
                                    };
                                    if (interview.answer_score !== undefined) {
                                        answer_row.score_value = interview.value;
                                        answer_row.score_text = interview.option_text;
                                    }
                                    if (interview.interview_text !== undefined) {
                                        answer_row.answer_text = interview.interview_text
                                    }
                                    if (el.comments.length > 0) {
                                        var c = '';
                                        el.comments.forEach(function (element) {
                                            c = c + element.content + ' - ' + element.author_name + ' | '
                                        });
                                        answer_row.comments = c;
                                    }
                                    if (el.flags.length > 0) {
                                        var f = '';
                                        el.flags.forEach(function (element) {
                                            f = f + element.content + ' - ' + element.author_name + ' - addressed: ' + element.addressed + ' | '
                                        });
                                        answer_row.flags = f;
                                    }

                                    answer_row.interviewee_name = interviewee.firstName + ' ' + interviewee.lastName;
                                    answer_row.interviewee_email = interviewee.email;
                                    answer_row.interviewee_phone = interviewee.phone;
                                    answer_row.interviewee_role = interviewee.role;
                                    $scope.getArray.push(answer_row);
                                });
                            });

                        } else {
                            answer_row = {
                                question_order: el.question_order,
                                question_text: el.question_text,
                                question_data_type: el.question_data_type,
                                question_mode: el.question_mode,
                                question_indicator_ID: el.question_indicator_ID,
                                question_indicator: el.question_indicator,
                                question_theme_ID: el.question_theme_ID,
                                question_value_chain_ID: el.question_value_chain_ID,
                                status: el.status,
                                score_value: '',
                                score_text: '',
                                answer_text: '',
                                comments: '',
                                flags: '',
                                interviewee_name: '',
                                interviewee_email: '',
                                interviewee_phone: '',
                                interviewee_role: ''
                            };
                            $scope.getArray.push(answer_row);
                        }

                        break;
                    case 'desk_research':
                        answer_row = {
                            question_order: el.question_order,
                            question_text: el.question_text,
                            question_data_type: el.question_data_type,
                            question_mode: el.question_mode,
                            question_indicator_ID: el.question_indicator_ID,
                            question_indicator: el.question_indicator,
                            question_theme_ID: el.question_theme_ID,
                            question_value_chain_ID: el.question_value_chain_ID,
                            status: el.status,
                            score_value: '',
                            score_text: '',
                            answer_text: '',
                            comments: '',
                            flags: '',
                            interviewee_name: '',
                            interviewee_email: '',
                            interviewee_phone: '',
                            interviewee_role: ''
                        };
                        if (el.answer_score !== undefined) {
                            answer_row.score_value = el.answer_score.value;
                            answer_row.score_text = el.answer_score.option_text;
                        }
                        if (el.answer_text !== undefined) {
                            answer_row.answer_text = el.answer_text
                        }
                        if (el.comments.length > 0) {
                            var c = '';
                            el.comments.forEach(function (element) {
                                c = c + element.content + ' - ' + element.author_name + ' | '
                            });
                            answer_row.comments = c;
                        }
                        if (el.flags.length > 0) {
                            var f = '';
                            el.flags.forEach(function (element) {
                                f = f + element.content + ' - ' + element.author_name + ' - addressed: ' + element.addressed + ' | '
                            });
                            answer_row.flags = f;
                        }
                        $scope.getArray.push(answer_row);
                        break;
                    case 'secondary_source':
                        answer_row = {
                            question_order: el.question_order,
                            question_text: el.question_text,
                            question_data_type: el.question_data_type,
                            question_mode: el.question_mode,
                            question_indicator_ID: el.question_indicator_ID,
                            question_indicator: el.question_indicator,
                            question_theme_ID: el.question_theme_ID,
                            question_value_chain_ID: el.question_value_chain_ID,
                            status: el.status,
                            score_value: '',
                            score_text: '',
                            answer_text: '',
                            comments: '',
                            flags: '',
                            interviewee_name: '',
                            interviewee_email: '',
                            interviewee_phone: '',
                            interviewee_role: ''
                        };
                        if (el.answer_score !== undefined) {
                            answer_row.score_value = el.answer_score.value;
                        }
                        $scope.getArray.push(answer_row);
                        break;
                    default:
                        answer_row = {
                            question_order: el.question_order,
                            question_text: el.question_text,
                            question_data_type: el.question_data_type,
                            question_mode: el.question_mode,
                            question_indicator_ID: el.question_indicator_ID,
                            question_indicator: el.question_indicator,
                            question_theme_ID: el.question_theme_ID,
                            question_value_chain_ID: el.question_value_chain_ID,
                            status: el.status,
                            score_value: '',
                            score_text: '',
                            answer_text: '',
                            comments: '',
                            flags: '',
                            interviewee_name: '',
                            interviewee_email: '',
                            interviewee_phone: '',
                            interviewee_role: ''
                        };
                        $scope.getArray.push(answer_row);
                }

            });
            $scope.assessment = data;
        });
    });
    //$scope.createArray = function () {
    //    mgaAnswerSrvc.query({assessment_ID: $routeParams.assessment_ID}, function (answers) {
    //
    //    });
    //};
    $scope.submitAssessment = function () {
        var new_assessment_data = $scope.assessment;

        new_assessment_data.status = 'interview';
        new_assessment_data.questions_complete = 0;
        mgaAnswerSrvc.query({
            assessment_ID: $routeParams.assessment_ID,
            question_mode: 'interview'
        }, function (answers) {
            new_assessment_data.question_set_length = answers.length;
            mgaAssessmentMethodSrvc.updateAssessment(new_assessment_data).then(function () {
                mgaNotifier.notify('Assessment submited');
                $route.reload();
                //$location.path('/admin/assessment-admin');
            }, function (reason) {
                mgaNotifier.notify(reason);
            });

        });

    }
});
<commit_msg>fixed answer score not propegating to export on interviews<commit_after>'use strict';
//var angular;
/*jslint nomen: true regexp: true*/

angular.module('app').controller('nrgiAssessmentAdminDetailCtrl', function ($scope, $route, $routeParams, $location, mgaIdentitySrvc, mgaNotifier, mgaAssessmentSrvc, mgaAssessmentMethodSrvc, mgaUserListSrvc, mgaIntervieweeSrvc, mgaAnswerSrvc) {
    // filtering options
    $scope.sort_options = [
        {value: "question_order", text: "Sort by question number"},
        {value: "question_flow_order", text: "Sort by question order"},
        {value: "question_indicator_ID", text: "Sort by indicator"},
        {value: "question_mode", text: "Sorty by question mode"},
        {value: "question_data_type", text: "Sort by data type"},
        //{value: "status", text: "Sort by status"},
        {value: "status", text: "Sort by status"}
    ];
    $scope.sort_order = $scope.sort_options[0].value;

    $scope.current_user = mgaIdentitySrvc.currentUser;

    // pull assessment data and add
    mgaAssessmentSrvc.get({assessment_ID: $routeParams.assessment_ID}, function (data) {
        $scope.answer_list = [];
        mgaAnswerSrvc.query({assessment_ID: $routeParams.assessment_ID}, function (answers) {

            $scope.getArray = [{
                question_order: 'question_order',
                question_text: 'question_text',
                question_data_type: 'question_data_type',
                question_mode: 'question_mode',
                question_indicator_ID: 'question_indicator_ID',
                question_indicator: 'question_indicator',
                question_theme_ID: 'question_theme_ID',
                question_value_chain_ID: 'question_value_chain_ID',
                status: 'status',
                score_value: 'score_value',
                score_text: 'score_text',
                answer_text: 'answer_text',
                comments: 'comments',
                flags: 'flags',
                interviewee_name: 'interviewee_name',
                interviewee_email: 'interviewee_email',
                interviewee_phone: 'interviewee_phone',
                interviewee_role: 'interviewee_role'
            }];

            $scope.edited_by = mgaUserListSrvc.get({_id: data.modified[data.modified.length - 1].modified_by});
            $scope.user_list = [];
            data.users.forEach(function (el) {
                var u = mgaUserListSrvc.get({_id: el});
                $scope.user_list.push(u);
            });
            answers.forEach(function (el) {
                var answer_row;
                $scope.answer_list.push(el);
                if (el.question_data_type === 'text') {
                    $scope.answer_list[$scope.answer_list.length - 1].summary_score = 'Text';
                } else if (el.answer_score === undefined) {
                    $scope.answer_list[$scope.answer_list.length - 1].summary_score = 'None';
                } else {
                    $scope.answer_list[$scope.answer_list.length - 1].summary_score = el.answer_score.value;
                }

                //TODO extract this into a function that is only called on export load or cache
                switch (el.question_mode) {
                    case 'interview':
                        if (el.interview_score.length > 0) {
                            el.interview_score.forEach(function (interview) {
                                mgaIntervieweeSrvc.get({_id: interview.interviewee_ID}, function (interviewee) {

                                    answer_row = {
                                        question_order: el.question_order,
                                        question_text: el.question_text,
                                        question_data_type: el.question_data_type,
                                        question_mode: el.question_mode,
                                        question_indicator_ID: el.question_indicator_ID,
                                        question_indicator: el.question_indicator,
                                        question_theme_ID: el.question_theme_ID,
                                        question_value_chain_ID: el.question_value_chain_ID,
                                        status: el.status,
                                        score_value: '',
                                        score_text: '',
                                        answer_text: '',
                                        comments: '',
                                        flags: '',
                                        interviewee_name: '',
                                        interviewee_email: '',
                                        interviewee_phone: '',
                                        interviewee_role: ''
                                    };
                                    if (interview.value !== undefined) {
                                        answer_row.score_value = interview.value;
                                        answer_row.score_text = interview.option_text;
                                    }
                                    if (interview.interview_text !== undefined) {
                                        answer_row.answer_text = interview.interview_text
                                    }
                                    if (el.comments.length > 0) {
                                        var c = '';
                                        el.comments.forEach(function (element) {
                                            c = c + element.content + ' - ' + element.author_name + ' | '
                                        });
                                        answer_row.comments = c;
                                    }
                                    if (el.flags.length > 0) {
                                        var f = '';
                                        el.flags.forEach(function (element) {
                                            f = f + element.content + ' - ' + element.author_name + ' - addressed: ' + element.addressed + ' | '
                                        });
                                        answer_row.flags = f;
                                    }

                                    answer_row.interviewee_name = interviewee.firstName + ' ' + interviewee.lastName;
                                    answer_row.interviewee_email = interviewee.email;
                                    answer_row.interviewee_phone = interviewee.phone;
                                    answer_row.interviewee_role = interviewee.role;
                                    $scope.getArray.push(answer_row);
                                });
                            });

                        } else {
                            answer_row = {
                                question_order: el.question_order,
                                question_text: el.question_text,
                                question_data_type: el.question_data_type,
                                question_mode: el.question_mode,
                                question_indicator_ID: el.question_indicator_ID,
                                question_indicator: el.question_indicator,
                                question_theme_ID: el.question_theme_ID,
                                question_value_chain_ID: el.question_value_chain_ID,
                                status: el.status,
                                score_value: '',
                                score_text: '',
                                answer_text: '',
                                comments: '',
                                flags: '',
                                interviewee_name: '',
                                interviewee_email: '',
                                interviewee_phone: '',
                                interviewee_role: ''
                            };
                            $scope.getArray.push(answer_row);
                        }

                        break;
                    case 'desk_research':
                        answer_row = {
                            question_order: el.question_order,
                            question_text: el.question_text,
                            question_data_type: el.question_data_type,
                            question_mode: el.question_mode,
                            question_indicator_ID: el.question_indicator_ID,
                            question_indicator: el.question_indicator,
                            question_theme_ID: el.question_theme_ID,
                            question_value_chain_ID: el.question_value_chain_ID,
                            status: el.status,
                            score_value: '',
                            score_text: '',
                            answer_text: '',
                            comments: '',
                            flags: '',
                            interviewee_name: '',
                            interviewee_email: '',
                            interviewee_phone: '',
                            interviewee_role: ''
                        };
                        if (el.answer_score !== undefined) {
                            answer_row.score_value = el.answer_score.value;
                            answer_row.score_text = el.answer_score.option_text;
                        }
                        if (el.answer_text !== undefined) {
                            answer_row.answer_text = el.answer_text
                        }
                        if (el.comments.length > 0) {
                            var c = '';
                            el.comments.forEach(function (element) {
                                c = c + element.content + ' - ' + element.author_name + ' | '
                            });
                            answer_row.comments = c;
                        }
                        if (el.flags.length > 0) {
                            var f = '';
                            el.flags.forEach(function (element) {
                                f = f + element.content + ' - ' + element.author_name + ' - addressed: ' + element.addressed + ' | '
                            });
                            answer_row.flags = f;
                        }
                        $scope.getArray.push(answer_row);
                        break;
                    case 'secondary_source':
                        answer_row = {
                            question_order: el.question_order,
                            question_text: el.question_text,
                            question_data_type: el.question_data_type,
                            question_mode: el.question_mode,
                            question_indicator_ID: el.question_indicator_ID,
                            question_indicator: el.question_indicator,
                            question_theme_ID: el.question_theme_ID,
                            question_value_chain_ID: el.question_value_chain_ID,
                            status: el.status,
                            score_value: '',
                            score_text: '',
                            answer_text: '',
                            comments: '',
                            flags: '',
                            interviewee_name: '',
                            interviewee_email: '',
                            interviewee_phone: '',
                            interviewee_role: ''
                        };
                        if (el.answer_score !== undefined) {
                            answer_row.score_value = el.answer_score.value;
                        }
                        $scope.getArray.push(answer_row);
                        break;
                    default:
                        answer_row = {
                            question_order: el.question_order,
                            question_text: el.question_text,
                            question_data_type: el.question_data_type,
                            question_mode: el.question_mode,
                            question_indicator_ID: el.question_indicator_ID,
                            question_indicator: el.question_indicator,
                            question_theme_ID: el.question_theme_ID,
                            question_value_chain_ID: el.question_value_chain_ID,
                            status: el.status,
                            score_value: '',
                            score_text: '',
                            answer_text: '',
                            comments: '',
                            flags: '',
                            interviewee_name: '',
                            interviewee_email: '',
                            interviewee_phone: '',
                            interviewee_role: ''
                        };
                        $scope.getArray.push(answer_row);
                }

            });
            $scope.assessment = data;
        });
    });
    //$scope.createArray = function () {
    //    mgaAnswerSrvc.query({assessment_ID: $routeParams.assessment_ID}, function (answers) {
    //
    //    });
    //};
    $scope.submitAssessment = function () {
        var new_assessment_data = $scope.assessment;

        new_assessment_data.status = 'interview';
        new_assessment_data.questions_complete = 0;
        mgaAnswerSrvc.query({
            assessment_ID: $routeParams.assessment_ID,
            question_mode: 'interview'
        }, function (answers) {
            new_assessment_data.question_set_length = answers.length;
            mgaAssessmentMethodSrvc.updateAssessment(new_assessment_data).then(function () {
                mgaNotifier.notify('Assessment submited');
                $route.reload();
                //$location.path('/admin/assessment-admin');
            }, function (reason) {
                mgaNotifier.notify(reason);
            });

        });

    }
});
<|endoftext|>


<commit_before>'use strict';

angular.module('app')
    .controller('rgiMoveAssessmentDialogCtrl', function (
        $scope,
        rgiUserSrvc,
        rgiDialogFactory
    ) {
        var getUserInfo = function(user) {
            return user.firstName + " " + user.lastName + ' (' + user.role + ')';
        };

        rgiUserSrvc.get({_id: $scope.$parent.assessment.edit_control}, function (control_profile) {
            var workflowOptions = [],
                assessment = $scope.$parent.assessment,
                stats = $scope.$parent.assessment_counters;

            if (assessment.status === 'trial_submitted') {
                if (stats.flagged !== 0) {
                    workflowOptions.push({
                        text: 'Send back to ' + getUserInfo(control_profile) + ' for review.',
                        value: control_profile.role + '_trial'
                    });
                } else if (stats.approved === stats.length) {
                    workflowOptions.push({
                        text: 'Allow ' + getUserInfo(control_profile) + ' to continue assessment.',
                        value: 'assigned_' + control_profile.role
                    });
                }
            } else {
                workflowOptions.push({
                    text: 'Send back to ' + getUserInfo(control_profile) + ' for review.',
                    value: 'review_' + control_profile.role
                });

                if ((control_profile.role === 'researcher') && (stats.flagged === 0) && assessment.reviewer_ID) {
                    if (assessment.first_pass) {
                        workflowOptions.push({
                            text: 'Move to ' + getUserInfo(assessment.reviewer_ID) + '.',
                            value: assessment.reviewer_ID.role + '_trial'
                        });
                    } else {
                        workflowOptions.push({
                            text: 'Move to ' + getUserInfo(assessment.reviewer_ID) + '.',
                            value: 'assigned_' + assessment.reviewer_ID.role
                        });
                    }
                } else if ((control_profile.role === 'reviewer') && (stats.flagged === 0)) {
                    workflowOptions.push({
                        text: 'Move to ' + getUserInfo(assessment.researcher_ID) + '.',
                        value: 'assigned_' + assessment.researcher_ID.role
                    });
                }
            }

            if ((stats.flagged === 0) && (stats.finalized === stats.length) && (assessment.status !== 'approved')) {
                workflowOptions.push({
                    text: 'Approve assessment',
                    value: 'approved'
                });
            }

            if (assessment.status === 'approved') {
                workflowOptions.push({
                    text: 'Move to internal review',
                    value: 'internal_review'
                });
                workflowOptions.push({
                    text: 'Move to external review',
                    value: 'external_review'
                });
                workflowOptions.push({
                    text: 'Final approval',
                    value: 'final_approval'
                });
            }

            $scope.workflow_opts = workflowOptions;
        });

        $scope.moveAssessment = function () {
            rgiDialogFactory.assessmentMoveConfirm($scope);
        };
    });
<commit_msg>refactor the 'Move Assessment Dialog' controller<commit_after>'use strict';

angular.module('app')
    .controller('rgiMoveAssessmentDialogCtrl', function (
        $scope,
        rgiUserSrvc,
        rgiDialogFactory
    ) {
        var getUserInfo = function(user) {
            return user.firstName + " " + user.lastName + ' (' + user.role + ')';
        };

        rgiUserSrvc.get({_id: $scope.$parent.assessment.edit_control}, function (profile) {
            var workflowOptions = [],
                assessment = $scope.$parent.assessment,
                stats = $scope.$parent.assessment_counters,
                addOption = function(text, value) {
                    workflowOptions.push({text: text, value: value});
                };

            if (assessment.status === 'trial_submitted') {
                if (stats.flagged !== 0) {
                    addOption('Send back to ' + getUserInfo(profile) + ' for review.', profile.role + '_trial');
                } else if (stats.approved === stats.length) {
                    addOption('Allow ' + getUserInfo(profile) + ' to continue assessment.', 'assigned_' + profile.role);
                }
            } else {
                addOption('Send back to ' + getUserInfo(profile) + ' for review.', 'review_' + profile.role);
                if ((profile.role === 'researcher') && (stats.flagged === 0) && assessment.reviewer_ID) {
                    var reviewer = assessment.reviewer_ID;

                    if (assessment.first_pass) {
                        addOption('Move to ' + getUserInfo(reviewer) + '.', reviewer.role + '_trial');
                    } else {
                        addOption('Move to ' + getUserInfo(reviewer) + '.', 'assigned_' + reviewer.role);
                    }
                } else if ((profile.role === 'reviewer') && (stats.flagged === 0)) {
                    var researcher = assessment.researcher_ID;
                    addOption('Move to ' + getUserInfo(researcher) + '.', 'assigned_' + researcher.role);
                }
            }

            if ((stats.flagged === 0) && (stats.finalized === stats.length) && (assessment.status !== 'approved')) {
                addOption('Approve assessment', 'approved');
            }

            if (assessment.status === 'approved') {
                addOption('Move to internal review', 'internal_review');
                addOption('Move to external review', 'external_review');
                addOption('Final approval', 'final_approval');
            }

            $scope.workflow_opts = workflowOptions;
        });

        $scope.moveAssessment = function () {
            rgiDialogFactory.assessmentMoveConfirm($scope);
        };
    });
<|endoftext|>


<commit_before>/* Copyright (c) 2012-2013 The TagSpaces Authors. All rights reserved.
 * Use of this source code is governed by a AGPL3 license that
 * can be found in the LICENSE file. */
define(function(require, exports, module) {
"use strict";

	console.log("Loading core.ui.js ...");

	var TSCORE = require("tscore");

    var editor = undefined;
	var formatter = undefined;

	var fileContent = undefined;

	var showAlertDialog = function(message, title) {
	    if (!title) { title = 'Alert'; }
	    if (!message) { message = 'No Message to Display.'; }

	    var alertModal =
	      $('
' +
	          '
' +
	            '×' +
	            '

' +
	          '
' +
              '

' +
	          '
' +
	            '<button id="okButton" class="btn btn-primary">Ok</button>' +
	          '
' +
	        '
');

        alertModal.find('h4').text(title);
        alertModal.find('.lead').text(message);
	    alertModal.find('#okButton').click(function(event) {
	      alertModal.modal('hide');
	    });

	    alertModal.modal('show');
	}

	var showConfirmDialog = function(title, message, callback) {
	    if (!title) { title = 'Confirm'; }
	    if (!message) { message = 'No Message to Display.'; }

	    var confirmModal =
	      $('
' +
	          '
' +
	            '×' +
	            '

' +
	          '
' +
	          '

' +
	          '
' +
	            '<button class="btn" data-dismiss="modal">Cancel</button>' +
	            '<button id="okButton" class="btn btn-primary">Ok</button>' +
	          '
' +
	        '
');

        confirmModal.find('h4').text(title);
	    confirmModal.find('.lead').text(message);
	    confirmModal.find('#okButton').click(function(event) {
	      callback();
	      confirmModal.modal('hide');
	    });

	    confirmModal.modal('show');
	};

    var showFileCreateDialog = function() {
        fileContent = TSCORE.Config.getNewTextFileContent(); // Default new file in text file
        $( "#newFileName" ).val(".txt");
        $( '#dialogFileCreate' ).modal({show: true});
        $( '#txtFileTypeButton' ).button('toggle');
    }

    var showFileRenameDialog = function() {
        $( "#renamedFileName" ).val(TSCORE.TagUtils.extractFileName(TSCORE.selectedFiles[0]));
        $( '#dialogFileRename' ).modal({show: true});
    }

    var showTagEditDialog = function() {
        $( "#newTagName" ).val(TSCORE.selectedTag);
        $( '#dialogEditTag' ).modal({show: true});
    }

	var initUI = function() {

	    $( "#openAboutBox" ).tooltip();

	    $( "#toggleLeftPanel" ).click(function() {
			TSCORE.toggleLeftPanel();
	    });

		$( "#testAlertButton" ).click(function() {
			TSCORE.showAlertDialog("test1","test2");
			TSCORE.showConfirmDialog("test1","test2", function() {alert("test")});
		})

	    $( "#txtFileTypeButton" ).click(function(e) {
            // Fixes reloading of the application by click
            e.preventDefault();

	        fileContent = TSCORE.Config.getNewTextFileContent();
	        //Leave the filename as it is by no extension
	        if($( "#newFileName" ).val().lastIndexOf(".")>=0) {
	            $( "#newFileName" ).val($( "#newFileName" ).val().substring(0,$( "#newFileName" ).val().lastIndexOf("."))+".txt");
	        }
	    });

	    $( "#htmlFileTypeButton" ).click(function(e) {
            // Fixes reloading of the application by click
            e.preventDefault();

	        fileContent = TSCORE.Config.getNewHTMLFileContent();
	        //Leave the filename as it is by no extension
	        if($( "#newFileName" ).val().lastIndexOf(".")>=0) {
	            $( "#newFileName" ).val($( "#newFileName" ).val().substring(0,$( "#newFileName" ).val().lastIndexOf("."))+".html");
	        }
	    });

	    $( "#mdFileTypeButton" ).click(function(e) {
            // Fixes reloading of the application by click
            e.preventDefault();

	        fileContent = TSCORE.Config.getNewMDFileContent();
	        //Leave the filename as it is by no extension
	        if($( "#newFileName" ).val().lastIndexOf(".")>=0) {
	            $( "#newFileName" ).val($( "#newFileName" ).val().substring(0,$( "#newFileName" ).val().lastIndexOf("."))+".md");
	        }
	    });

	    $( '#fileCreateConfirmButton' ).click(function() {
            var bValid = true;
//                bValid = bValid && checkLength( newFileName, "filename", 4, 200 );

            if(TSCORE.fileExists($( "#newFileName" ).val())) {
                updateTips("File already exists.");
                bValid = false;
            }
            if ( bValid ) {
                TSCORE.IO.saveTextFile(TSCORE.currentPath+TSCORE.TagUtils.DIR_SEPARATOR+$( "#newFileName" ).val(),fileContent);
                TSCORE.IO.listDirectory(TSCORE.currentPath);
            }
        });

        $( '#renameFileButton' ).click(function() {
            var bValid = true;
    //        bValid = bValid && checkLength( $( "#renamedFileName" ).val(), "filename", 3, 200 );
    //        bValid = bValid && checkRegexp( renamedFileName, /^[a-z]([0-9a-z_.])+$/i, "Filename may consist of a-z, 0-9, underscores, begin with a letter." );
            if ( bValid ) {
                var containingDir = TSCORE.TagUtils.extractContainingDirectoryPath(TSCORE.selectedFiles[0]);
                TSCORE.IO.renameFile(
                        TSCORE.selectedFiles[0],
                        containingDir+TSCORE.TagUtils.DIR_SEPARATOR+$( "#renamedFileName" ).val()
                    );
            }
        });

        // Edit Tag Dialog

	    $( "#plainTagTypeButton" ).click(function(e) {
            // Fixes reloading of the application by click
            e.preventDefault();

	        TSCORE.selectedTag, $( "#newTagName" ).datepicker( "destroy" ).val("");
	    });

	    $( "#dateTagTypeButton" ).click(function(e) {
            // Fixes reloading of the application by click
            e.preventDefault();

	        TSCORE.selectedTag, $( "#newTagName" ).datepicker({
	            showWeek: true,
	            firstDay: 1,
	            dateFormat: "yymmdd"
	        });
	    });

	    $( "#currencyTagTypeButton" ).click(function(e) {
            // Fixes reloading of the application by click
            e.preventDefault();

	        TSCORE.selectedTag, $( "#newTagName" ).datepicker( "destroy" ).val("XEUR")
	    });

        $( "#editTagButton" ).click(function() {
            TSCORE.TagUtils.renameTag(TSCORE.selectedFiles[0], TSCORE.selectedTag, $( "#newTagName" ).val());
            TSCORE.IO.listDirectory(TSCORE.currentPath);
        });

	    // End Edit Tag Dialog

	    $( "#aboutDialogBack" ).click(function() {
            $("#aboutIframe").attr("src","about.html");
        });

        // Open About Dialog
        $( "#openAboutBox" ).click(function() {
           $('#dialogAbout').modal('show');
        });

        // Open Options Dialog
        $( "#openOptions" ).click(function() {
            require(['tsoptions'], function () {
                $('#dialogOptions').modal('show');
            });
        });

	    // Advanced Settings
        $( "#aboutDialogSettings" ).click(function() {
            $('#dialogOptions').modal('hide');
            require(['jsoneditor'], function () {
                editor = new JSONEditor(document.getElementById("settingsEditor"));
                formatter = new JSONFormatter(document.getElementById("settingsPlainJSON"));
                $("#settingsPlainJSON").hide();
                editor.set(TSCORE.Config.Settings);
                $('#dialogAdvancedSetting').modal('show');
            });
        });

        $( "#editorButton" ).click(function() {
            if($("#settingsEditor").is(":hidden") ) {
                $("#settingsPlainJSON").hide();
                $("#settingsEditor").show();
                editor.set(formatter.get());
            }
        });

        $( "#importExportButton" ).click(function() {
            if($("#settingsPlainJSON").is(":hidden") ) {
                formatter.set(editor.get());
                $("#settingsPlainJSON").show();
                $("#settingsEditor").hide();
            }
        });

        $( "#deffaultSettingsButton" ).click(function() {
            TSCORE.showConfirmDialog(
                "Warning",
                "Are you sure you want to restore the default application settings?\n"+
                +"All manually made changes such as tags and taggroups will be lost.",
                function() {
                    TSCORE.Config.Settings = TSCORE.Config.DefaultSettings;
                    TSCORE.Config.saveSettings();
                    TSCORE.reloadUI();
                    console.log("Default settings loaded.");
                }
            );
        });

        $( "#saveSettingsButton" ).click(function() {
            TSCORE.Config.Settings = editor.get();
            TSCORE.Config.saveSettings();
            TSCORE.reloadUI();
        });
        // End Advanced Settings

	    // File Menu
        $( "#fileMenuAddTag" ).click( function() {
            TSCORE.showAddTagsDialog();
        });

        $( "#fileMenuOpenFile" ).click( function() {
            TSCORE.FileOpener.openFile(TSCORE.selectedFiles[0]);
        });

        $( "#fileMenuOpenDirectory" ).click( function() {
            TSCORE.IO.openDirectory(TSCORE.currentPath);
        });

        $( "#fileMenuRenameFile" ).click( function() {
            TSCORE.showFileRenameDialog();
        });

        $( "#fileMenuDeleteFile" ).click( function() {
            console.log("Deleting file...");
            TSCORE.showConfirmDialog(
                "Delete File(s)",
                "These items will be permanently deleted and cannot be recovered. Are you sure?",
                function() {
                    TSCORE.IO.deleteElement(TSCORE.selectedFiles[0]);
                    TSCORE.IO.listDirectory(TSCORE.currentPath);
                }
            );
        });
        // End File Menu

	}

	var hideAllDropDownMenus = function() {
		$('BODY')
			.find('.dropdown-menu').hide().end()
			.find('[data-dropdown]').removeClass('dropdown-open');
	}

    // Public API definition
	exports.initUI 					= initUI;
	exports.showAlertDialog 		= showAlertDialog;
	exports.showConfirmDialog 		= showConfirmDialog;
	exports.showFileRenameDialog    = showFileRenameDialog;
	exports.showFileCreateDialog    = showFileCreateDialog;
    exports.showTagEditDialog       = showTagEditDialog;
	exports.hideAllDropDownMenus	= hideAllDropDownMenus;

});<commit_msg>Add handler for opening a new instance of TagSpaces<commit_after>/* Copyright (c) 2012-2013 The TagSpaces Authors. All rights reserved.
 * Use of this source code is governed by a AGPL3 license that
 * can be found in the LICENSE file. */
define(function(require, exports, module) {
"use strict";

	console.log("Loading core.ui.js ...");

	var TSCORE = require("tscore");

    var editor = undefined;
	var formatter = undefined;

	var fileContent = undefined;

	var showAlertDialog = function(message, title) {
	    if (!title) { title = 'Alert'; }
	    if (!message) { message = 'No Message to Display.'; }

	    var alertModal =
	      $('
' +
	          '
' +
	            '×' +
	            '

' +
	          '
' +
              '

' +
	          '
' +
	            '<button id="okButton" class="btn btn-primary">Ok</button>' +
	          '
' +
	        '
');

        alertModal.find('h4').text(title);
        alertModal.find('.lead').text(message);
	    alertModal.find('#okButton').click(function(event) {
	      alertModal.modal('hide');
	    });

	    alertModal.modal('show');
	}

	var showConfirmDialog = function(title, message, callback) {
	    if (!title) { title = 'Confirm'; }
	    if (!message) { message = 'No Message to Display.'; }

	    var confirmModal =
	      $('
' +
	          '
' +
	            '×' +
	            '

' +
	          '
' +
	          '

' +
	          '
' +
	            '<button class="btn" data-dismiss="modal">Cancel</button>' +
	            '<button id="okButton" class="btn btn-primary">Ok</button>' +
	          '
' +
	        '
');

        confirmModal.find('h4').text(title);
	    confirmModal.find('.lead').text(message);
	    confirmModal.find('#okButton').click(function(event) {
	      callback();
	      confirmModal.modal('hide');
	    });

	    confirmModal.modal('show');
	};

    var showFileCreateDialog = function() {
        fileContent = TSCORE.Config.getNewTextFileContent(); // Default new file in text file
        $( "#newFileName" ).val(".txt");
        $( '#dialogFileCreate' ).modal({show: true});
        $( '#txtFileTypeButton' ).button('toggle');
    }

    var showFileRenameDialog = function() {
        $( "#renamedFileName" ).val(TSCORE.TagUtils.extractFileName(TSCORE.selectedFiles[0]));
        $( '#dialogFileRename' ).modal({show: true});
    }

    var showTagEditDialog = function() {
        $( "#newTagName" ).val(TSCORE.selectedTag);
        $( '#dialogEditTag' ).modal({show: true});
    }

	var initUI = function() {

	    $( "#openAboutBox" ).tooltip();

	    $( "#toggleLeftPanel" ).click(function() {
			TSCORE.toggleLeftPanel();
	    });

		$( "#testAlertButton" ).click(function() {
			TSCORE.showAlertDialog("test1","test2");
			TSCORE.showConfirmDialog("test1","test2", function() {alert("test")});
		})

	    $( "#txtFileTypeButton" ).click(function(e) {
            // Fixes reloading of the application by click
            e.preventDefault();

	        fileContent = TSCORE.Config.getNewTextFileContent();
	        //Leave the filename as it is by no extension
	        if($( "#newFileName" ).val().lastIndexOf(".")>=0) {
	            $( "#newFileName" ).val($( "#newFileName" ).val().substring(0,$( "#newFileName" ).val().lastIndexOf("."))+".txt");
	        }
	    });

	    $( "#htmlFileTypeButton" ).click(function(e) {
            // Fixes reloading of the application by click
            e.preventDefault();

	        fileContent = TSCORE.Config.getNewHTMLFileContent();
	        //Leave the filename as it is by no extension
	        if($( "#newFileName" ).val().lastIndexOf(".")>=0) {
	            $( "#newFileName" ).val($( "#newFileName" ).val().substring(0,$( "#newFileName" ).val().lastIndexOf("."))+".html");
	        }
	    });

	    $( "#mdFileTypeButton" ).click(function(e) {
            // Fixes reloading of the application by click
            e.preventDefault();

	        fileContent = TSCORE.Config.getNewMDFileContent();
	        //Leave the filename as it is by no extension
	        if($( "#newFileName" ).val().lastIndexOf(".")>=0) {
	            $( "#newFileName" ).val($( "#newFileName" ).val().substring(0,$( "#newFileName" ).val().lastIndexOf("."))+".md");
	        }
	    });

	    $( '#fileCreateConfirmButton' ).click(function() {
            var bValid = true;
//                bValid = bValid && checkLength( newFileName, "filename", 4, 200 );

            if(TSCORE.fileExists($( "#newFileName" ).val())) {
                updateTips("File already exists.");
                bValid = false;
            }
            if ( bValid ) {
                TSCORE.IO.saveTextFile(TSCORE.currentPath+TSCORE.TagUtils.DIR_SEPARATOR+$( "#newFileName" ).val(),fileContent);
                TSCORE.IO.listDirectory(TSCORE.currentPath);
            }
        });

        $( '#renameFileButton' ).click(function() {
            var bValid = true;
    //        bValid = bValid && checkLength( $( "#renamedFileName" ).val(), "filename", 3, 200 );
    //        bValid = bValid && checkRegexp( renamedFileName, /^[a-z]([0-9a-z_.])+$/i, "Filename may consist of a-z, 0-9, underscores, begin with a letter." );
            if ( bValid ) {
                var containingDir = TSCORE.TagUtils.extractContainingDirectoryPath(TSCORE.selectedFiles[0]);
                TSCORE.IO.renameFile(
                        TSCORE.selectedFiles[0],
                        containingDir+TSCORE.TagUtils.DIR_SEPARATOR+$( "#renamedFileName" ).val()
                    );
            }
        });

        // Edit Tag Dialog

	    $( "#plainTagTypeButton" ).click(function(e) {
            // Fixes reloading of the application by click
            e.preventDefault();

	        TSCORE.selectedTag, $( "#newTagName" ).datepicker( "destroy" ).val("");
	    });

	    $( "#dateTagTypeButton" ).click(function(e) {
            // Fixes reloading of the application by click
            e.preventDefault();

	        TSCORE.selectedTag, $( "#newTagName" ).datepicker({
	            showWeek: true,
	            firstDay: 1,
	            dateFormat: "yymmdd"
	        });
	    });

	    $( "#currencyTagTypeButton" ).click(function(e) {
            // Fixes reloading of the application by click
            e.preventDefault();

	        TSCORE.selectedTag, $( "#newTagName" ).datepicker( "destroy" ).val("XEUR")
	    });

        $( "#editTagButton" ).click(function() {
            TSCORE.TagUtils.renameTag(TSCORE.selectedFiles[0], TSCORE.selectedTag, $( "#newTagName" ).val());
            TSCORE.IO.listDirectory(TSCORE.currentPath);
        });

	    // End Edit Tag Dialog

        $( "#startNewInstanceBack" ).click(function() {
            window.open(window.location.href,'_blank');
        });

	    $( "#aboutDialogBack" ).click(function() {
            $("#aboutIframe").attr("src","about.html");
        });

        // Open About Dialog
        $( "#openAboutBox" ).click(function() {
           $('#dialogAbout').modal('show');
        });

        // Open Options Dialog
        $( "#openOptions" ).click(function() {
            require(['tsoptions'], function () {
                $('#dialogOptions').modal('show');
            });
        });

	    // Advanced Settings
        $( "#aboutDialogSettings" ).click(function() {
            $('#dialogOptions').modal('hide');
            require(['jsoneditor'], function () {
                editor = new JSONEditor(document.getElementById("settingsEditor"));
                formatter = new JSONFormatter(document.getElementById("settingsPlainJSON"));
                $("#settingsPlainJSON").hide();
                editor.set(TSCORE.Config.Settings);
                $('#dialogAdvancedSetting').modal('show');
            });
        });

        $( "#editorButton" ).click(function() {
            if($("#settingsEditor").is(":hidden") ) {
                $("#settingsPlainJSON").hide();
                $("#settingsEditor").show();
                editor.set(formatter.get());
            }
        });

        $( "#importExportButton" ).click(function() {
            if($("#settingsPlainJSON").is(":hidden") ) {
                formatter.set(editor.get());
                $("#settingsPlainJSON").show();
                $("#settingsEditor").hide();
            }
        });

        $( "#deffaultSettingsButton" ).click(function() {
            TSCORE.showConfirmDialog(
                "Warning",
                "Are you sure you want to restore the default application settings?\n"+
                +"All manually made changes such as tags and taggroups will be lost.",
                function() {
                    TSCORE.Config.Settings = TSCORE.Config.DefaultSettings;
                    TSCORE.Config.saveSettings();
                    TSCORE.reloadUI();
                    console.log("Default settings loaded.");
                }
            );
        });

        $( "#saveSettingsButton" ).click(function() {
            TSCORE.Config.Settings = editor.get();
            TSCORE.Config.saveSettings();
            TSCORE.reloadUI();
        });
        // End Advanced Settings

	    // File Menu
        $( "#fileMenuAddTag" ).click( function() {
            TSCORE.showAddTagsDialog();
        });

        $( "#fileMenuOpenFile" ).click( function() {
            TSCORE.FileOpener.openFile(TSCORE.selectedFiles[0]);
        });

        $( "#fileMenuOpenDirectory" ).click( function() {
            TSCORE.IO.openDirectory(TSCORE.currentPath);
        });

        $( "#fileMenuRenameFile" ).click( function() {
            TSCORE.showFileRenameDialog();
        });

        $( "#fileMenuDeleteFile" ).click( function() {
            console.log("Deleting file...");
            TSCORE.showConfirmDialog(
                "Delete File(s)",
                "These items will be permanently deleted and cannot be recovered. Are you sure?",
                function() {
                    TSCORE.IO.deleteElement(TSCORE.selectedFiles[0]);
                    TSCORE.IO.listDirectory(TSCORE.currentPath);
                }
            );
        });
        // End File Menu

	}

	var hideAllDropDownMenus = function() {
		$('BODY')
			.find('.dropdown-menu').hide().end()
			.find('[data-dropdown]').removeClass('dropdown-open');
	}

    // Public API definition
	exports.initUI 					= initUI;
	exports.showAlertDialog 		= showAlertDialog;
	exports.showConfirmDialog 		= showConfirmDialog;
	exports.showFileRenameDialog    = showFileRenameDialog;
	exports.showFileCreateDialog    = showFileCreateDialog;
    exports.showTagEditDialog       = showTagEditDialog;
	exports.hideAllDropDownMenus	= hideAllDropDownMenus;

});<|endoftext|>


<commit_before>/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global require, exports */

(function () {
    "use strict";

    var async = require("async");
    var process_runner = require("./process_runner.js");
    var config = require("./config.js");
    var utils = require("./utils.js");
    var fs = require("fs");
    var os = require("os");

    var restartUDHCPD = function (callback) {
        //service udhcpd restart 2>&1 >/dev/null
        process_runner.exec("service", ["udhcpd", "restart"], callback);
    };

    var restartAPD = function (callback) {
        //service hostapd restart 2>&1 >/dev/null
        process_runner.exec("service", ["hostapd", "restart"], callback);
    };

    var loadAPConfTemplate = function (callback) {
        fs.readFile(config.HOSTAPD_CONF_TEMPLATE_PATH, {encoding: "utf8"}, callback);
    };

    var createAPConf = function (ssid, template) {
        template.replace("{{SSID}}", ssid);
        return template;
    };

    var writeAPConf = function (data, callback) {
        fs.writeFile(config.HOSTAPD_CONF_PATH, data, callback);
    };

    //todo: we may want to cache the results of this, so we dont have to read a file
    //everytime this api is called. Might not be a big deal though, since there should only ever be
    //one person accessing the site
    var readRestrictedAccessList = function (callback) {
        fs.readFile(config.HOSTAPD_RESTRICTED_ADDRESSES_PATH,
                    {encoding: "utf8"},
            function (err, data) {
                var addresses = data.split(os.EOL);
                callback(null, addresses);
            }
            );
    };

    var saveRestrictedAccessList = function (addresses, callback) {
        var tmp = addresses.join(os.EOL);
        fs.writeFile(config.HOSTAPD_RESTRICTED_ADDRESSES_PATH, tmp, callback);
    };

    var updateRestrictedAccessList = function (addresses, callback) {
        //todo: confirm whether we need to restart service after updating access list
        async.series(
            [
                function (callback) {saveRestrictedAccessList(addresses, callback); },
                restartAPD
            ],
            function (err, out) {
                if (err) {
                    callback(err);
                    return;
                }
                callback(null, out);
            }
        );
    };

    var updateAPConf = function (ssid, callback) {

        var _generateAPConf = function (err, data, callback) {

            console.log("_generateAPConf", err, data);
            var conf = createAPConf(ssid, data);
            callback(null, conf);
        };

        //todo: do we need to restart restartUDHCPD (it is slow)
        async.waterfall(
            [
                loadAPConfTemplate,
                _generateAPConf,
                writeAPConf,
                restartAPD,
                restartUDHCPD
            ],
            function (err, out) {
                if (err) {
                    callback(err);
                    return;
                }
                callback(null, out);
            }
        );
    };

    var updateAccessPoint = function (ssid, address, callback) {

        if (!utils.isValidMacAddress(address)) {
            callback("Invalid mac address");
            return;
        }

        if (!ssid || !ssid.length) {
            callback("Invalid SSID.");
            return;
        }

        //note, the arguments are not passed on the shell, so we don't have to worry
        //about injection (although the script being called does)
        //http://stackoverflow.com/questions/15168071/how-secure-is-using-execfile-for-bash-scripts
        async.series(
            [
                function (callback) {process_runner.exec("ifconfig", [config.ACCESS_POINT_INTERFACE, "down"], callback); },
                function (callback) {process_runner.exec("ifconfig", [config.ACCESS_POINT_INTERFACE, "hw", "ether", address], callback); },
                function (callback) {process_runner.exec("ifconfig", [config.ACCESS_POINT_INTERFACE, "up"], callback); },
                function (callback) {updateAPConf(ssid, callback); },
                restartAPD,
                restartUDHCPD
            ],
            function (err, out) {
                if (err) {
                    callback(err);
                    return;
                }
                callback(null, out);
            }
        );
    };

    exports.updateAccessPoint = updateAccessPoint;
}());<commit_msg>fixing some bugs<commit_after>/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global require, exports */

(function () {
    "use strict";

    var async = require("async");
    var process_runner = require("./process_runner.js");
    var config = require("./config.js");
    var utils = require("./utils.js");
    var fs = require("fs");
    var os = require("os");

    var restartUDHCPD = function (callback) {
        //service udhcpd restart 2>&1 >/dev/null
        process_runner.exec("service", ["udhcpd", "restart"], callback);
    };

    var restartAPD = function (callback) {
        //service hostapd restart 2>&1 >/dev/null
        process_runner.exec("service", ["hostapd", "restart"], callback);
    };

    var loadAPConfTemplate = function (callback) {
        fs.readFile(config.HOSTAPD_CONF_TEMPLATE_PATH, {encoding: "utf8"}, callback);
    };

    var createAPConf = function (ssid, template) {
        template.replace("{{SSID}}", ssid);
        return template;
    };

    var writeAPConf = function (data, callback) {
        fs.writeFile(config.HOSTAPD_CONF_PATH, data, callback);
    };

    //todo: we may want to cache the results of this, so we dont have to read a file
    //everytime this api is called. Might not be a big deal though, since there should only ever be
    //one person accessing the site
    var readRestrictedAccessList = function (callback) {
        fs.readFile(config.HOSTAPD_RESTRICTED_ADDRESSES_PATH,
                    {encoding: "utf8"},
            function (err, data) {
                var addresses = data.split(os.EOL);
                callback(null, addresses);
            }
            );
    };

    var saveRestrictedAccessList = function (addresses, callback) {
        var tmp = addresses.join(os.EOL);
        fs.writeFile(config.HOSTAPD_RESTRICTED_ADDRESSES_PATH, tmp, callback);
    };

    var updateRestrictedAccessList = function (addresses, callback) {
        //todo: confirm whether we need to restart service after updating access list
        async.series(
            [
                function (callback) {saveRestrictedAccessList(addresses, callback); },
                restartAPD
            ],
            function (err, out) {
                if (err) {
                    callback(err);
                    return;
                }
                callback(null, out);
            }
        );
    };

    var updateAPConf = function (ssid, callback) {

        var _generateAPConf = function (err, data, callback) {

            console.log("_generateAPConf");
            console.log("err:", err);
            console.log("data : ", data);
            var conf = createAPConf(ssid, data);
            callback(null, conf);
        };

        //todo: do we need to restart restartUDHCPD (it is slow)
        async.waterfall(
            [
                loadAPConfTemplate,
                _generateAPConf,
                writeAPConf,
                restartAPD,
                restartUDHCPD
            ],
            function (err, out) {
                if (err) {
                    callback(err);
                    return;
                }
                callback(null, out);
            }
        );
    };

    var updateAccessPoint = function (ssid, address, callback) {

        if (!utils.isValidMacAddress(address)) {
            callback("Invalid mac address");
            return;
        }

        if (!ssid || !ssid.length) {
            callback("Invalid SSID.");
            return;
        }

        //note, the arguments are not passed on the shell, so we don't have to worry
        //about injection (although the script being called does)
        //http://stackoverflow.com/questions/15168071/how-secure-is-using-execfile-for-bash-scripts
        async.series(
            [
                function (callback) {process_runner.exec("ifconfig", [config.ACCESS_POINT_INTERFACE, "down"], callback); },
                function (callback) {process_runner.exec("ifconfig", [config.ACCESS_POINT_INTERFACE, "hw", "ether", address], callback); },
                function (callback) {process_runner.exec("ifconfig", [config.ACCESS_POINT_INTERFACE, "up"], callback); },
                function (callback) {updateAPConf(ssid, callback); },
                restartAPD,
                restartUDHCPD
            ],
            function (err, out) {
                if (err) {
                    callback(err);
                    return;
                }
                callback(null, out);
            }
        );
    };

    exports.updateAccessPoint = updateAccessPoint;
}());<|endoftext|>


<commit_before>function GM_openInTab(_url) {
  self.port.emit("GM_openInTab", _url);
};

function GM_setValue(_name, _value) {
  localStorage[_name] = _value;
};

function GM_getValue(_name, _default) {
  if (localStorage[_name] === null && _default === null) return undefined;
  return localStorage[_name] || _default;
};

function GM_deleteValue(_name) {
  localStorage.removeItem(_name);
};

function GM_listValues() {
  return Object.keys(localStorage);
};

function GM_setClipboard(_text) {
//   Break on Firefox mobile
//   self.port.emit("GM_setClipboard", _text);
};

//Deprecated
function GM_log(_message) {
  console.log(_message);
};

function GM_xmlhttpRequest(_details) {
  //Ugly hack? Race condition? Memory leak?
  _onload = _details.onload;
  self.port.emit("GM_xmlhttpRequest", _details);
};

self.port.on("callback_GM_xmlhttpRequest", function(_response) {
  _onload(_response);
});

function GM_addStyle(_css) {
  self.port.emit("GM_addStyle", _css);
}

var GM_info = new Object();
GM_info.version = '1.1.5';
GM_info.scriptWillUpdate = true;

//To do
function GM_registerMenuCommand(_caption, _commandFunc, _accessKey) {
  return null;
}

self.port.on("load-userscript", function(_script) {
  eval(_script);
});<commit_msg>Fix GM_info<commit_after>function GM_openInTab(_url) {
  self.port.emit("GM_openInTab", _url);
};

function GM_setValue(_name, _value) {
  localStorage[_name] = _value;
};

function GM_getValue(_name, _default) {
  if (localStorage[_name] === null && _default === null) return undefined;
  return localStorage[_name] || _default;
};

function GM_deleteValue(_name) {
  localStorage.removeItem(_name);
};

function GM_listValues() {
  return Object.keys(localStorage);
};

function GM_setClipboard(_text) {
//   Break on Firefox mobile
//   self.port.emit("GM_setClipboard", _text);
};

//Deprecated
function GM_log(_message) {
  console.log(_message);
};

function GM_xmlhttpRequest(_details) {
  //Ugly hack? Race condition? Memory leak?
  _onload = _details.onload;
  self.port.emit("GM_xmlhttpRequest", _details);
};

self.port.on("callback_GM_xmlhttpRequest", function(_response) {
  _onload(_response);
});

function GM_addStyle(_css) {
  self.port.emit("GM_addStyle", _css);
}

var GM_info = new Object();
GM_info.version = '1.15';
GM_info.scriptWillUpdate = true;

//To do
function GM_registerMenuCommand(_caption, _commandFunc, _accessKey) {
  return null;
}

self.port.on("load-userscript", function(_script) {
  eval(_script);
});<|endoftext|>