<commit_before>"use strict";

var map;
var tile_layer;
var wkx = require('wkx');
var buffer = require('buffer');
var filters = [];
var table_container;
var query_builder;
var where;
var view;

function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

function fail_handler(jqXHR, exception) {
    var msg = '';
    if (jqXHR.status === 0) {
        msg = 'Not connected.\n Verify Network.';
    } else if (jqXHR.status == 404) {
        msg = 'Requested page not found. [404]';
    } else if (jqXHR.status == 500) {
        msg = 'Internal Server Error [500].';
    } else if (exception === 'parsererror') {
        msg = 'Requested JSON parse failed.';
    } else if (exception === 'timeout') {
        msg = 'Time out error.';
    } else if (exception === 'abort') {
        msg = 'Ajax request aborted.';
    } else {
        msg = 'Uncaught Error.\n' + jqXHR.responseText;
    }
    console.log(msg);
}

var table_info = {
    columns: [],
    rows: null,
    name: null,
    schema: null,
};

var geo_datatypes = [
    "point", "polygon", "polygonwithhole", "collection", "linestring"
];

function request_data(data, callback, settings) {
    $("#loading-indicator").show();

    var base_query = {
        "from": {
            "type": "table",
            "schema": schema,
            "table": table
        }
    };
    var count_query = JSON.parse(JSON.stringify(base_query));
    count_query["fields"] = [{
        type: "function",
        function: "count",
        operands: ["*"]
    }];
    count_query.where = where;
    var select_query = JSON.parse(JSON.stringify(base_query));
    select_query["order_by"] = data.order.map(function (c) {
        return {
            type: "column",
            column: table_info.columns[c.column],
            ordering: c.dir
        }
    });
    select_query["fields"] = [];
    for (var i in table_info.columns) {
        var col = table_info.columns[i];
        var query = {
            type: "column",
            column: col
        };
        if (col == "geom") {
            query = {
                type: "label",
                label: "geom",
                element: {
                    type: "function",
                    function: "ST_Transform",
                    operands: [
                        query,
                        4326
                    ]
                }
            }
        }
        select_query["fields"].push(query);
    }
    select_query.offset = data.start;
    select_query.limit = data.length;
    if (where !== null) {
        select_query.where = where;
    }
    var draw = Number(data.draw);
    $.when(
        $.ajax({
            type: 'POST',
            url: '/api/v0/advanced/search',
            dataType: 'json',
            data: {
                csrfmiddlewaretoken: csrftoken,
                query: JSON.stringify(count_query)
            }
        }), $.ajax({
            type: 'POST',
            url: '/api/v0/advanced/search',
            dataType: 'json',
            data: {
                csrfmiddlewaretoken: csrftoken,
                query: JSON.stringify(select_query)
            }
        })
    ).done(function (count_response, select_response) {
        $("#loading-indicator").hide();
        if (map !== undefined) {
            build_map(select_response[0].data, select_response[0].description)
        }

        if (view.type === "map") {
            build_map(select_response[0].data, select_response[0].description);
        } else if (view.type === "graph") {
            build_graph(select_response[0].data);
        }
        callback({
            data: select_response[0].data,
            draw: draw,
            recordsFiltered: count_response[0].data[0][0],
            recordsTotal: table_info.rows
        });
    }).fail(fail_handler);
}

function build_map(data, description) {
    map.eachLayer(function (layer) {
        if (layer !== tile_layer) { map.removeLayer(layer) }
    });
    var geo_columns = get_selected_geo_columns();
    var col_idxs = description.reduce(function (l, r, i) {
        if (geo_columns.includes(r[0])) {
            l.push(i);
        }
        return l;
    }, []);
    var bounds = [];
    for (var row_id in data) {
        var row = data[row_id];
        var geo_values = col_idxs.map(function (i) {
            if (row[i] !== null) {
                var buf = new buffer.Buffer(row[i], "hex");
                var wkb = wkx.Geometry.parse(buf);
                var gj = L.geoJSON(wkb.toGeoJSON());
                gj.on("click", flash_handler(row_id));
                gj.addTo(map);
                return gj;
            }
        });
        bounds.push(L.featureGroup(geo_values.filter(x => !!x)));
    }
    var b = L.featureGroup(bounds).getBounds();
    map.fitBounds(b);
}

function get_selected_geo_columns() {
    if (view.options.hasOwnProperty("geom")) {
        return [view.options.geom];
    } else if (view.options.hasOwnProperty("lat") && view.options.hasOwnProperty("lon")) {
        return [view.options.lat, view.options.lon];
    }
    else {
        console.log("Unrecognised map type")
    }
}

function build_graph(data) {
    // Get the div for the graph
    var plotly_div = $("#datagraph")[0];

    // Load column names to use in plot
    var x = view.options.x;
    var y = view.options.y;

    // Get ids of those columns
    var x_id = table_info.columns.indexOf(x);
    var y_id = table_info.columns.indexOf(y);

    // Extract data from query results
    var points = data.reduce(function (accumulator, row) {
        accumulator[0].push(row[x_id]);
        accumulator[1].push(row[y_id]);
        return accumulator
    }, [[], []]);

    // Remove possible older plots
    Plotly.purge(plotly_div);

    // Plot it
    Plotly.plot(
        plotly_div,
        [{
            x: points[0],
            y: points[1]
        }],
        {
            margin: { t: 0 },
            xaxis: {
                title: { text: x }
            },
            yaxis: {
                title: { text: y }
            }
        }
    );
}

function flash_handler(i) {
    return function () {
        var tr = table_container.row(i).node();
        $(tr).fadeOut(50).fadeIn(50);
    };
}

function load_graph(schema, table, csrftoken) {

}

function load_view(schema, table, csrftoken, current_view) {
    view = current_view;
    table_info.name = table;
    table_info.schema = schema;
    var count_query = {
        from: {
            type: "table",
            schema: schema,
            table: table
        },
        fields: [{
            type: "function",
            function: "count",
            operands: ["*"]
        }]
    };
    $.when(
        $.ajax({
            url: '/api/v0/schema/' + schema + '/tables/' + table + '/columns',
        }), $.ajax({
            type: 'POST',
            url: '/api/v0/advanced/search',
            dataType: 'json',
            data: {
                csrfmiddlewaretoken: csrftoken,
                query: JSON.stringify(count_query)
            }
        })
    ).done(function (column_response, count_response) {

        for (var colname in column_response[0]) {
            var str = '' + colname + '	';
            $(str).appendTo('#datatable' + '>thead>tr');
            table_info.columns.push(colname);
            var dt = column_response[0][colname]["data_type"];
            var mapped_dt;
            if (dt in type_maps) {
                mapped_dt = type_maps[dt];
            } else {
                if (valid_types.includes(dt)) {
                    mapped_dt = dt;
                } else {
                    mapped_dt = "string";
                }
            }
            filters.push({ id: colname, type: mapped_dt });
        }
        if (view.type === "map") {
            map = L.map('map');
            tile_layer = L.tileLayer(
                'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                'attribution': 'Kartendaten © OpenStreetMap Mitwirkende',
                'useCache': true
            }
            );
            tile_layer.addTo(map);
        }

        table_info.rows = count_response[0].data[0][0];
        table_container = $('#datatable').DataTable({
            ajax: request_data,
            serverSide: true,
            scrollY: true,
            scrollX: true,
            searching: false,
            search: {}
        });
        query_builder = $('#builder').queryBuilder({
            filters: filters
        });
        $('#btn-set').on('click', apply_filters);
        $('#btn-download-view').on('click', parse_download);

    }).fail(fail_handler)
}
// uses the basic api.
/*
function parse_download(){
    var url = '/api/v0/schema/' + schema + '/tables/' + table + '/rows/'
    var rules = $('#builder').queryBuilder('getRules');
    if(rules == null) {
        window.alert("No Filters applied");
        return;
    }
    where = parse_filter(rules);

    if(where.operator == "or") {
        var mids = 0;
        var operands = where.operands;
        var enrichment = "";
        operands.forEach( operand => {
            var firstFlag = false;
            operand.operands.forEach( participant => {
                if(participant.constructor == Object){
                    enrichment += participant.column;
                    firstFlag = true;
                }
                if(participant.constructor == String && firstFlag) enrichment += operand.operator + participant;
            });
            if(enrichment.length !== 0 && mids != operands.length - 1) { enrichment += '||'; mids += 1;}
        });
            url += '?where=' + enrichment + '&form=csv';
    }
    else if(where.operator == "and") {
        var mids = 0;
        var operands = where.operands;
        var enrichment = "";
        operands.forEach( operand => {
            var firstFlag = false;
            operand.operands.forEach( participant => {
                if(participant.constructor == Object){
                    enrichment += participant.column;
                    firstFlag = true;
                }
                if(participant.constructor == String && firstFlag) enrichment += operand.operator + participant;
            });
            if(enrichment.length !== 0 && mids != operands.length - 1) { enrichment += '&'; mids += 1;}
        });
        url += '?where=' + enrichment + '&form=csv';
    }
    downloadFile(url);

}
*/

function parse_download() {
    var base_query = {
        "fields": [
        ],
        "from": {
            "type": "table",
            "schema": schema,
            "table": table
        }
    };
    var rules = $('#builder').queryBuilder('getRules');
    if (rules == null) {
        window.alert("Please check for invalid Rules");
        return;
    }
    base_query.where = parse_filter(rules);
    $.ajax({
        type: 'POST',
        url: '/api/v0/advanced/search',
        dataType: 'json',
        data: {
            csrfmiddlewaretoken: csrftoken,
            query: JSON.stringify(base_query)
        }
    }).done((response) => {
        var regex = new RegExp(/\[|\]/, "gmi");
        var temp = [];
        var head = [];
        response.content.description.forEach(col_id => {
            head.push(col_id[0]);
        });
        temp.push(JSON.stringify(head).replace(regex, ''));
        temp.push("\n");
        response.data.forEach(element => {
            temp.push(JSON.stringify(element).replace(regex, ''));
            temp.push("\n");
        });
        var responseBlob = new Blob(temp);
        var tempElement = document.createElement('a');
        tempElement.href = window.URL.createObjectURL(responseBlob);
        tempElement.download = 'Partial_' + schema + '_' + table + '.csv';
        tempElement.click();
        tempElement.remove();
    });
}

function apply_filters() {
    var rules = $('#builder').queryBuilder('getRules');
    if (rules !== null) {
        where = parse_filter(rules);
        table_container.ajax.reload();
    }
}

function parse_filter(f) {
    return {
        type: "operator",
        operator: f.condition.toLowerCase(),
        operands: f.rules.map(parse_rule)
    }
}

function negate(q) {
    return {
        type: "operator",
        operator: "not",
        operands: [q]
    }
}

function parse_rule(r) {
    switch (r.operator) {
        case "equal":
            return {
                type: "operator",
                operator: "=",
                operands: [{ type: "column", column: r.field }, r.value]
            };
        case "not_equal":
            return negate({
                type: "operator",
                operator: "=",
                operands: [{ type: "column", column: r.field }, r.value]
            });
        case "in":
            return {
                type: "operator",
                operator: "in",
                operands: [{ type: "column", column: r.field }, r.value]
            };
        case "not_in":
            return negate({
                type: "operator",
                operator: "in",
                operands: [{ type: "column", column: r.field }, r.value]
            });
        case "less":
            return {
                type: "operator",
                operator: "<",
                operands: [{ type: "column", column: r.field }, r.value]
            };
        case "less_or_equal":
            return {
                type: "operator",
                operator: "<=",
                operands: [{ type: "column", column: r.field }, r.value]
            };
        case "greater":
            return {
                type: "operator",
                operator: ">",
                operands: [{ type: "column", column: r.field }, r.value]
            };
        case "greater_or_equal":
            return {
                type: "operator",
                operator: ">=",
                operands: [{ type: "column", column: r.field }, r.value]
            };
        case "between":
            return {
                type: "operator",
                operator: "and",
                operands:
                    [
                        {
                            type: "operator",
                            operator: "<",
                            operands: [r.value[0], { type: "column", column: r.field }]
                        }, {
                            type: "operator",
                            operator: "<",
                            operands: [{ type: "column", column: r.field }, r.value[1]]
                        }]
            };
        case "not_between":
            return negate({
                type: "operator",
                operator: "and",
                operands:
                    [
                        {
                            type: "operator",
                            operator: "<",
                            operands: [r.value[0], { type: "column", column: r.field }]
                        }, {
                            type: "operator",
                            operator: "<",
                            operands: [{ type: "column", column: r.field }, r.value[1]]
                        }]
            });
        case "begins_with":
            return {
                type: "operator",
                operator: "like",
                operands: [{ type: "column", column: r.field }, r.value + "%"]
            };
        case "not_begins_with":
            return negate({
                type: "operator",
                operator: "like",
                operands: [{ type: "column", column: r.field }, r.value + "%"]
            });
        case "contains":
            return {
                type: "operator",
                operator: "in",
                operands: [{ type: "column", column: r.field }, r.value]
            };
        case "not_contains":
            return negate({
                type: "operator",
                operator: "in",
                operands: [{ type: "column", column: r.field }, r.value]
            });
        case "ends_with":
            return {
                type: "operator",
                operator: "like",
                operands: [{ type: "column", column: r.field }, "%" + r.value]
            };
        case "not_ends_with":
            return negate({
                type: "operator",
                operator: "like",
                operands: [{ type: "column", column: r.field }, "%" + r.value]
            });
        case "is_empty":
            return {
                type: "operator",
                operator: "=",
                operands: [{ type: "column", column: r.field }, '']
            };
        case "is_not_empty":
            return negate({
                type: "operator",
                operator: "=",
                operands: [{ type: "column", column: r.field }, '']
            });
        case "is_null":
            return {
                type: "operator",
                operator: "is",
                operands: [{ type: "column", column: r.field }, null]
            };
        case "is_not_null":
            return negate({
                type: "operator",
                operator: "IS",
                operands: [{ type: "column", column: r.field }, null]
            });
    }
}

var type_maps = {
    "double precision": "double",
};

var valid_types = ["string", "integer", "double", "date", "time", "datetime", "boolean"];
<commit_msg>completes smoke testing<commit_after>"use strict";

var map;
var tile_layer;
var wkx = require('wkx');
var buffer = require('buffer');
var filters = [];
var table_container;
var query_builder;
var where;
var view;

function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

function fail_handler(jqXHR, exception) {
    var msg = '';
    if (jqXHR.status === 0) {
        msg = 'Not connected.\n Verify Network.';
    } else if (jqXHR.status == 404) {
        msg = 'Requested page not found. [404]';
    } else if (jqXHR.status == 500) {
        msg = 'Internal Server Error [500].';
    } else if (exception === 'parsererror') {
        msg = 'Requested JSON parse failed.';
    } else if (exception === 'timeout') {
        msg = 'Time out error.';
    } else if (exception === 'abort') {
        msg = 'Ajax request aborted.';
    } else {
        msg = 'Uncaught Error.\n' + jqXHR.responseText;
    }
    console.log(msg);
}

var table_info = {
    columns: [],
    rows: null,
    name: null,
    schema: null,
};

var geo_datatypes = [
    "point", "polygon", "polygonwithhole", "collection", "linestring"
];

function request_data(data, callback, settings) {
    $("#loading-indicator").show();

    var base_query = {
        "from": {
            "type": "table",
            "schema": schema,
            "table": table
        }
    };
    var count_query = JSON.parse(JSON.stringify(base_query));
    count_query["fields"] = [{
        type: "function",
        function: "count",
        operands: ["*"]
    }];
    count_query.where = where;
    var select_query = JSON.parse(JSON.stringify(base_query));
    select_query["order_by"] = data.order.map(function (c) {
        return {
            type: "column",
            column: table_info.columns[c.column],
            ordering: c.dir
        }
    });
    select_query["fields"] = [];
    for (var i in table_info.columns) {
        var col = table_info.columns[i];
        var query = {
            type: "column",
            column: col
        };
        if (col == "geom") {
            query = {
                type: "label",
                label: "geom",
                element: {
                    type: "function",
                    function: "ST_Transform",
                    operands: [
                        query,
                        4326
                    ]
                }
            }
        }
        select_query["fields"].push(query);
    }
    select_query.offset = data.start;
    select_query.limit = data.length;
    if (where !== null) {
        select_query.where = where;
    }
    var draw = Number(data.draw);
    $.when(
        $.ajax({
            type: 'POST',
            url: '/api/v0/advanced/search',
            dataType: 'json',
            data: {
                csrfmiddlewaretoken: csrftoken,
                query: JSON.stringify(count_query)
            }
        }), $.ajax({
            type: 'POST',
            url: '/api/v0/advanced/search',
            dataType: 'json',
            data: {
                csrfmiddlewaretoken: csrftoken,
                query: JSON.stringify(select_query)
            }
        })
    ).done(function (count_response, select_response) {
        $("#loading-indicator").hide();
        if (map !== undefined) {
            build_map(select_response[0].data, select_response[0].description)
        }

        if (view.type === "map") {
            build_map(select_response[0].data, select_response[0].description);
        } else if (view.type === "graph") {
            build_graph(select_response[0].data);
        }
        callback({
            data: select_response[0].data,
            draw: draw,
            recordsFiltered: count_response[0].data[0][0],
            recordsTotal: table_info.rows
        });
    }).fail(fail_handler);
}

function build_map(data, description) {
    map.eachLayer(function (layer) {
        if (layer !== tile_layer) { map.removeLayer(layer) }
    });
    var geo_columns = get_selected_geo_columns();
    var col_idxs = description.reduce(function (l, r, i) {
        if (geo_columns.includes(r[0])) {
            l.push(i);
        }
        return l;
    }, []);
    var bounds = [];
    for (var row_id in data) {
        var row = data[row_id];
        var geo_values = col_idxs.map(function (i) {
            if (row[i] !== null) {
                var buf = new buffer.Buffer(row[i], "hex");
                var wkb = wkx.Geometry.parse(buf);
                var gj = L.geoJSON(wkb.toGeoJSON());
                gj.on("click", flash_handler(row_id));
                gj.addTo(map);
                return gj;
            }
        });
        bounds.push(L.featureGroup(geo_values.filter(x => !!x)));
    }
    var b = L.featureGroup(bounds).getBounds();
    map.fitBounds(b);
}

function get_selected_geo_columns() {
    if (view.options.hasOwnProperty("geom")) {
        return [view.options.geom];
    } else if (view.options.hasOwnProperty("lat") && view.options.hasOwnProperty("lon")) {
        return [view.options.lat, view.options.lon];
    }
    else {
        console.log("Unrecognised map type")
    }
}

function build_graph(data) {
    // Get the div for the graph
    var plotly_div = $("#datagraph")[0];

    // Load column names to use in plot
    var x = view.options.x;
    var y = view.options.y;

    // Get ids of those columns
    var x_id = table_info.columns.indexOf(x);
    var y_id = table_info.columns.indexOf(y);

    // Extract data from query results
    var points = data.reduce(function (accumulator, row) {
        accumulator[0].push(row[x_id]);
        accumulator[1].push(row[y_id]);
        return accumulator
    }, [[], []]);

    // Remove possible older plots
    Plotly.purge(plotly_div);

    // Plot it
    Plotly.plot(
        plotly_div,
        [{
            x: points[0],
            y: points[1]
        }],
        {
            margin: { t: 0 },
            xaxis: {
                title: { text: x }
            },
            yaxis: {
                title: { text: y }
            }
        }
    );
}

function flash_handler(i) {
    return function () {
        var tr = table_container.row(i).node();
        $(tr).fadeOut(50).fadeIn(50);
    };
}

function load_graph(schema, table, csrftoken) {

}

function load_view(schema, table, csrftoken, current_view) {
    view = current_view;
    table_info.name = table;
    table_info.schema = schema;
    var count_query = {
        from: {
            type: "table",
            schema: schema,
            table: table
        },
        fields: [{
            type: "function",
            function: "count",
            operands: ["*"]
        }]
    };
    $.when(
        $.ajax({
            url: '/api/v0/schema/' + schema + '/tables/' + table + '/columns',
        }), $.ajax({
            type: 'POST',
            url: '/api/v0/advanced/search',
            dataType: 'json',
            data: {
                csrfmiddlewaretoken: csrftoken,
                query: JSON.stringify(count_query)
            }
        })
    ).done(function (column_response, count_response) {

        for (var colname in column_response[0]) {
            var str = '' + colname + '	';
            $(str).appendTo('#datatable' + '>thead>tr');
            table_info.columns.push(colname);
            var dt = column_response[0][colname]["data_type"];
            var mapped_dt;
            if (dt in type_maps) {
                mapped_dt = type_maps[dt];
            } else {
                if (valid_types.includes(dt)) {
                    mapped_dt = dt;
                } else {
                    mapped_dt = "string";
                }
            }
            filters.push({ id: colname, type: mapped_dt });
        }
        if (view.type === "map") {
            map = L.map('map');
            tile_layer = L.tileLayer(
                'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                'attribution': 'Kartendaten © OpenStreetMap Mitwirkende',
                'useCache': true
            }
            );
            tile_layer.addTo(map);
        }

        table_info.rows = count_response[0].data[0][0];
        table_container = $('#datatable').DataTable({
            ajax: request_data,
            serverSide: true,
            scrollY: true,
            scrollX: true,
            searching: false,
            search: {}
        });
        query_builder = $('#builder').queryBuilder({
            filters: filters
        });
        $('#btn-set').on('click', apply_filters);
        $('#btn-download-view').on('click', parse_download);

    }).fail(fail_handler)
}

function parse_download() {
    var base_query = {
        "fields": [
        ],
        "from": {
            "type": "table",
            "schema": schema,
            "table": table
        }
    };
    var rules = $('#builder').queryBuilder('getRules');
    if (rules == null) {
        window.alert("Please check for invalid Rules");
        return;
    }
    base_query.where = parse_filter(rules);
    $.ajax({
        type: 'POST',
        url: '/api/v0/advanced/search',
        dataType: 'json',
        data: {
            csrfmiddlewaretoken: csrftoken,
            query: JSON.stringify(base_query)
        }
    }).done((response) => {
        var regex = new RegExp(/\[|\]/, "gmi");
        var temp = [];
        var head = [];
        response.content.description.forEach(col_id => {
            head.push(col_id[0]);
        });
        temp.push(JSON.stringify(head).replace(regex, ''));
        temp.push("\n");
        response.data.forEach(element => {
            temp.push(JSON.stringify(element).replace(regex, ''));
            temp.push("\n");
        });
        var responseBlob = new Blob(temp);
        var tempElement = document.createElement('a');
        tempElement.href = window.URL.createObjectURL(responseBlob);
        tempElement.download = 'Partial_' + schema + '_' + table + '.csv';
        tempElement.click();
        tempElement.remove();
    });
}

function apply_filters() {
    var rules = $('#builder').queryBuilder('getRules');
    if (rules !== null) {
        where = parse_filter(rules);
        table_container.ajax.reload();
    }
}

function parse_filter(f) {
    return {
        type: "operator",
        operator: f.condition.toLowerCase(),
        operands: f.rules.map(parse_rule)
    }
}

function negate(q) {
    return {
        type: "operator",
        operator: "not",
        operands: [q]
    }
}

function parse_rule(r) {
    switch (r.operator) {
        case "equal":
            return {
                type: "operator",
                operator: "=",
                operands: [{ type: "column", column: r.field }, r.value]
            };
        case "not_equal":
            return negate({
                type: "operator",
                operator: "=",
                operands: [{ type: "column", column: r.field }, r.value]
            });
        case "in":
            return {
                type: "operator",
                operator: "in",
                operands: [{ type: "column", column: r.field }, r.value]
            };
        case "not_in":
            return negate({
                type: "operator",
                operator: "in",
                operands: [{ type: "column", column: r.field }, r.value]
            });
        case "less":
            return {
                type: "operator",
                operator: "<",
                operands: [{ type: "column", column: r.field }, r.value]
            };
        case "less_or_equal":
            return {
                type: "operator",
                operator: "<=",
                operands: [{ type: "column", column: r.field }, r.value]
            };
        case "greater":
            return {
                type: "operator",
                operator: ">",
                operands: [{ type: "column", column: r.field }, r.value]
            };
        case "greater_or_equal":
            return {
                type: "operator",
                operator: ">=",
                operands: [{ type: "column", column: r.field }, r.value]
            };
        case "between":
            return {
                type: "operator",
                operator: "and",
                operands:
                    [
                        {
                            type: "operator",
                            operator: "<",
                            operands: [r.value[0], { type: "column", column: r.field }]
                        }, {
                            type: "operator",
                            operator: "<",
                            operands: [{ type: "column", column: r.field }, r.value[1]]
                        }]
            };
        case "not_between":
            return negate({
                type: "operator",
                operator: "and",
                operands:
                    [
                        {
                            type: "operator",
                            operator: "<",
                            operands: [r.value[0], { type: "column", column: r.field }]
                        }, {
                            type: "operator",
                            operator: "<",
                            operands: [{ type: "column", column: r.field }, r.value[1]]
                        }]
            });
        case "begins_with":
            return {
                type: "operator",
                operator: "like",
                operands: [{ type: "column", column: r.field }, r.value + "%"]
            };
        case "not_begins_with":
            return negate({
                type: "operator",
                operator: "like",
                operands: [{ type: "column", column: r.field }, r.value + "%"]
            });
        case "contains":
            return {
                type: "operator",
                operator: "in",
                operands: [{ type: "column", column: r.field }, r.value]
            };
        case "not_contains":
            return negate({
                type: "operator",
                operator: "in",
                operands: [{ type: "column", column: r.field }, r.value]
            });
        case "ends_with":
            return {
                type: "operator",
                operator: "like",
                operands: [{ type: "column", column: r.field }, "%" + r.value]
            };
        case "not_ends_with":
            return negate({
                type: "operator",
                operator: "like",
                operands: [{ type: "column", column: r.field }, "%" + r.value]
            });
        case "is_empty":
            return {
                type: "operator",
                operator: "=",
                operands: [{ type: "column", column: r.field }, '']
            };
        case "is_not_empty":
            return negate({
                type: "operator",
                operator: "=",
                operands: [{ type: "column", column: r.field }, '']
            });
        case "is_null":
            return {
                type: "operator",
                operator: "is",
                operands: [{ type: "column", column: r.field }, null]
            };
        case "is_not_null":
            return negate({
                type: "operator",
                operator: "IS",
                operands: [{ type: "column", column: r.field }, null]
            });
    }
}

var type_maps = {
    "double precision": "double",
};

var valid_types = ["string", "integer", "double", "date", "time", "datetime", "boolean"];
<|endoftext|>


<commit_before>var natureOfCode = natureOfCode || {};

(function(ns){
"use strict";

  ns.Mover = function (settings) {
      this.location  = new ns.Vector2D(settings.x, settings.y);
      this.mass = settings.mass;
      this.drawingFunction = settings.draw;
      this.afterUpdateCallback = settings.afterUpdate;
      this.velocity = new ns.Vector2D(0, 0);
      this.acceleration = new ns.Vector2D(0,0);
      this.topSpeed = settings.topSpeed;
  };

  ns.Mover.prototype = (function () {
      var defaultTopSpeed = 10,
          forcesArray = [],

          //public. This is the function where movement happens. It should be called at each frame.
          update = function (width, height) {
              this.acceleration = calculateAcceleration(forcesArray, this.mass);
              forcesArray = [];//the forces have to be reapplied at each cicle, they don't accumulate;

              this.velocity = this.velocity.addVector(this.acceleration);
              this.velocity = limit(this.velocity, this.topSpeed || defaultTopSpeed);

              this.location = this.location.addVector(this.velocity);

              checkEdges.call(this,width, height);

              if(this.afterUpdateCallback) this.afterUpdateCallback.call(this);
          },

          //public. This is the function where the object is drawn. It should be called at each frame.
          display =  function (canvas) {
              var context = canvas.getContext('2d');

              if(this.drawingFunction){
                this.drawingFunction(context,this.location.x,this.location.y);
              }else{
                drawCircle(context,this.location.x,this.location.y);
              }

              ns.arrows.drawVelocityAndAcceleration(context,this);
          },

          //public. You can use forces to tell the Mover how to move.
          applyForce = function(force){
              //Forces are only stored in an array for now.
              //They will be really applied in the update function.
              forcesArray.push(force);
          },

          //private. calculating acceleration using newton's second law: a = F/m
          calculateAcceleration = function(forces, mass){
              var newAcceleration,
                  resultingForce = new ns.Vector2D(0,0),
                  i;

              //first add all the forces
              for(i = 0;i<forces.length;i++){
                resultingForce = resultingForce.addVector(forces[i]);
              }

              //divide by mass
              if(mass){
                newAcceleration = resultingForce.divide(mass);
              }else{
                newAcceleration = resultingForce;
              }

              return newAcceleration;
          },

          //private. Keeps the mover from going out of screen.
          checkEdges = function (width, height) {
              if(this.location.x > width || this.location.x < 0 ){
                this.velocity = new ns.Vector2D(-this.velocity.x,this.velocity.y);
              }
              if(this.location.y > height || this.location.y < 0 ){
                this.velocity = new ns.Vector2D(this.velocity.x,-this.velocity.y);
              }
          },

          //private. Keeps the mover from going too fast.
          limit = function(vector,max){
              var result = vector,
                  magnitude = vector.magnitude();

              if(magnitude > max){
                  result = vector.divide(magnitude/max);
              }

              return result;
          },

          //private.
          drawCircle = function(context,x,y){
            //draw body
            context.beginPath();
            context.arc(x, y, 10, 0, 2 * Math.PI, false);
            context.fillStyle = '#00ffff';
            context.fill();
          };

      return{
          update:update,
          display:display,
          applyForce:applyForce
      };
  })();

})(natureOfCode);
<commit_msg>prevent the movers from staying offscreen<commit_after>var natureOfCode = natureOfCode || {};

(function(ns){
"use strict";

  ns.Mover = function (settings) {
      this.location  = new ns.Vector2D(settings.x, settings.y);
      this.mass = settings.mass;
      this.drawingFunction = settings.draw;
      this.afterUpdateCallback = settings.afterUpdate;
      this.velocity = new ns.Vector2D(0, 0);
      this.acceleration = new ns.Vector2D(0,0);
      this.topSpeed = settings.topSpeed;
  };

  ns.Mover.prototype = (function () {
      var defaultTopSpeed = 10,
          forcesArray = [],

          //public. This is the function where movement happens. It should be called at each frame.
          update = function (width, height) {
              this.acceleration = calculateAcceleration(forcesArray, this.mass);
              forcesArray = [];//the forces have to be reapplied at each cicle, they don't accumulate;

              this.velocity = this.velocity.addVector(this.acceleration);
              this.velocity = limit(this.velocity, this.topSpeed || defaultTopSpeed);

              this.location = this.location.addVector(this.velocity);

              checkEdges.call(this,width, height);

              if(this.afterUpdateCallback) this.afterUpdateCallback.call(this);
          },

          //public. This is the function where the object is drawn. It should be called at each frame.
          display =  function (canvas) {
              var context = canvas.getContext('2d');

              if(this.drawingFunction){
                this.drawingFunction(context,this.location.x,this.location.y);
              }else{
                drawCircle(context,this.location.x,this.location.y);
              }

              ns.arrows.drawVelocityAndAcceleration(context,this);
          },

          //public. You can use forces to tell the Mover how to move.
          applyForce = function(force){
              //Forces are only stored in an array for now.
              //They will be really applied in the update function.
              forcesArray.push(force);
          },

          //private. calculating acceleration using newton's second law: a = F/m
          calculateAcceleration = function(forces, mass){
              var newAcceleration,
                  resultingForce = new ns.Vector2D(0,0),
                  i;

              //first add all the forces
              for(i = 0;i<forces.length;i++){
                resultingForce = resultingForce.addVector(forces[i]);
              }

              //divide by mass
              if(mass){
                newAcceleration = resultingForce.divide(mass);
              }else{
                newAcceleration = resultingForce;
              }

              return newAcceleration;
          },

          //private. Keeps the mover from going out of screen.
          checkEdges = function (width, height) {
              if(this.location.x > width || this.location.x < 0 ){
                this.velocity = new ns.Vector2D(-this.velocity.x,this.velocity.y);
              }
              if(this.location.y > height || this.location.y < 0 ){
                this.velocity = new ns.Vector2D(this.velocity.x,-this.velocity.y);
              }

              if(this.location.x < 0) this.location.x = 0;
              if(this.location.x > width) this.location.x = width;
              if(this.location.y < 0) this.location.y = 0;
              if(this.location.y > height) this.location.y = height;
          },

          //private. Keeps the mover from going too fast.
          limit = function(vector,max){
              var result = vector,
                  magnitude = vector.magnitude();

              if(magnitude > max){
                  result = vector.divide(magnitude/max);
              }

              return result;
          },

          //private.
          drawCircle = function(context,x,y){
            //draw body
            context.beginPath();
            context.arc(x, y, 10, 0, 2 * Math.PI, false);
            context.fillStyle = '#00ffff';
            context.fill();
            context.strokeStyle = '#00ffff';
            context.stroke();
          };

      return{
          update:update,
          display:display,
          applyForce:applyForce
      };
  })();

})(natureOfCode);
<|endoftext|>


<commit_before>define(
    ["declare",
        "mainmodel",
        "mainconfig",
        "registry",
        "topic",
        "hash",
        "all",
        "string",
        "class",
        "on",
        "featureLayer",
        "querytask",
        "query",
        "dom",
        "root/languages",
        "ioquery",
        'mapconfig'
    ], function(declare, Model, Config, registry, topic, hash, all, string, domClass, on, FeatureLayer, queryTask, query, dom, languages, ioQuery, MapConfig) {
        var appType = "";
        var langType = "";

        return declare(null, {

            changeTitle: function(language) {
                var title = app.config.appLanguages[language].title;
                window.document.title = title;
            },

            UIcreationComplete: function(type, language) {
                appType = type;
                langType = language;

                //set the title based on language
                this.changeTitle(language);

                Model.initialize("headerView", appType, langType);

            },

            changeLanguage: function(value) {

                this.changeTitle(value);

                var newLanguage = value;
                var translation = languages[newLanguage];
                var mainmodel = Model.getVM();
                var prevLanguage = mainmodel.currentLanguage();
                var identifyParams, IdentifyTask;

                // Update the Hash in the URL
                var currentHash = hash();
                var hashObj = ioQuery.queryToObject(currentHash);
                hashObj.l = newLanguage;
                hash(ioQuery.objectToQuery(hashObj));

                //Change common elements here
                var title = app.config.appLanguages[newLanguage].title;
                var flagTitle = app.config.appLanguages[newLanguage].flagTitle;

                mainmodel.title(title);
                mainmodel.flagTitle(flagTitle);

                mainmodel.currentLanguage(newLanguage);

                require(["toolsmodel", "mapui", "mapmodel", "array", "mapcontroller"], function(ToolsModel, MapUI, MapModel, arrayUtil, MapController) {
                    var vm = MapModel.getVM();
                    var mp = vm.mapPoint();
                    var map = MapUI.getMap();
                    var infoLayer = map.infoWindow;
                    var mapConf = MapConfig.getConfig();

                    switch (appType) {
                        case "atlas":

                            var toolsmodel = ToolsModel.getVM();

                            toolsmodel.tabBasemapTitle(translation.tabBasemapTitle);
                            toolsmodel.tabLegendTitle(translation.tabLegendTitle);
                            toolsmodel.printDialog(translation.printDialog);

                            toolsmodel.tabLayersTitle(translation.tabLayersTitle);
                            toolsmodel.buttonLayersText(translation.buttonLayersText);

                            toolsmodel.about(translation.about);
                            toolsmodel.downloadData(translation.downloadData);
                            toolsmodel.sources(translation.sources);
                            toolsmodel.print(translation.print);
                            toolsmodel.mapThemesLabel(translation.mapThemesLabel);

                            toolsmodel.legislativeText(translation.legislativeText);
                            toolsmodel.printReport(translation.printReport);
                            toolsmodel.zoom(translation.zoom);

                            toolsmodel.closeButtonText(translation.closeButtonText);
                            toolsmodel.popupDataTab(translation.popupDataTab);
                            toolsmodel.popupAnalysisTab(translation.popupAnalysisTab);

                            toolsmodel.analysisLoss(translation.analysisLoss);
                            toolsmodel.analysisLC(translation.analysisLC);
                            toolsmodel.analysisTCD(translation.analysisTCD);
                            toolsmodel.analysisIFL(translation.analysisIFL);
                            toolsmodel.analysisCS(translation.analysisCS);
                            toolsmodel.analysisFire(translation.analysisFire);
                            toolsmodel.analysisLCComposition(translation.analysisLCComposition);

                            toolsmodel.analysisOptions(translation.analysisOptions);

                            toolsmodel.firesOneWeek(translation.firesOneWeek);
                            toolsmodel.fires72Hours(translation.fires72Hours);
                            toolsmodel.fires48Hours(translation.fires48Hours);
                            toolsmodel.fires24Hours(translation.fires24Hours);

                            toolsmodel.lossStartingYear(translation.lossStartingYear);
                            toolsmodel.lossEndingYear(translation.lossEndingYear);

                            toolsmodel.accordionForestCoverTitle(translation.accordionForestCoverTitle);
                            toolsmodel.accordionForestLossTitle(translation.accordionForestLossTitle);
                            toolsmodel.accordionLandUseTitle(translation.accordionLandUseTitle);

                            toolsmodel.forestCoverLossLabel(translation.forestCoverLossLabel);
                            toolsmodel.activeFiresLabel(translation.activeFiresLabel);
                            toolsmodel.treeCoverDensityLabel(translation.treeCoverDensityLabel);
                            toolsmodel.landCoverLabel(translation.landCoverLabel);

                            toolsmodel.treeCoverGainLabel(translation.treeCoverGainLabel);
                            toolsmodel.carbonLayerLabel(translation.carbonLayerLabel);
                            toolsmodel.intactForestLayerLabel(translation.intactForestLayerLabel);

                            toolsmodel.treeCoverAnalysis(translation.treeCoverAnalysis);
                            toolsmodel.otherAnalysisTypes(translation.otherAnalysisTypes);

                            toolsmodel.selectAll(translation.selectAll);
                            toolsmodel.clearAll(translation.clearAll);
                            toolsmodel.transparency(translation.transparency);

                            toolsmodel.basemapTitles(translation.basemapTitles);

                            toolsmodel.drawButtonText(translation.drawButtonText);
                            toolsmodel.uploadButtonText(translation.uploadButtonText);
                            toolsmodel.uploadInstructions(translation.uploadInstructions);

                            toolsmodel.clearAllFeatures(translation.clearAllFeatures);
                            toolsmodel.deleteCustomFeature(translation.deleteCustomFeature);
                            toolsmodel.landsatTextLabel(translation.landsatTextLabel);

                            // update the current analysis type to the same type but in the new language
                            switch (toolsmodel.currentAnalysisType()) {
                                case languages[prevLanguage].analysisLoss:
                                    toolsmodel.currentAnalysisType(translation.analysisLoss);
                                break;
                                case languages[prevLanguage].analysisLC:
                                    toolsmodel.currentAnalysisType(translation.analysisLC);
                                break;
                                case languages[prevLanguage].analysisTCD:
                                    toolsmodel.currentAnalysisType(translation.analysisTCD);
                                break;
                                case languages[prevLanguage].analysisIFL:
                                    toolsmodel.currentAnalysisType(translation.analysisIFL);
                                break;
                                case languages[prevLanguage].analysisCS:
                                    toolsmodel.currentAnalysisType(translation.analysisCS);
                                break;
                                case languages[prevLanguage].analysisFire:
                                    toolsmodel.currentAnalysisType(translation.analysisFire);
                                break;
                                case languages[prevLanguage].analysisLCComposition:
                                    toolsmodel.currentAnalysisType(translation.analysisLCComposition);
                                break;
                                default:
                                    toolsmodel.currentAnalysisType(translation.analysisLoss);
                                break;
                            }

                            //change map language layer
                            var language = newLanguage.toLowerCase();
                            var mapLayerLangId = "";
                            //console.log(map);
                            arrayUtil.some(map.layerIds, function(layerId) {
                                layerIdlowerCase = layerId.toLowerCase();
                                mapLayerLangId = layerId;
                                return (layerIdlowerCase.indexOf("_" + language) > -1);
                            }); //end array loop

                            var layoutObj = mainmodel.printLayouts();
                            //console.log(layoutObj);

                            vm.currentActiveLayer(map.getLayer(mapLayerLangId));

                            arrayUtil.forEach(map.getLayer(mapLayerLangId).layerInfos, function(layerInfos, index) {
                                var sliderTitle = "sliderTitleDiv" + index;
                                var dataTitle = "dataTitleDiv" + index;
                                dom.byId(sliderTitle).innerHTML = layerInfos.name;
                            });

                            var toggleLanguage = [];

                            toggleLanguage = query(".language");

                            arrayUtil.forEach(toggleLanguage, function(togLanguage, index) {
                                var langValue = togLanguage.value;
                                if (langValue == newLanguage) {

                                    togLanguage.style.color = "white";
                                    togLanguage.style.fontWeight = "bold";
                                } else {
                                    togLanguage.style.color = "black";
                                    togLanguage.style.fontWeight = "normal";
                                }
                            });

                            arrayUtil.forEach(map.layerIds, function(layerId) {

                                if (layerId == mapLayerLangId) {
                                    var visLayers = map.getLayer(layerId).visibleLayers;
                                    map.getLayer(layerId).show();
                                    map.getLayer(layerId).setVisibleLayers(visLayers);
                                } else if ((layerId != mapLayerLangId) && (layerId != map.layerIds[0])) {

                                    arrayUtil.forEach(map.getLayer(layerId).layerInfos, function(layerInfo, k) {

                                        var layerInt = k + 1;

                                        var featureLayerId = layerId + "_" + layerInt;
                                        var targetFeatureLayer = map._layers[featureLayerId];

                                        if (targetFeatureLayer) {

                                            targetFeatureLayer.hide();
                                        }
                                    }); //end array loop */

                                    // Dont hide layers that are considered extra layers, or layers not defined
                                    // in the webmap, those layers should not be turned off because we are changing
                                    // languages
                                    if (arrayUtil.indexOf(mapConf.extraLayerKeys, layerId) === -1) {
                                        map.getLayer(layerId).hide();
                                    }
                                }
                            });

                            var dynamicLayerInfo = map.getLayer(mapLayerLangId).createDynamicLayerInfosFromLayerInfos();
                            var visiblerLayers = map.getLayer(mapLayerLangId).visibleLayers;
                            //Hide All Feature Layers, show if included in visiblerLayers
                            arrayUtil.forEach(dynamicLayerInfo, function(layerInfo, k) {
                                var layerInt = k + 1;

                                var featureLayerId = mapLayerLangId + "_" + layerInt;
                                var targetFeatureLayer = map._layers[featureLayerId];
                                if (targetFeatureLayer) {
                                    if (arrayUtil.indexOf(visiblerLayers, layerInt) > -1) {
                                        targetFeatureLayer.show();

                                    } else {
                                        console.log(targetFeatureLayer.id);
                                        targetFeatureLayer.hide();
                                    }

                                }

                            });

                            registry.byId("legendDiv").refresh([{
                                layer: vm.currentActiveLayer(),
                                title: ""
                            }]);

                            map.getLayer("maskLayer").show();
                            vm.currentActiveLayer(map.getLayer(mapLayerLangId));
                            map.infoWindow.hide();

                            // Change any Extra layers layer number to the correct language
                            var layerConf,
                                layerNum,
                                layer;

                            arrayUtil.forEach(mapConf.extraLayerKeys, function (configKey) {
                                layerConf = mapConf[configKey];
                                if (layerConf.hasLanguageSupport) {
                                    layer = map.getLayer(layerConf.id);
                                    layerNum = newLanguage === 'en' ? 0 : (newLanguage === 'fr' ? 1 : 2);
                                    layer.setVisibleLayers([layerNum]);
                                    console.dir(layer);
                                }
                            });

                            break;

                        case "other":

                            break;

                    } //end switch

                }); //end require

            }

        }); //end declare
    }); //end define<commit_msg>removed some spacing<commit_after>define(
    ["declare",
        "mainmodel",
        "mainconfig",
        "registry",
        "topic",
        "hash",
        "all",
        "string",
        "class",
        "on",
        "featureLayer",
        "querytask",
        "query",
        "dom",
        "root/languages",
        "ioquery",
        'mapconfig'
    ], function(declare, Model, Config, registry, topic, hash, all, string, domClass, on, FeatureLayer, queryTask, query, dom, languages, ioQuery, MapConfig) {
        var appType = "";
        var langType = "";

        return declare(null, {

            changeTitle: function(language) {
                var title = app.config.appLanguages[language].title;
                window.document.title = title;
            },

            UIcreationComplete: function(type, language) {
                appType = type;
                langType = language;

                //set the title based on language
                this.changeTitle(language);

                Model.initialize("headerView", appType, langType);

            },

            changeLanguage: function(value) {

                this.changeTitle(value);

                var newLanguage = value;
                var translation = languages[newLanguage];
                var mainmodel = Model.getVM();
                var prevLanguage = mainmodel.currentLanguage();
                var identifyParams, IdentifyTask;

                // Update the Hash in the URL
                var currentHash = hash();
                var hashObj = ioQuery.queryToObject(currentHash);
                hashObj.l = newLanguage;
                hash(ioQuery.objectToQuery(hashObj));

                //Change common elements here
                var title = app.config.appLanguages[newLanguage].title;
                var flagTitle = app.config.appLanguages[newLanguage].flagTitle;

                mainmodel.title(title);
                mainmodel.flagTitle(flagTitle);

                mainmodel.currentLanguage(newLanguage);

                require(["toolsmodel", "mapui", "mapmodel", "array", "mapcontroller"], function(ToolsModel, MapUI, MapModel, arrayUtil, MapController) {
                    var vm = MapModel.getVM();
                    var mp = vm.mapPoint();
                    var map = MapUI.getMap();
                    var infoLayer = map.infoWindow;
                    var mapConf = MapConfig.getConfig();

                    switch (appType) {
                        case "atlas":

                            var toolsmodel = ToolsModel.getVM();

                            toolsmodel.tabBasemapTitle(translation.tabBasemapTitle);
                            toolsmodel.tabLegendTitle(translation.tabLegendTitle);
                            toolsmodel.printDialog(translation.printDialog);

                            toolsmodel.tabLayersTitle(translation.tabLayersTitle);
                            toolsmodel.buttonLayersText(translation.buttonLayersText);

                            toolsmodel.about(translation.about);
                            toolsmodel.downloadData(translation.downloadData);
                            toolsmodel.sources(translation.sources);
                            toolsmodel.print(translation.print);
                            toolsmodel.mapThemesLabel(translation.mapThemesLabel);

                            toolsmodel.legislativeText(translation.legislativeText);
                            toolsmodel.printReport(translation.printReport);
                            toolsmodel.zoom(translation.zoom);

                            toolsmodel.closeButtonText(translation.closeButtonText);
                            toolsmodel.popupDataTab(translation.popupDataTab);
                            toolsmodel.popupAnalysisTab(translation.popupAnalysisTab);

                            toolsmodel.analysisLoss(translation.analysisLoss);
                            toolsmodel.analysisLC(translation.analysisLC);
                            toolsmodel.analysisTCD(translation.analysisTCD);
                            toolsmodel.analysisIFL(translation.analysisIFL);
                            toolsmodel.analysisCS(translation.analysisCS);
                            toolsmodel.analysisFire(translation.analysisFire);
                            toolsmodel.analysisLCComposition(translation.analysisLCComposition);

                            toolsmodel.analysisOptions(translation.analysisOptions);

                            toolsmodel.firesOneWeek(translation.firesOneWeek);
                            toolsmodel.fires72Hours(translation.fires72Hours);
                            toolsmodel.fires48Hours(translation.fires48Hours);
                            toolsmodel.fires24Hours(translation.fires24Hours);

                            toolsmodel.lossStartingYear(translation.lossStartingYear);
                            toolsmodel.lossEndingYear(translation.lossEndingYear);

                            toolsmodel.accordionForestCoverTitle(translation.accordionForestCoverTitle);
                            toolsmodel.accordionForestLossTitle(translation.accordionForestLossTitle);
                            toolsmodel.accordionLandUseTitle(translation.accordionLandUseTitle);

                            toolsmodel.forestCoverLossLabel(translation.forestCoverLossLabel);
                            toolsmodel.activeFiresLabel(translation.activeFiresLabel);
                            toolsmodel.treeCoverDensityLabel(translation.treeCoverDensityLabel);
                            toolsmodel.landCoverLabel(translation.landCoverLabel);

                            toolsmodel.treeCoverGainLabel(translation.treeCoverGainLabel);
                            toolsmodel.carbonLayerLabel(translation.carbonLayerLabel);
                            toolsmodel.intactForestLayerLabel(translation.intactForestLayerLabel);

                            toolsmodel.treeCoverAnalysis(translation.treeCoverAnalysis);
                            toolsmodel.otherAnalysisTypes(translation.otherAnalysisTypes);

                            toolsmodel.selectAll(translation.selectAll);
                            toolsmodel.clearAll(translation.clearAll);
                            toolsmodel.transparency(translation.transparency);

                            toolsmodel.basemapTitles(translation.basemapTitles);

                            toolsmodel.drawButtonText(translation.drawButtonText);
                            toolsmodel.uploadButtonText(translation.uploadButtonText);
                            toolsmodel.uploadInstructions(translation.uploadInstructions);

                            toolsmodel.clearAllFeatures(translation.clearAllFeatures);
                            toolsmodel.deleteCustomFeature(translation.deleteCustomFeature);
                            toolsmodel.landsatTextLabel(translation.landsatTextLabel);

                            // update the current analysis type to the same type but in the new language
                            switch (toolsmodel.currentAnalysisType()) {
                                case languages[prevLanguage].analysisLoss:
                                    toolsmodel.currentAnalysisType(translation.analysisLoss);
                                break;
                                case languages[prevLanguage].analysisLC:
                                    toolsmodel.currentAnalysisType(translation.analysisLC);
                                break;
                                case languages[prevLanguage].analysisTCD:
                                    toolsmodel.currentAnalysisType(translation.analysisTCD);
                                break;
                                case languages[prevLanguage].analysisIFL:
                                    toolsmodel.currentAnalysisType(translation.analysisIFL);
                                break;
                                case languages[prevLanguage].analysisCS:
                                    toolsmodel.currentAnalysisType(translation.analysisCS);
                                break;
                                case languages[prevLanguage].analysisFire:
                                    toolsmodel.currentAnalysisType(translation.analysisFire);
                                break;
                                case languages[prevLanguage].analysisLCComposition:
                                    toolsmodel.currentAnalysisType(translation.analysisLCComposition);
                                break;
                                default:
                                    toolsmodel.currentAnalysisType(translation.analysisLoss);
                                break;
                            }

                            //change map language layer
                            var language = newLanguage.toLowerCase();
                            var mapLayerLangId = "";
                            //console.log(map);
                            arrayUtil.some(map.layerIds, function(layerId) {
                                layerIdlowerCase = layerId.toLowerCase();
                                mapLayerLangId = layerId;
                                return (layerIdlowerCase.indexOf("_" + language) > -1);
                            }); //end array loop

                            var layoutObj = mainmodel.printLayouts();
                            //console.log(layoutObj);

                            vm.currentActiveLayer(map.getLayer(mapLayerLangId));

                            arrayUtil.forEach(map.getLayer(mapLayerLangId).layerInfos, function(layerInfos, index) {
                                var sliderTitle = "sliderTitleDiv" + index;
                                var dataTitle = "dataTitleDiv" + index;
                                dom.byId(sliderTitle).innerHTML = layerInfos.name;
                            });

                            var toggleLanguage = [];

                            toggleLanguage = query(".language");

                            arrayUtil.forEach(toggleLanguage, function(togLanguage, index) {
                                var langValue = togLanguage.value;
                                if (langValue == newLanguage) {

                                    togLanguage.style.color = "white";
                                    togLanguage.style.fontWeight = "bold";
                                } else {
                                    togLanguage.style.color = "black";
                                    togLanguage.style.fontWeight = "normal";
                                }
                            });

                            arrayUtil.forEach(map.layerIds, function(layerId) {

                                if (layerId == mapLayerLangId) {
                                    var visLayers = map.getLayer(layerId).visibleLayers;
                                    map.getLayer(layerId).show();
                                    map.getLayer(layerId).setVisibleLayers(visLayers);
                                } else if ((layerId != mapLayerLangId) && (layerId != map.layerIds[0])) {

                                    arrayUtil.forEach(map.getLayer(layerId).layerInfos, function(layerInfo, k) {

                                        var layerInt = k + 1;

                                        var featureLayerId = layerId + "_" + layerInt;
                                        var targetFeatureLayer = map._layers[featureLayerId];

                                        if (targetFeatureLayer) {

                                            targetFeatureLayer.hide();
                                        }
                                    }); //end array loop */

                                    // Dont hide layers that are considered extra layers, or layers not defined
                                    // in the webmap, those layers should not be turned off because we are changing
                                    // languages
                                    if (arrayUtil.indexOf(mapConf.extraLayerKeys, layerId) === -1) {
                                        map.getLayer(layerId).hide();
                                    }
                                }
                            });

                            var dynamicLayerInfo = map.getLayer(mapLayerLangId).createDynamicLayerInfosFromLayerInfos();
                            var visiblerLayers = map.getLayer(mapLayerLangId).visibleLayers;
                            //Hide All Feature Layers, show if included in visiblerLayers
                            arrayUtil.forEach(dynamicLayerInfo, function(layerInfo, k) {
                                var layerInt = k + 1;

                                var featureLayerId = mapLayerLangId + "_" + layerInt;
                                var targetFeatureLayer = map._layers[featureLayerId];
                                if (targetFeatureLayer) {
                                    if (arrayUtil.indexOf(visiblerLayers, layerInt) > -1) {
                                        targetFeatureLayer.show();

                                    } else {
                                        console.log(targetFeatureLayer.id);
                                        targetFeatureLayer.hide();
                                    }

                                }

                            });

                            registry.byId("legendDiv").refresh([{
                                layer: vm.currentActiveLayer(),
                                title: ""
                            }]);

                            map.getLayer("maskLayer").show();
                            vm.currentActiveLayer(map.getLayer(mapLayerLangId));
                            map.infoWindow.hide();

                            // Change any Extra layers layer number to the correct language
                            var layerConf,
                                layerNum,
                                layer;

                            arrayUtil.forEach(mapConf.extraLayerKeys, function (configKey) {
                                layerConf = mapConf[configKey];
                                if (layerConf.hasLanguageSupport) {
                                    layer = map.getLayer(layerConf.id);
                                    layerNum = newLanguage === 'en' ? 0 : (newLanguage === 'fr' ? 1 : 2);
                                    layer.setVisibleLayers([layerNum]);
                                    console.dir(layer);
                                }
                            });

                            break;

                        case "other":

                            break;

                    } //end switch

                }); //end require

            }

        }); //end declare
    }); //end define<|endoftext|>


<commit_before>var { State, Navigation } = require('react-router');
var RouteHandlerMixin = require('react-router/mixins/RouteHandler');

// mixin for viewlists
// works with react-router and gives some helper functions
// to manage viewLists

module.exports = {
  mixins: [
    State,
    RouteHandlerMixin,
    Navigation,
  ],

  routedViewListProps(props) {
    return {
      scrollToStep: this.scrollToStep(),
      onViewEntered: (i) => {
        if (props && props.onViewEntered)
          props.onViewEntered(i);

        this._handleViewEntered(i);
      }
    };
  },

  scrollToStep() {
    return this.numActiveRoutes() - this.getRouteDepth();
  },

  childRouteHandler(props) {
    if (!this.hasChildRoute())
      return null;

    var childProps = Object.assign({}, {key: this.subRouteKey()}, props);
    return this.getRouteHandler(childProps);
  },

  // todo: debug why this is called more than it should be
  _handleViewEntered(i) {
    // debugger
    if (i === 0 && this.numActiveRoutes() > this.getRouteDepth()) {
      var r = this.getRoutes().reverse();
      r.shift();
      setTimeout(() => {
        this.transitionTo(r[0].path)
      });
    }
  },

  numActiveRoutes() {
    return this.getRoutes().length;
  },

  hasChildRoute() {
    return this.numActiveRoutes() > this.getRouteDepth();
  },

  subRouteKey() {
    return this.getRoutes().reverse()[0].name + this.getParams().id;
  }
};<commit_msg>remove commented debugger<commit_after>var { State, Navigation } = require('react-router');
var RouteHandlerMixin = require('react-router/mixins/RouteHandler');

// mixin for viewlists
// works with react-router and gives some helper functions
// to manage viewLists

module.exports = {
  mixins: [
    State,
    RouteHandlerMixin,
    Navigation,
  ],

  routedViewListProps(props) {
    return {
      scrollToStep: this.scrollToStep(),
      onViewEntered: (i) => {
        if (props && props.onViewEntered)
          props.onViewEntered(i);

        this._handleViewEntered(i);
      }
    };
  },

  scrollToStep() {
    return this.numActiveRoutes() - this.getRouteDepth();
  },

  childRouteHandler(props) {
    if (!this.hasChildRoute())
      return null;

    var childProps = Object.assign({}, {key: this.subRouteKey()}, props);
    return this.getRouteHandler(childProps);
  },

  // todo: debug why this is called more than it should be
  _handleViewEntered(i) {
    if (i === 0 && this.numActiveRoutes() > this.getRouteDepth()) {
      var r = this.getRoutes().reverse();
      r.shift();
      setTimeout(() => {
        this.transitionTo(r[0].path)
      });
    }
  },

  numActiveRoutes() {
    return this.getRoutes().length;
  },

  hasChildRoute() {
    return this.numActiveRoutes() > this.getRouteDepth();
  },

  subRouteKey() {
    return this.getRoutes().reverse()[0].name + this.getParams().id;
  }
};<|endoftext|>


<commit_before>var utils = require("@/common/utils");
var _const = require("@/common/const");
var uikit = require("./uikit");
var apiHelper = require("./apis");
var channel = require("./channel");
var profile = require("@/app/tools/profile");
var eventListener = require("@/app/tools/eventListener");
var loading = require("./uikit/loading");
var getToHost = require("@/app/common/transfer");
var commonConfig = require("@/common/config");

var dom;
var starsUl;
var resolvedBtn;
var commentDom;
var tagContainer;
var dialog;

var starList;

var session;
var invite;
var score;
var evaluationDegreeId;
var isSingleTag;
var resolvedDom;
var resolveTip;
var resolvedId = 1;
var _initOnce = _.once(_init);
var evaluateType; // 评价方式
var sessionResolved;// 问题解决评价
var fiveStarState;//默认五星评价
var defaultScore;

module.exports = {
	init: init,
	show: show,
};

function _init(){
	// 自定义主题色
	var config = commonConfig.getConfig();
	var themeName = config.ui.themeName;
	if(themeName && themeName.indexOf("theme_custom") > -1){
		var arr = themeName.split("theme_custom");
		var color = arr[1];
	}

	loading.show("satisfaction");
	//默认五星评价的开关
	apiHelper.getDefaultFiveStarEnable()
	.then(function(resp){
		fiveStarState = resp;
	});
	apiHelper.getSatisfactionTipWord().then(function(tipWord){
		dom = sessionResolved ? utils.createElementFromHTML([
			"
",
			"
" + resolveTip + "",
			"
" + __("evaluation.resolved") + "",
			"" + __("evaluation.unsolved") + "

",
			"" + tipWord + "",
			"

",
			"

",
			"<textarea spellcheck=\"false\" placeholder=\"" + __("evaluation.review") + "\"></textarea>",
			"
"
		].join(""))
			:
			utils.createElementFromHTML([
				"
",
				"" + tipWord + "",
				"

",
				"

",
				"<textarea spellcheck=\"false\" placeholder=\"" + __("evaluation.review") + "\"></textarea>",
				"
"
			].join(""));
		starsUl = dom.querySelector("ul");
		commentDom = dom.querySelector("textarea");
		tagContainer = dom.querySelector(".tag-container");
		resolvedBtn = dom.querySelectorAll(".resolve-btn");
		resolvedDom = dom.querySelector(".resolved");

		utils.live(".resolve-btn", "click", function(){
			utils.removeClass(resolvedBtn, "selected bg-color");
			utils.addClass(this, "selected bg-color");
			if(color){
				$(".resolve-btn").css("cssText","background-color: #fff !important");
				$(".theme_custom").find(".bg-color").css("cssText","background-color: " + color + " !important");
			}
			resolvedId = this.dataset.num;
			if(fiveStarState){
				if(resolvedId == 1){
					utils.addClass(starList, "sel");
					score = defaultScore;
				}
				else{
					utils.removeClass(starList, "sel");
					score = false;
				}
			}
		});

		utils.live("li", "click", function(){
			var level = +this.getAttribute("data-level");

			evaluationDegreeId = this.getAttribute("data-evaluate-id");
			score = this.getAttribute("data-score");
			isSingleTag = this.getAttribute("data-isSingleTag");
			level && _.each(starList, function(elem, i){
				utils.toggleClass(elem, "sel", i < level);
			});

			evaluationDegreeId && _createLabel(evaluationDegreeId);
		}, starsUl);

		utils.live("span.tag", "click", function(){
			var selectedTagNodeList = tagContainer.querySelectorAll(".selected");
			if(isSingleTag == "true"){
				utils.removeClass(selectedTagNodeList, "selected");
				utils.toggleClass(this, "selected");
			}
			else{
				utils.toggleClass(this, "selected");
			}

		}, tagContainer);

		dialog = uikit.createDialog({
			contentDom: dom,
			className: "satisfaction"
		}).addButton({
			confirmText: __("common.submit"),
			confirm: _confirm,
		});
		loading.hide("satisfaction");
		dialog.show();

		// 火狐浏览器 _setSatisfaction时找不到starsUl，所以必须先执行完init
		_setSatisfaction();

		// 自定义主题色
		color && $(".theme_custom").find(".bg-color").css("cssText","background-color: " + color + " !important");
	});
}

function _clear(){
	commentDom.blur();
	commentDom.value = "";
	score = null;
	// clear stars
	utils.removeClass(starList, "sel");
	// clear label
	tagContainer.innerHTML = "";
	// clear resolvedBtn
	utils.removeClass(resolvedBtn, "selected bg-color");
	utils.addClass(resolvedDom, "selected bg-color");
	resolvedBtn.css("cssText","background-color: #fff !important");

	resolvedId = 1;

}

function _sendSatisfaction(score, content, session, invite, appraiseTags, resolutionParam, evaluationDegreeId){
	var data = {
		ext: {
			weichat: {
				ctrlType: "enquiry",
				ctrlArgs: {
					// 后端类型要求，inviteId必须传数字
					inviteId: invite || 0,
					serviceSessionId: session || profile.currentOfficialAccount.sessionId || "",
					detail: content,
					summary: score,
					appraiseTags: appraiseTags,
					resolutionParam: resolutionParam,
					evaluationDegreeId: evaluationDegreeId,
					// 评价方式，由前端传入：visitor - 访客主动评价; agent - 坐席邀请; system - 强制邀请,访客点击关闭窗口或会话结束
					evaluateWay: evaluateType
				}
			}
		}
	};
	if(!sessionResolved){
		delete data.ext.weichat.ctrlArgs.resolutionParam;
	}
	channel.sendText("", data);
}

function _setSatisfaction(){
	apiHelper.getEvaluationDegrees().then(function(entities){
		var labelID;
		var lastScore;
		starsUl.innerHTML = _.chain(entities)
		.sortBy("level")
		.map(function(elem, index){
			// stat level 1-based
			var level = index + 1;
			var name = elem.name;
			var id = elem.id;
			var score = elem.score;
			var isSingleTag = elem.isSingleTag;
			labelID = id;
			lastScore = score;

			return "
H
";
		})
		.value()
		.join("");

		starList = starsUl.querySelectorAll("li");
		defaultScore = lastScore
		if(fiveStarState){
			if(resolvedId == 1){
				utils.addClass(starList, "sel");
				//创建评价标签
				_createLabel(labelID);
				score = defaultScore;
			}
			else{
				utils.removeClass(starList, "sel");
				score = false;
			}
		}

	});
}

function _createLabel(evaluateId){
	apiHelper.getAppraiseTags(evaluateId).then(function(entities){
		tagContainer.innerHTML = _.map(entities, function(elem){
			var name = elem.name;
			var id = elem.id;

			return "" + name + "";
		}).join("");
		utils.removeClass(tagContainer, "hide");
	});
}

function _confirm(){
	var selectedTagNodeList = tagContainer.querySelectorAll(".selected");
	var tagNodeList = tagContainer.querySelectorAll(".tag");
	var content = commentDom.value;
	var appraiseTags = _.map(selectedTagNodeList, function(elem){
		return {
			id: elem.getAttribute("data-label-id"),
			name: elem.innerText
		};
	});
	var resolutionParam = [{
		id: resolvedId,
		name: resolvedId == 1 ? "已解决" : "未解决",
		score: resolvedId,
		resolutionParamTags: []
	}];

	// 必须选择星级
	if(!score){
		uikit.tip(__("evaluation.select_level_please"));
		// 防止对话框关闭
		return false;
	}
	// 若有标签则至少选择一个
	else if(tagNodeList.length > 0 && selectedTagNodeList.length === 0){
		uikit.tip(__("evaluation.select_tag_please"));
		// 防止对话框关闭
		return false;
	}

	_sendSatisfaction(score, content, session, invite, appraiseTags, resolutionParam, evaluationDegreeId);
	uikit.showSuccess(__("evaluation.submit_success"));
	getToHost.send({ event: _const.EVENTS.EVALUATIONSUBMIT });
	// 强制评价点击确定关闭会话框
	setTimeout(function(){
		// 关闭会话
		if(evaluateType === "system"){
			// 取消轮询接口
			eventListener.trigger(_const.SYSTEM_EVENT.CHAT_CLOSED);
			profile.currentOfficialAccount.sessionId && apiHelper.closeChatDialog({ serviceSessionId: profile.currentOfficialAccount.sessionId });
			getToHost.send({ event: _const.EVENTS.CLOSE });
		}
	}, 2000);
	_clear();
}

function show(inviteId, serviceSessionId, evaluateWay){

	apiHelper.getEvaluteSolveWord().then(function(tip){
		resolveTip = tip;
	});
	apiHelper.getServiceSessionResolved()
	.then(function(resp){
		sessionResolved = resp;
		_initOnce();
	});

	session = serviceSessionId;
	invite = inviteId;
	evaluateType = evaluateWay;
	_setDefaultScore();
	dialog && dialog.show();
}

function _setDefaultScore(){
	if(!starsUl){
		return false;
	}
	_setSatisfaction();
}

function init(){
	eventListener.add(
		_const.SYSTEM_EVENT.SATISFACTION_EVALUATION_MESSAGE_RECEIVED,
		function(officialAccount, inviteId, serviceSessionId){
			if(officialAccount !== profile.currentOfficialAccount) return;
			show(inviteId, serviceSessionId, "system");
		}
	);
}
<commit_msg>修改满意度报错<commit_after>var utils = require("@/common/utils");
var _const = require("@/common/const");
var uikit = require("./uikit");
var apiHelper = require("./apis");
var channel = require("./channel");
var profile = require("@/app/tools/profile");
var eventListener = require("@/app/tools/eventListener");
var loading = require("./uikit/loading");
var getToHost = require("@/app/common/transfer");
var commonConfig = require("@/common/config");

var dom;
var starsUl;
var resolvedBtn;
var commentDom;
var tagContainer;
var dialog;

var starList;

var session;
var invite;
var score;
var evaluationDegreeId;
var isSingleTag;
var resolvedDom;
var resolveTip;
var resolvedId = 1;
var _initOnce = _.once(_init);
var evaluateType; // 评价方式
var sessionResolved;// 问题解决评价
var fiveStarState;//默认五星评价
var defaultScore;

module.exports = {
	init: init,
	show: show,
};

function _init(){
	// 自定义主题色
	var config = commonConfig.getConfig();
	var themeName = config.ui.themeName;
	if(themeName && themeName.indexOf("theme_custom") > -1){
		var arr = themeName.split("theme_custom");
		var color = arr[1];
	}

	loading.show("satisfaction");
	//默认五星评价的开关
	apiHelper.getDefaultFiveStarEnable()
	.then(function(resp){
		fiveStarState = resp;
	});
	apiHelper.getSatisfactionTipWord().then(function(tipWord){
		dom = sessionResolved ? utils.createElementFromHTML([
			"
",
			"
" + resolveTip + "",
			"
" + __("evaluation.resolved") + "",
			"" + __("evaluation.unsolved") + "

",
			"" + tipWord + "",
			"

",
			"

",
			"<textarea spellcheck=\"false\" placeholder=\"" + __("evaluation.review") + "\"></textarea>",
			"
"
		].join(""))
			:
			utils.createElementFromHTML([
				"
",
				"" + tipWord + "",
				"

",
				"

",
				"<textarea spellcheck=\"false\" placeholder=\"" + __("evaluation.review") + "\"></textarea>",
				"
"
			].join(""));
		starsUl = dom.querySelector("ul");
		commentDom = dom.querySelector("textarea");
		tagContainer = dom.querySelector(".tag-container");
		resolvedBtn = dom.querySelectorAll(".resolve-btn");
		resolvedDom = dom.querySelector(".resolved");

		utils.live(".resolve-btn", "click", function(){
			utils.removeClass(resolvedBtn, "selected bg-color");
			utils.addClass(this, "selected bg-color");
			if(color){
				$(".resolve-btn").css("cssText","background-color: #fff !important");
				$(".theme_custom").find(".bg-color").css("cssText","background-color: " + color + " !important");
			}
			resolvedId = this.dataset.num;
			if(fiveStarState){
				if(resolvedId == 1){
					utils.addClass(starList, "sel");
					score = defaultScore;
				}
				else{
					utils.removeClass(starList, "sel");
					score = false;
				}
			}
		});

		utils.live("li", "click", function(){
			var level = +this.getAttribute("data-level");

			evaluationDegreeId = this.getAttribute("data-evaluate-id");
			score = this.getAttribute("data-score");
			isSingleTag = this.getAttribute("data-isSingleTag");
			level && _.each(starList, function(elem, i){
				utils.toggleClass(elem, "sel", i < level);
			});

			evaluationDegreeId && _createLabel(evaluationDegreeId);
		}, starsUl);

		utils.live("span.tag", "click", function(){
			var selectedTagNodeList = tagContainer.querySelectorAll(".selected");
			if(isSingleTag == "true"){
				utils.removeClass(selectedTagNodeList, "selected");
				utils.toggleClass(this, "selected");
			}
			else{
				utils.toggleClass(this, "selected");
			}

		}, tagContainer);

		dialog = uikit.createDialog({
			contentDom: dom,
			className: "satisfaction"
		}).addButton({
			confirmText: __("common.submit"),
			confirm: _confirm,
		});
		loading.hide("satisfaction");
		dialog.show();

		// 火狐浏览器 _setSatisfaction时找不到starsUl，所以必须先执行完init
		_setSatisfaction();

		// 自定义主题色
		color && $(".theme_custom").find(".bg-color").css("cssText","background-color: " + color + " !important");
	});
}

function _clear(){
	commentDom.blur();
	commentDom.value = "";
	score = null;
	// clear stars
	utils.removeClass(starList, "sel");
	// clear label
	tagContainer.innerHTML = "";
	// clear resolvedBtn
	utils.removeClass(resolvedBtn, "selected bg-color");
	utils.addClass(resolvedDom, "selected bg-color");

	resolvedId = 1;

}

function _sendSatisfaction(score, content, session, invite, appraiseTags, resolutionParam, evaluationDegreeId){
	var data = {
		ext: {
			weichat: {
				ctrlType: "enquiry",
				ctrlArgs: {
					// 后端类型要求，inviteId必须传数字
					inviteId: invite || 0,
					serviceSessionId: session || profile.currentOfficialAccount.sessionId || "",
					detail: content,
					summary: score,
					appraiseTags: appraiseTags,
					resolutionParam: resolutionParam,
					evaluationDegreeId: evaluationDegreeId,
					// 评价方式，由前端传入：visitor - 访客主动评价; agent - 坐席邀请; system - 强制邀请,访客点击关闭窗口或会话结束
					evaluateWay: evaluateType
				}
			}
		}
	};
	if(!sessionResolved){
		delete data.ext.weichat.ctrlArgs.resolutionParam;
	}
	channel.sendText("", data);
}

function _setSatisfaction(){
	apiHelper.getEvaluationDegrees().then(function(entities){
		var labelID;
		var lastScore;
		starsUl.innerHTML = _.chain(entities)
		.sortBy("level")
		.map(function(elem, index){
			// stat level 1-based
			var level = index + 1;
			var name = elem.name;
			var id = elem.id;
			var score = elem.score;
			var isSingleTag = elem.isSingleTag;
			labelID = id;
			lastScore = score;

			return "
H
";
		})
		.value()
		.join("");

		starList = starsUl.querySelectorAll("li");
		defaultScore = lastScore
		if(fiveStarState){
			if(resolvedId == 1){
				utils.addClass(starList, "sel");
				//创建评价标签
				_createLabel(labelID);
				score = defaultScore;
			}
			else{
				utils.removeClass(starList, "sel");
				score = false;
			}
		}

	});
}

function _createLabel(evaluateId){
	apiHelper.getAppraiseTags(evaluateId).then(function(entities){
		tagContainer.innerHTML = _.map(entities, function(elem){
			var name = elem.name;
			var id = elem.id;

			return "" + name + "";
		}).join("");
		utils.removeClass(tagContainer, "hide");
	});
}

function _confirm(){
	var selectedTagNodeList = tagContainer.querySelectorAll(".selected");
	var tagNodeList = tagContainer.querySelectorAll(".tag");
	var content = commentDom.value;
	var appraiseTags = _.map(selectedTagNodeList, function(elem){
		return {
			id: elem.getAttribute("data-label-id"),
			name: elem.innerText
		};
	});
	var resolutionParam = [{
		id: resolvedId,
		name: resolvedId == 1 ? "已解决" : "未解决",
		score: resolvedId,
		resolutionParamTags: []
	}];

	// 必须选择星级
	if(!score){
		uikit.tip(__("evaluation.select_level_please"));
		// 防止对话框关闭
		return false;
	}
	// 若有标签则至少选择一个
	else if(tagNodeList.length > 0 && selectedTagNodeList.length === 0){
		uikit.tip(__("evaluation.select_tag_please"));
		// 防止对话框关闭
		return false;
	}

	_sendSatisfaction(score, content, session, invite, appraiseTags, resolutionParam, evaluationDegreeId);
	uikit.showSuccess(__("evaluation.submit_success"));
	getToHost.send({ event: _const.EVENTS.EVALUATIONSUBMIT });
	// 强制评价点击确定关闭会话框
	setTimeout(function(){
		// 关闭会话
		if(evaluateType === "system"){
			// 取消轮询接口
			eventListener.trigger(_const.SYSTEM_EVENT.CHAT_CLOSED);
			profile.currentOfficialAccount.sessionId && apiHelper.closeChatDialog({ serviceSessionId: profile.currentOfficialAccount.sessionId });
			getToHost.send({ event: _const.EVENTS.CLOSE });
		}
	}, 2000);
	_clear();
}

function show(inviteId, serviceSessionId, evaluateWay){

	apiHelper.getEvaluteSolveWord().then(function(tip){
		resolveTip = tip;
	});
	apiHelper.getServiceSessionResolved()
	.then(function(resp){
		sessionResolved = resp;
		_initOnce();
	});

	session = serviceSessionId;
	invite = inviteId;
	evaluateType = evaluateWay;
	_setDefaultScore();
	dialog && dialog.show();
}

function _setDefaultScore(){
	if(!starsUl){
		return false;
	}
	_setSatisfaction();
}

function init(){
	eventListener.add(
		_const.SYSTEM_EVENT.SATISFACTION_EVALUATION_MESSAGE_RECEIVED,
		function(officialAccount, inviteId, serviceSessionId){
			if(officialAccount !== profile.currentOfficialAccount) return;
			show(inviteId, serviceSessionId, "system");
		}
	);
}
<|endoftext|>


<commit_before>$(document).ready(function() {

    function webmining(e) {
        var loadingImage = $('#loading-image-path').attr('value');
        $('a.web-mining-button').parent('div').append('');
        $("a.web-mining-button").click(function(e) {
            e.preventDefault();
        });
        $("a.web-mining-button").off('click.webmining', webmining);
        $("a.web-mining-button").addClass("disabled-webmining-button");
        var url = $('.webmining-url').attr('value');
        url += '/' + $('.resource-code').val();
        $.ajax({
            type: "POST",
            url: url,
            cache: false,
            success: function(json) {
                var resource = JSON && JSON.parse(json) || $.parseJSON(json);
                if (resource.description.length === 0) {
                    $(".web-mining-image-url").attr('value', "");
                    $(".web-mining-description").val("");
                    $(".web-mining-long-description").text(resource.longDescription.replace(/\\r\\n/g, '\r\n'));
                    $("#modal").addClass("modal-visible");
                } else {
                    $(".web-mining-image-url").attr('value', resource.image);
                    $(".web-mining-description").val(resource.description);
                    $(".web-mining-long-description").text(resource.longDescription.replace(/\\r\\n/g, '\r\n'));
                }
                $("a.web-mining-button").on('click.webmining', webmining);
                $("a.web-mining-button").removeClass("disabled-webmining-button");
                if ($('#apply-image').attr('value') !== "") {
                    $('#apply-image').click();
                } else {
                    eraseURL();
                    document.getElementById('caesar_resourceBundle_resourceType_path').value = "";
                }
                $('#loading-webmining').remove();
            },
            error: function() {
                $("a.web-mining-button").on('click.webmining', webmining);
                $("a.web-mining-button").removeClass("disabled-webmining-button");
                $('#loading-webmining').remove();
            }
        });

        e.preventDefault();
        return false; // Empêche la redirection normale
    }

    function disableWebminingButton() {
        var code = $('.resource-code').val();
        if (code === "" || !isValidIsbn(code)) {
            $("a.web-mining-button").click(function(e) {
                e.preventDefault();
            });
            $("a.web-mining-button").addClass("disabled-webmining-button");
            $("a.web-mining-button").off('click.webmining', webmining);
        } else {
            $("a.web-mining-button").removeClass("disabled-webmining-button");
            $("a.web-mining-button").on('click.webmining', webmining);
        }
    }
    $(".btn").click(function(e) {
        $("#modal").removeClass("modal-visible");
        e.preventDefault();
        return false; // Empêche la redirection normale
    });

    $('.resource-code').keyup(disableWebminingButton);

    $("a.web-mining-button").on('click.webmining', webmining);
    disableWebminingButton();

    $("#clearSkeleton").on('click', function(e) {
        var url = $('.empty-skeleton-url').attr('value');
        $.ajax({
            type: "POST",
            url: url,
            cache: false,
            success: function(skeleton) {
                $(".web-mining-long-description").text(skeleton.replace(/\\r\\n/g, '\r\n'));
            },
            error: function() {
                $(".web-mining-long-description").text('Error');
            }
        });

        e.preventDefault();
        return false; // Empêche la redirection normale
    });
});<commit_msg>fix js bug<commit_after>$(document).ready(function() {
    var looking = false;
    var disabled = false;
    function webmining(e) {
        if (looking || disabled) {
            return;
        }
        looking = true;
        var loadingImage = $('#loading-image-path').attr('value');
        $('a.web-mining-button').parent('div').append('');
        $("a.web-mining-button").addClass("disabled-webmining-button");
        var url = $('.webmining-url').attr('value');
        url += '/' + $('.resource-code').val();
        $.ajax({
            type: "POST",
            url: url,
            cache: false,
            success: function(json) {
                var resource = JSON && JSON.parse(json) || $.parseJSON(json);
                if (resource.description.length === 0) {
                    $(".web-mining-image-url").attr('value', "");
                    $(".web-mining-description").val("");
                    $(".web-mining-long-description").text(resource.longDescription.replace(/\\r\\n/g, '\r\n'));
                    $("#modal").addClass("modal-visible");
                } else {
                    $(".web-mining-image-url").attr('value', resource.image);
                    $(".web-mining-description").val(resource.description);
                    $(".web-mining-long-description").text(resource.longDescription.replace(/\\r\\n/g, '\r\n'));
                }
                $("a.web-mining-button").removeClass("disabled-webmining-button");
                if ($('#apply-image').attr('value') !== "") {
                    $('#apply-image').click();
                } else {
                    eraseURL();
                    document.getElementById('caesar_resourceBundle_resourceType_path').value = "";
                }
                $('#loading-webmining').remove();
                looking = false;
            },
            error: function() {
                $("a.web-mining-button").removeClass("disabled-webmining-button");
                $('#loading-webmining').remove();
                looking = false;
            }
        });

        e.preventDefault();
        return false; // Empêche la redirection normale
    }

    function disableWebminingButton() {
        var code = $('.resource-code').val();
        if (code === "" || !isValidIsbn(code)) {
            disabled = true;
            $("a.web-mining-button").addClass("disabled-webmining-button");
        } else {
            $("a.web-mining-button").removeClass("disabled-webmining-button");
            disabled = false;
        }
    }
    $(".btn").click(function(e) {
        $("#modal").removeClass("modal-visible");
        e.preventDefault();
        return false; // Empêche la redirection normale
    });

    $('.resource-code').keyup(disableWebminingButton);

    $("a.web-mining-button").on('click.webmining', webmining);
    disableWebminingButton();

    $("#clearSkeleton").on('click', function(e) {
        var url = $('.empty-skeleton-url').attr('value');
        $.ajax({
            type: "POST",
            url: url,
            cache: false,
            success: function(skeleton) {
                $(".web-mining-long-description").text(skeleton.replace(/\\r\\n/g, '\r\n'));
            },
            error: function() {
                $(".web-mining-long-description").text('Error');
            }
        });

        e.preventDefault();
        return false; // Empêche la redirection normale
    });
});<|endoftext|>