<commit_before>define(['override', 'jquery', 'utils'], function(override, $, utils) {

    "use strict";

    return function(grid, pluginOptions) {
        override(grid, function($super) {
            return {
                renderCell: function(record, column, rowIndex, columnIndex) {
                    var cell = $super.renderCell.apply(this, arguments);

                    var editable = this.editing.isEditable(record, column);
                    if(editable) {
                        cell.addClass("pg-editable");
                    }

                    return cell;
                },

                init: function() {
                    var grid = this;

                    $super.init();

                    this.container.on("click", ".pg-cell.pg-editable", function(event) {
                        var targetCell = event.target;
                        while(targetCell && !$(targetCell).is('.pg-cell')) {
                            targetCell = targetCell.parentNode;
                        }

                        var key = $(targetCell).attr('data-column-key');
                        var rowId = $(targetCell).parents(".pg-row:eq(0)").data('row-id');
                        var rowIdx = $(targetCell).parents(".pg-row:eq(0)").data('row-idx');
                        var record = grid.dataSource.getRecordById(rowId);

                        grid.editing.startEdit(targetCell, key, record, rowIdx);
                    });

                    $(this.dataSource).on('editabilitychanged', function(event, attr) {
                        grid.editing.updateEditability(attr.values);
                    });
                },

                editing: {
                    grid: grid,
                    editors: {},

                    addEditor: function(column, editor) {
                        this.editors[column.key] = editor;
                    },

                    isEditable: function(record, column) {
                        var editable = column.editable;
                        if(editable && typeof pluginOptions.isEditable === 'function') {
                            editable = pluginOptions.isEditable.apply(grid, [record, column]);
                        }
                        return editable;
                    },

                    startEdit: function(target, key, record, rowIdx) {
                        var column = grid.getColumnForKey(key);
                        var oldValue = record[key];
                        var editor = this.createEditor(record, column, oldValue);
                        var editing = this;

                        grid.scrollToCell(rowIdx, key);

                        if($(target).is('.pg-editing')) return;

                        if(!column.editable) return;

                        var opts = {
                            cell: target,
                            key: key,
                            record: record,
                            rowIdx: rowIdx,
                            column: column
                        };

                        var beforeEditEvent = new $.Event('beforeedit', opts);
                        grid.trigger(beforeEditEvent);

                        if(beforeEditEvent.isDefaultPrevented()) {
                            return;
                        }

                        $(editor).on('commit', function(event, value, move) {
                            utils.inAnimationFrame(function() {
                                editing.commit(target, record, rowIdx, column, value, oldValue, move);
                            });
                        }).on('abort', function(event) {
                            utils.inAnimationFrame(function() {
                                editing.abort(target, record, rowIdx, column, oldValue);
                            });
                        });
                        $(target).addClass('pg-editing').empty().append(editor);
                    },

                    commit: function(target, record, rowIdx, column, value, oldValue, move) {
                        grid.dataSource.setValue(record.id, column.key, value);
                        this.endEdit(target, record, rowIdx, column, grid.dataSource.getRecordById(record.id)[column.key]);

                        var nextRowIdx = rowIdx, nextColumn = column, nextRecord = record;

                        if(move) {
                            switch(move) {
                                case 1:
                                case -1:
                                    do {
                                        nextRowIdx += move;
                                        nextRecord = grid.dataSource.getData(nextRowIdx, nextRowIdx+1)[0];
                                    } while(nextRecord && !this.isEditable(nextRecord, nextColumn));
                                    break;
                                case 2:
                                case -2:
                                    var i = grid.getColumnIndexForKey(column.key);
                                    do {
                                        i += move / 2;
                                        if(i >= grid.columnCount() || i < 0) {
                                            nextRowIdx += move / 2;
                                            nextRecord = grid.dataSource.getData(nextRowIdx, nextRowIdx+1)[0];
                                            i = move < 0 ? grid.columnCount() - 1 : 0;
                                        }
                                        nextColumn = grid.getColumnForIndex(i);
                                    } while(nextRecord && !this.isEditable(nextRecord, nextColumn));
                                    break;
                            }

                            if(nextRecord) {
                                var targetCell = grid.getCellFor(nextRecord.id, nextColumn.key);

                                this.startEdit(targetCell, nextColumn.key, nextRecord, nextRowIdx);
                            }
                        }
                    },

                    abort: function(target, record, rowIdx, column, oldValue) {
                        this.endEdit(target, record, rowIdx, column, oldValue);
                    },

                    endEdit: function(target, record, rowIdx, column, value) {
                        $(target).removeClass('pg-editing');
                        grid.updateCellValue(record.id, column.key);
                    },

                    createEditor: function(record, column, value) {
                        var editor;
                        if (pluginOptions.editors && pluginOptions.editors[column.type]) {
                            editor = pluginOptions.editors[column.type](record, column, value);
                        } else {
                            editor = $("<input>").attr("type", column.type).val(value);
                        }
                        var grid = this, hasChanged = false;
                        editor.on("keydown", function(event) {
                            switch(event.keyCode) {
                            case 13:
                                event.preventDefault();
                                $(this).trigger('commit', [editor.val(), event.shiftKey ? -1 : 1]); break;
                            case 27:
                                event.preventDefault();
                                $(this).trigger('abort'); break;
                            case 9:
                                event.preventDefault();
                                $(this).trigger('commit', [editor.val(), event.shiftKey ? -2 : 2]); break;
                            }
                        });

                        editor.on("blur", function(event) {
                            if(pluginOptions.commitOnBlur !== false && hasChanged) {
                                $(this).trigger('commit', [editor.val()]);
                            } else if(pluginOptions.abortOnBlur === true || !hasChanged) {
                                $(this).trigger('abort');
                            }
                        }).on("change", function(event) {
                            hasChanged = true;
                        });

                        if (editor[0].select) {
                            setTimeout(editor[0].select.bind(editor[0]), 10);
                        } else if (editor[0].focus) {
                            setTimeout(editor[0].focus.bind(editor[0]), 10);
                        }
                        return editor;
                    },

                    updateEditability: function(cells) {
                        for(var x=0,l=cells.length;x<l;x++) {
                            var cell = cells[x],
                                column = grid.getColumnForKey(cell.key),
                                row = grid.getRecordById(cell.id),
                                cellElement = column && row && grid.getCellFor(cell.id, cell.key);
                            if(cellElement) {
                                this.updateCellEditability(row, column, cellElement);
                            }
                        }
                    },

                    updateCellEditability: function(row, column, cellElement) {
                        $(cellElement).toggleClass("pg-editable", this.isEditable(row, column));
                    }
                }
            }
        });
    };

});<commit_msg>make editing more resilient<commit_after>define(['override', 'jquery', 'utils'], function(override, $, utils) {

    "use strict";

    return function(grid, pluginOptions) {
        override(grid, function($super) {
            return {
                renderCell: function(record, column, rowIndex, columnIndex) {
                    var cell = $super.renderCell.apply(this, arguments);

                    var editable = this.editing.isEditable(record, column);
                    if(editable) {
                        cell.addClass("pg-editable");
                    }

                    return cell;
                },

                init: function() {
                    var grid = this;

                    $super.init();

                    this.container.on("click", ".pg-cell.pg-editable", function(event) {
                        var targetCell = event.target;
                        while(targetCell && !$(targetCell).is('.pg-cell')) {
                            targetCell = targetCell.parentNode;
                        }

                        var key = $(targetCell).attr('data-column-key');
                        var rowId = $(targetCell).parents(".pg-row:eq(0)").data('row-id');
                        var rowIdx = $(targetCell).parents(".pg-row:eq(0)").data('row-idx');
                        var record = grid.dataSource.getRecordById(rowId);

                        grid.editing.startEdit(targetCell, key, record, rowIdx);
                    });

                    $(this.dataSource).on('editabilitychanged', function(event, attr) {
                        grid.editing.updateEditability(attr.values);
                    });
                },

                editing: {
                    grid: grid,
                    editors: {},

                    addEditor: function(column, editor) {
                        this.editors[column.key] = editor;
                    },

                    isEditable: function(record, column) {
                        var editable = column.editable;
                        if(editable && typeof pluginOptions.isEditable === 'function') {
                            editable = pluginOptions.isEditable.apply(grid, [record, column]);
                        }
                        return editable;
                    },

                    startEdit: function(target, key, record, rowIdx) {
                        var column = grid.getColumnForKey(key);
                        var oldValue = record[key];
                        var editor = this.createEditor(record, column, oldValue);
                        var editing = this;

                        grid.scrollToCell(rowIdx, key);

                        if($(target).is('.pg-editing')) return;

                        if(!column.editable) return;

                        var opts = {
                            cell: target,
                            key: key,
                            record: record,
                            rowIdx: rowIdx,
                            column: column
                        };

                        var beforeEditEvent = new $.Event('beforeedit', opts);
                        grid.trigger(beforeEditEvent);

                        if(beforeEditEvent.isDefaultPrevented()) {
                            return;
                        }

                        $(editor).on('commit', function(event, value, move) {
                            utils.inAnimationFrame(function() {
                                editing.commit(target, record, rowIdx, column, value, oldValue, move);
                            });
                        }).on('abort', function(event) {
                            utils.inAnimationFrame(function() {
                                editing.abort(target, record, rowIdx, column, oldValue);
                            });
                        });
                        $(target).addClass('pg-editing').empty().append(editor);
                    },

                    commit: function(target, record, rowIdx, column, value, oldValue, move) {
                        try {
                            grid.dataSource.setValue(record.id, column.key, value);
                        } catch(e) {
                            console.error("Exception while committing value", record, column, value, e);
                        }
                        this.endEdit(target, record, rowIdx, column, grid.dataSource.getRecordById(record.id)[column.key]);

                        var nextRowIdx = rowIdx, nextColumn = column, nextRecord = record;

                        if(move) {
                            switch(move) {
                                case 1:
                                case -1:
                                    do {
                                        nextRowIdx += move;
                                        nextRecord = grid.dataSource.getData(nextRowIdx, nextRowIdx+1)[0];
                                    } while(nextRecord && !this.isEditable(nextRecord, nextColumn));
                                    break;
                                case 2:
                                case -2:
                                    var i = grid.getColumnIndexForKey(column.key);
                                    do {
                                        i += move / 2;
                                        if(i >= grid.columnCount() || i < 0) {
                                            nextRowIdx += move / 2;
                                            nextRecord = grid.dataSource.getData(nextRowIdx, nextRowIdx+1)[0];
                                            i = move < 0 ? grid.columnCount() - 1 : 0;
                                        }
                                        nextColumn = grid.getColumnForIndex(i);
                                    } while(nextRecord && !this.isEditable(nextRecord, nextColumn));
                                    break;
                            }

                            if(nextRecord) {
                                var targetCell = grid.getCellFor(nextRecord.id, nextColumn.key);

                                this.startEdit(targetCell, nextColumn.key, nextRecord, nextRowIdx);
                            }
                        }
                    },

                    abort: function(target, record, rowIdx, column, oldValue) {
                        this.endEdit(target, record, rowIdx, column, oldValue);
                    },

                    endEdit: function(target, record, rowIdx, column, value) {
                        $(target).removeClass('pg-editing');
                        grid.updateCellValue(record.id, column.key);
                    },

                    createEditor: function(record, column, value) {
                        var editor;
                        if (pluginOptions.editors && pluginOptions.editors[column.type]) {
                            editor = pluginOptions.editors[column.type](record, column, value);
                        } else {
                            editor = $("<input>").attr("type", column.type).val(value);
                        }
                        var grid = this, hasChanged = false;
                        editor.on("keydown", function(event) {
                            switch(event.keyCode) {
                            case 13:
                                event.preventDefault();
                                $(this).trigger('commit', [editor.val(), event.shiftKey ? -1 : 1]); break;
                            case 27:
                                event.preventDefault();
                                $(this).trigger('abort'); break;
                            case 9:
                                event.preventDefault();
                                $(this).trigger('commit', [editor.val(), event.shiftKey ? -2 : 2]); break;
                            }
                        });

                        editor.on("blur", function(event) {
                            if(pluginOptions.commitOnBlur !== false && hasChanged) {
                                $(this).trigger('commit', [editor.val()]);
                            } else if(pluginOptions.abortOnBlur === true || !hasChanged) {
                                $(this).trigger('abort');
                            }
                        }).on("change", function(event) {
                            hasChanged = true;
                        });

                        if (editor[0].select) {
                            setTimeout(editor[0].select.bind(editor[0]), 10);
                        } else if (editor[0].focus) {
                            setTimeout(editor[0].focus.bind(editor[0]), 10);
                        }
                        return editor;
                    },

                    updateEditability: function(cells) {
                        for(var x=0,l=cells.length;x<l;x++) {
                            var cell = cells[x],
                                column = grid.getColumnForKey(cell.key),
                                row = grid.getRecordById(cell.id),
                                cellElement = column && row && grid.getCellFor(cell.id, cell.key);
                            if(cellElement) {
                                this.updateCellEditability(row, column, cellElement);
                            }
                        }
                    },

                    updateCellEditability: function(row, column, cellElement) {
                        $(cellElement).toggleClass("pg-editable", this.isEditable(row, column));
                    }
                }
            }
        });
    };

});<|endoftext|>


<commit_before>/**
 * Created by 166878 on 20.09.2016.
 */
function certificateToStr(certificate){
    return  "" +
            "   " + certificate.id + "" +
            "   " + certificate.flight_type +
            " ";
}
function getHourRow(hour){
    var now= new Date();
    var hours_change = -(now.getTimezoneOffset())/60;
    var hourToShow=parseInt(hour);//+hours_change;
    console.log("Время при запросе:");
    console.log("Пришедшее: ", hour);
    // console.log("Смещение:", hours_change);
    console.log("Показываемое:", hourToShow);
    return  "
" +
            "   " + hourToShow + ":00	" +
            "   " +
            "

" +
            "   	" +
            "
";
}

function showModal(date){
    //Showing modal window with per-day schedule table
    $("#chosen_date").html(date.format("DD.MM.YYYY"));
    $(".current-date").html(date.format("YYYY-MM-DD"));
    $("#time_table").find(".hour-row").remove();
    $("#found_certs").find(".cert_row").remove();
    $(".day-empty").addClass("hidden");
    $("#myModal").modal("show");

    //Retrieving per-day schedule
    var chosen_date = date.unix();
    getTimeTableData(chosen_date);
    findCertificates();
}
function fillTimeTableWithData(table_selector, data){
    //If there is more than one busy hour
    if (Object.keys(data).length > 0) {

        //Iterating over the hours
        for (var hour in data) {
            //Retrieve next hour
            if (!data.hasOwnProperty(hour)) {
                continue;
            }
            var certificates_in_hour = data[hour];
            var curDate = new Date();
            var currentTimeZoneOffsetInHours = -curDate.getTimezoneOffset()/60;
            //If there is more than one flight in that hour
            if (certificates_in_hour.length != 0) {
                //Creating new hour row in table
                $(table_selector).append(getHourRow(hour));

                //Iterating over the flights in this hour and rendering them
                certificates_in_hour.forEach(function(item, i, arr){
                    $(table_selector + " .certificates-in-hour-"+hour).append(certificateToStr(item));
                });
            }
        }
    }
    //Otherwise showing the string telling the day is empty
    else {
        $(table_selector + " .day-empty").removeClass("hidden");
    }
}
function getTimeTableData(date){
    $("#time_table_loader").removeClass("hidden");
    jQuery.getJSON("/admin/show_day_schedule?date="+date, function (data){
        $("#time_table_loader").addClass("hidden");
        fillTimeTableWithData("#time_table", data);
    });
}

function getCertRow(cert) {
    return "
" +
        "   " +
        "       "+cert.ID_Sertificate+"" +
        "   	" +
        "   "+
                cert.name + " " + cert.last_name + "" +
        "   	" +
        "   " +
        "       <button class='btn btn-xs btn-default' data-toggle='collapse' data-target='#" + cert.ID_Sertificate + "'>" +
        "           " +
        "       </button>" +
        "   	" +
        "
" +
        "
" +
        "    " +
        "
" +
        "               <input type='text' class='form-control' placeholder='Часы' id='hours-"+cert.ID_Sertificate+"'>" +
        "               :" +
        "               <input type='text' class='form-control' placeholder='Минуты' id='minutes-"+cert.ID_Sertificate+"'>" +
        "               "+
        "                   <button class='btn btn-default set-use-time-btn' type='button' data-certificate-id='"+ cert.ID_Sertificate +"'>Ok</button>" +
        "               " +
        "
" +
        "   	" +
        "
"
}

function onYesSetTime(event){
    var modal_window = event.data;
    var date = moment(modal_window.data.date).unix();
    var certificate_id = JSON.stringify([modal_window.data.certificate_id]);
    var fieldnames = JSON.stringify(["use_time"]);
    var fieldvalues = JSON.stringify([date]);
    modal_window.showLoader();

    $("#time_table" + " .day-empty").addClass("hidden");
    //TODO: Make post query to set use_time to certificate
    jQuery.post("/certificate/edit", {ids : certificate_id, field_names : fieldnames, field_values: fieldvalues}, function (data) {
        console.log(data);
        $("#time_table").find(".hour-row").remove();
        $("#found_certs").find(".cert_row").remove();
        getTimeTableData(date);
        findCertificates();
    });
    modal_window.hideLoader();
    modal_window.close();

}

function onNoSetTime(event){

}

function onSetUseTime(event){
    var btn = $(this);

    var certificate_id = $(this).data("certificate-id");
    if (certificate_id == "undefined"){
        return false;
    }
    var now= new Date();
    var hours_change = -(now.getTimezoneOffset())/60;
    var hours = parseInt($("#hours-"+certificate_id).val())+hours_change;
    var hoursToShow = $("#hours-"+certificate_id).val();
    var minutes = $("#minutes-"+certificate_id).val();
    var seconds = "00";
    var date=$(".current-date").html() + " " + [hours, minutes, seconds].join(":");
    var dateToShow=$(".current-date").html() + " " + [hoursToShow, minutes, seconds].join(":");

    console.log("Время при добавлении:");
    console.log("Показываемое:", hoursToShow);
    console.log("Смещение:", hours_change);
    console.log("Отправляемое: ", hours);

    //ToDo check validate time
    var dialog = new YesNoDialog();
    dialog.setModalSelector("#yes-no-modal");
    dialog.show({
        caption: "Установка времени",
        message: dateToShow,

        yes_caption: "Установить",
        no_caption: "Отмена",

        data: {
            "certificate_id": certificate_id,
            "date": date
        },

        yes_handler: onYesSetTime,
        no_handler: onNoSetTime
    });

    return true;
}

function fillCertsListWithData(table_selector,data){
    data.forEach(function(item) {
       $(table_selector).append(getCertRow(item))
    });
    $(".set-use-time-btn").click(onSetUseTime);
    $("#find_cert").click(data, findByIDCertificate);
    $("#clear_filter").click(data, clearSearchFilter);
}

function findCertificates() {
    $("#found_cert_loader").removeClass("hidden");
    var fields = JSON.stringify(["ID_Sertificate", "flight_type", "cert_link", "name", "last_name"]);
    var criteria = JSON.stringify({ "ID_SertState": [5]});
    jQuery.post("/certificate/select", {field_names : fields, criteria : criteria}, function (data) {
        $("#found_cert_loader").addClass("hidden");
        fillCertsListWithData("#found_certs",data)
    })

}

function findByIDCertificate(data){
    var id = $("#cert_id_for_watching").val();
    var found = false;
    var certificate_list = data.data;

    certificate_list.forEach(function (item) {
        if (item.ID_Sertificate == id){
            $("#found_certs").find(".cert_row").remove();
            $("#found_certs").append(getCertRow(item));
            found = true;
        }
    });
    if (!found){
        $("#found_certs").find(".cert_row").remove();
        $("#found_certs").append("
Сертификат не найдет
");
    }
}

function clearSearchFilter(event){
    var certificate_list = event.data;
    $("#cert_id_for_watching").val("");
    $("#found_certs").find(".cert_row").remove();

    certificate_list.forEach(function (item) {
        $("#found_certs").append(getCertRow(item));
    });
}

$(document).ajaxError(function(event, jqXHR, ajaxSettings, message){
    console.log(message);
});

$(document).ready(function(e){

    $("#calendar").fullCalendar({
        monthNames: ["Январь","Февраль","Март","Апрель","Май","Июнь","Июль","Август","Сентябрь","Октябрь","Ноябрь","Декабрь"],
        header: {
            left: 'title',
            right: 'today, prev, next'
        },
        dayClick: showModal
    });
});<commit_msg>Added target="_blank" to flight_shedule<commit_after>/**
 * Created by 166878 on 20.09.2016.
 */
function certificateToStr(certificate){
    return  "" +
            "   " + certificate.id + "" +
            "   " + certificate.flight_type +
            " ";
}
function getHourRow(hour){
    var now= new Date();
    var hours_change = -(now.getTimezoneOffset())/60;
    var hourToShow=parseInt(hour);//+hours_change;
    console.log("Время при запросе:");
    console.log("Пришедшее: ", hour);
    // console.log("Смещение:", hours_change);
    console.log("Показываемое:", hourToShow);
    return  "
" +
            "   " + hourToShow + ":00	" +
            "   " +
            "

" +
            "   	" +
            "
";
}

function showModal(date){
    //Showing modal window with per-day schedule table
    $("#chosen_date").html(date.format("DD.MM.YYYY"));
    $(".current-date").html(date.format("YYYY-MM-DD"));
    $("#time_table").find(".hour-row").remove();
    $("#found_certs").find(".cert_row").remove();
    $(".day-empty").addClass("hidden");
    $("#myModal").modal("show");

    //Retrieving per-day schedule
    var chosen_date = date.unix();
    getTimeTableData(chosen_date);
    findCertificates();
}
function fillTimeTableWithData(table_selector, data){
    //If there is more than one busy hour
    if (Object.keys(data).length > 0) {

        //Iterating over the hours
        for (var hour in data) {
            //Retrieve next hour
            if (!data.hasOwnProperty(hour)) {
                continue;
            }
            var certificates_in_hour = data[hour];
            var curDate = new Date();
            var currentTimeZoneOffsetInHours = -curDate.getTimezoneOffset()/60;
            //If there is more than one flight in that hour
            if (certificates_in_hour.length != 0) {
                //Creating new hour row in table
                $(table_selector).append(getHourRow(hour));

                //Iterating over the flights in this hour and rendering them
                certificates_in_hour.forEach(function(item, i, arr){
                    $(table_selector + " .certificates-in-hour-"+hour).append(certificateToStr(item));
                });
            }
        }
    }
    //Otherwise showing the string telling the day is empty
    else {
        $(table_selector + " .day-empty").removeClass("hidden");
    }
}
function getTimeTableData(date){
    $("#time_table_loader").removeClass("hidden");
    jQuery.getJSON("/admin/show_day_schedule?date="+date, function (data){
        $("#time_table_loader").addClass("hidden");
        fillTimeTableWithData("#time_table", data);
    });
}

function getCertRow(cert) {
    return "
" +
        "   " +
        "       "+cert.ID_Sertificate+"" +
        "   	" +
        "   "+
                cert.name + " " + cert.last_name + "" +
        "   	" +
        "   " +
        "       <button class='btn btn-xs btn-default' data-toggle='collapse' data-target='#" + cert.ID_Sertificate + "'>" +
        "           " +
        "       </button>" +
        "   	" +
        "
" +
        "
" +
        "    " +
        "
" +
        "               <input type='text' class='form-control' placeholder='Часы' id='hours-"+cert.ID_Sertificate+"'>" +
        "               :" +
        "               <input type='text' class='form-control' placeholder='Минуты' id='minutes-"+cert.ID_Sertificate+"'>" +
        "               "+
        "                   <button class='btn btn-default set-use-time-btn' type='button' data-certificate-id='"+ cert.ID_Sertificate +"'>Ok</button>" +
        "               " +
        "
" +
        "   	" +
        "
"
}

function onYesSetTime(event){
    var modal_window = event.data;
    var date = moment(modal_window.data.date).unix();
    var certificate_id = JSON.stringify([modal_window.data.certificate_id]);
    var fieldnames = JSON.stringify(["use_time"]);
    var fieldvalues = JSON.stringify([date]);
    modal_window.showLoader();

    $("#time_table" + " .day-empty").addClass("hidden");
    //TODO: Make post query to set use_time to certificate
    jQuery.post("/certificate/edit", {ids : certificate_id, field_names : fieldnames, field_values: fieldvalues}, function (data) {
        console.log(data);
        $("#time_table").find(".hour-row").remove();
        $("#found_certs").find(".cert_row").remove();
        getTimeTableData(date);
        findCertificates();
    });
    modal_window.hideLoader();
    modal_window.close();

}

function onNoSetTime(event){

}

function onSetUseTime(event){
    var btn = $(this);

    var certificate_id = $(this).data("certificate-id");
    if (certificate_id == "undefined"){
        return false;
    }
    var now= new Date();
    var hours_change = -(now.getTimezoneOffset())/60;
    var hours = parseInt($("#hours-"+certificate_id).val())+hours_change;
    var hoursToShow = $("#hours-"+certificate_id).val();
    var minutes = $("#minutes-"+certificate_id).val();
    var seconds = "00";
    var date=$(".current-date").html() + " " + [hours, minutes, seconds].join(":");
    var dateToShow=$(".current-date").html() + " " + [hoursToShow, minutes, seconds].join(":");

    console.log("Время при добавлении:");
    console.log("Показываемое:", hoursToShow);
    console.log("Смещение:", hours_change);
    console.log("Отправляемое: ", hours);

    //ToDo check validate time
    var dialog = new YesNoDialog();
    dialog.setModalSelector("#yes-no-modal");
    dialog.show({
        caption: "Установка времени",
        message: dateToShow,

        yes_caption: "Установить",
        no_caption: "Отмена",

        data: {
            "certificate_id": certificate_id,
            "date": date
        },

        yes_handler: onYesSetTime,
        no_handler: onNoSetTime
    });

    return true;
}

function fillCertsListWithData(table_selector,data){
    data.forEach(function(item) {
       $(table_selector).append(getCertRow(item))
    });
    $(".set-use-time-btn").click(onSetUseTime);
    $("#find_cert").click(data, findByIDCertificate);
    $("#clear_filter").click(data, clearSearchFilter);
}

function findCertificates() {
    $("#found_cert_loader").removeClass("hidden");
    var fields = JSON.stringify(["ID_Sertificate", "flight_type", "cert_link", "name", "last_name"]);
    var criteria = JSON.stringify({ "ID_SertState": [5]});
    jQuery.post("/certificate/select", {field_names : fields, criteria : criteria}, function (data) {
        $("#found_cert_loader").addClass("hidden");
        fillCertsListWithData("#found_certs",data)
    })

}

function findByIDCertificate(data){
    var id = $("#cert_id_for_watching").val();
    var found = false;
    var certificate_list = data.data;

    certificate_list.forEach(function (item) {
        if (item.ID_Sertificate == id){
            $("#found_certs").find(".cert_row").remove();
            $("#found_certs").append(getCertRow(item));
            found = true;
        }
    });
    if (!found){
        $("#found_certs").find(".cert_row").remove();
        $("#found_certs").append("
Сертификат не найдет
");
    }
}

function clearSearchFilter(event){
    var certificate_list = event.data;
    $("#cert_id_for_watching").val("");
    $("#found_certs").find(".cert_row").remove();

    certificate_list.forEach(function (item) {
        $("#found_certs").append(getCertRow(item));
    });
}

$(document).ajaxError(function(event, jqXHR, ajaxSettings, message){
    console.log(message);
});

$(document).ready(function(e){

    $("#calendar").fullCalendar({
        monthNames: ["Январь","Февраль","Март","Апрель","Май","Июнь","Июль","Август","Сентябрь","Октябрь","Ноябрь","Декабрь"],
        header: {
            left: 'title',
            right: 'today, prev, next'
        },
        dayClick: showModal
    });
});<|endoftext|>


<commit_before>import {Api} from './api';
import {EventAggregator} from 'aurelia-event-aggregator';
import * as messages from './messages';

export class Game {
	static inject() { return [Api, EventAggregator]; }

	constructor(api, ea) {
		this.api = api;
		this.ea = ea;
		this.villains = [];
		this.villainOptions = [];
		this.environments = [];
		this.environmentOptions = [];
		this.heroes = [];
		this.heroOptions = [];
		this.characterDelegates = {
			select: (name) => this._addCharacter(name)
		};
		this.ea.subscribe(messages.StateSync, msg => this._onStateSync(msg.state));
		this.api.retrieveData().then(data => this._setData(data));
	}

	activate(params, routeConfig) {
		this.gameId = params.id;
		this.api.joinGame(this.gameId);
	}

	copyGameIdToClipboard() {
		let gameIdElement = document.querySelector('#gameId');
		gameIdElement.select();
		document.execCommand('copy');
	}

	_onStateSync(state) {
		console.log('state:', state);
		this.villains.splice(0, this.villains.length);
		this.environments.splice(0, this.environments.length);
		this.heroes.splice(0, this.heroes.length);
		for (let object of state.objects) {
			if ('villain' === object.type)
				this.villains.push(object);
			else if ('environment' === object.type)
				this.environments.push(object);
			else if ('hero' === object.type)
				this.heroes.push(object);
		}
	}

	_setData(data) {
		this._replaceOptions(this.villainOptions, data, 'villain');
		this._replaceOptions(this.environmentOptions, data, 'environment');
		this._replaceOptions(this.heroOptions, data, 'hero');
	}

	_replaceOptions(options, data, type) {
		options.splice(0, options.length);
		for (let option of data.filter(o => type === o.type && 'character' === o.subtype && o.inList))
			options.push({id: option.name, name: option.displayName});
	}

	_addCharacter(name) {
		this.api.createCharacter(name);
	}
}
<commit_msg>Removing debug logging.<commit_after>import {Api} from './api';
import {EventAggregator} from 'aurelia-event-aggregator';
import * as messages from './messages';

export class Game {
	static inject() { return [Api, EventAggregator]; }

	constructor(api, ea) {
		this.api = api;
		this.ea = ea;
		this.villains = [];
		this.villainOptions = [];
		this.environments = [];
		this.environmentOptions = [];
		this.heroes = [];
		this.heroOptions = [];
		this.characterDelegates = {
			select: (name) => this._addCharacter(name)
		};
		this.ea.subscribe(messages.StateSync, msg => this._onStateSync(msg.state));
		this.api.retrieveData().then(data => this._setData(data));
	}

	activate(params, routeConfig) {
		this.gameId = params.id;
		this.api.joinGame(this.gameId);
	}

	copyGameIdToClipboard() {
		let gameIdElement = document.querySelector('#gameId');
		gameIdElement.select();
		document.execCommand('copy');
	}

	_onStateSync(state) {
		this.villains.splice(0, this.villains.length);
		this.environments.splice(0, this.environments.length);
		this.heroes.splice(0, this.heroes.length);
		for (let object of state.objects) {
			if ('villain' === object.type)
				this.villains.push(object);
			else if ('environment' === object.type)
				this.environments.push(object);
			else if ('hero' === object.type)
				this.heroes.push(object);
		}
	}

	_setData(data) {
		this._replaceOptions(this.villainOptions, data, 'villain');
		this._replaceOptions(this.environmentOptions, data, 'environment');
		this._replaceOptions(this.heroOptions, data, 'hero');
	}

	_replaceOptions(options, data, type) {
		options.splice(0, options.length);
		for (let option of data.filter(o => type === o.type && 'character' === o.subtype && o.inList))
			options.push({id: option.name, name: option.displayName});
	}

	_addCharacter(name) {
		this.api.createCharacter(name);
	}
}
<|endoftext|>


<commit_before>angular.module('appControllers').controller('SettingsCtrl', SettingsCtrl); // get the main module contollers set
SettingsCtrl.$inject = ['$rootScope', '$scope', '$state', '$location', '$window', '$http']; // Inject my dependencies

// create our controller function with all necessary logic
function SettingsCtrl($rootScope, $scope, $state, $location, $window, $http) {

	$scope.$parent.helppage = 'plates/settings-help.html';

	var toggles = ['UAT_Enabled', 'ES_Enabled', 'Ping_Enabled', 'GPS_Enabled', 'IMU_Sensor_Enabled',
		'BMP_Sensor_Enabled', 'DisplayTrafficSource', 'DEBUG', 'ReplayLog', 'AHRSLog'];
	var settings = {};
	for (i = 0; i < toggles.length; i++) {
		settings[toggles[i]] = undefined;
	}
	$scope.update_files = '';

	function loadSettings(data) {
		settings = angular.fromJson(data);
		// consider using angular.extend()
		$scope.rawSettings = angular.toJson(data, true);
		$scope.visible_serialout = false;
		if ((settings.SerialOutputs !== undefined) && (settings.SerialOutputs !== null) && (settings.SerialOutputs['/dev/serialout0'] !== undefined)) {
			$scope.Baud = settings.SerialOutputs['/dev/serialout0'].Baud;
			$scope.visible_serialout = true;
		}
		$scope.UAT_Enabled = settings.UAT_Enabled;
		$scope.ES_Enabled = settings.ES_Enabled;
		$scope.Ping_Enabled = settings.Ping_Enabled;
		$scope.GPS_Enabled = settings.GPS_Enabled;

		$scope.IMU_Sensor_Enabled = settings.IMU_Sensor_Enabled;
		$scope.BMP_Sensor_Enabled = settings.BMP_Sensor_Enabled;
		$scope.DisplayTrafficSource = settings.DisplayTrafficSource;
		$scope.DEBUG = settings.DEBUG;
		$scope.ReplayLog = settings.ReplayLog;
		$scope.AHRSLog = settings.AHRSLog;

		$scope.PPM = settings.PPM;
		$scope.WatchList = settings.WatchList;
		$scope.OwnshipModeS = settings.OwnshipModeS;
		$scope.DeveloperMode = settings.DeveloperMode;
        $scope.GLimits = settings.GLimits;
	}

	function getSettings() {
		// Simple GET request example (note: response is asynchronous)
		$http.get(URL_SETTINGS_GET).
		then(function (response) {
			loadSettings(response.data);
			// $scope.$apply();
		}, function (response) {
			$scope.rawSettings = "error getting settings";
			for (i = 0; i < toggles.length; i++) {
				settings[toggles[i]] = false;
			}
		});
	}

	function setSettings(msg) {
		// Simple POST request example (note: response is asynchronous)
		$http.post(URL_SETTINGS_SET, msg).
		then(function (response) {
			loadSettings(response.data);
			// $scope.$apply();
		}, function (response) {
			$scope.rawSettings = "error setting settings";
			for (i = 0; i < toggles.length; i++) {
				settings[toggles[i]] = false;
			}

		});
	}

	getSettings();

	$scope.$watchGroup(toggles, function (newValues, oldValues, scope) {
		var newsettings = {};
		var dirty = false;
		for (i = 0; i < newValues.length; i++) {
			if ((newValues[i] !== undefined) && (settings[toggles[i]] !== undefined)) {
				if (newValues[i] !== settings[toggles[i]]) {
					settings[toggles[i]] = newValues[i];
					newsettings[toggles[i]] = newValues[i];
					dirty = true;
				}
			}
		}
		if (dirty) {
			// console.log(angular.toJson(newsettings));
			setSettings(angular.toJson(newsettings));
		}
	});

	$scope.updateppm = function () {
		settings["PPM"] = 0;
		if (($scope.PPM !== undefined) && ($scope.PPM !== null) && ($scope.PPM !== settings["PPM"])) {
			settings["PPM"] = parseInt($scope.PPM);
			newsettings = {
				"PPM": settings["PPM"]
			};
			// console.log(angular.toJson(newsettings));
			setSettings(angular.toJson(newsettings));
		}
	};

	$scope.updateBaud = function () {
		settings["Baud"] = 0;
		if (($scope.Baud !== undefined) && ($scope.Baud !== null) && ($scope.Baud !== settings["Baud"])) {
			settings["Baud"] = parseInt($scope.Baud);
			newsettings = {
				"Baud": settings["Baud"]
			};
			// console.log(angular.toJson(newsettings));
			setSettings(angular.toJson(newsettings));
		}
	};

    $scope.updatewatchlist = function () {
        if ($scope.WatchList !== settings["WatchList"]) {
            settings["WatchList"] = "";
            if ($scope.WatchList !== undefined) {
                settings["WatchList"] = $scope.WatchList.toUpperCase();
            }
            newsettings = {
                "WatchList": settings["WatchList"]
            };
            // console.log(angular.toJson(newsettings));
            setSettings(angular.toJson(newsettings));
        }
    };

	$scope.updatemodes = function () {
		if ($scope.OwnshipModeS !== settings["OwnshipModeS"]) {
			settings["OwnshipModeS"] = $scope.OwnshipModeS.toUpperCase();
			newsettings = {
				"OwnshipModeS": $scope.OwnshipModeS.toUpperCase()
			};
			// console.log(angular.toJson(newsettings));
			setSettings(angular.toJson(newsettings));
		}
	};

	$scope.updatestaticips = function () {
		if ($scope.StaticIps !== settings.StaticIps) {
			newsettings = {
				"StaticIps": $scope.StaticIps === undefined ? "" : $scope.StaticIps.join(' ')
			};
			// console.log(angular.toJson(newsettings));
			setSettings(angular.toJson(newsettings));
		}
	};

	$scope.updateGLimits = function () {
        if ($scope.GLimits !== settings["GLimits"]) {
            settings["GLimits"] = $scope.GLimits;
            newsettings = {
                "GLimits": settings["GLimits"]
            };
            // console.log(angular.toJson(newsettings));
            setSettings(angular.toJson(newsettings));
        }
    };

	$scope.postShutdown = function () {
		$window.location.href = "/";
		$location.path('/home');
		$http.post(URL_SHUTDOWN).
		then(function (response) {
			// do nothing
			// $scope.$apply();
		}, function (response) {
			// do nothing
		});
	};

	$scope.postReboot = function () {
		$window.location.href = "/";
		$location.path('/home');
		$http.post(URL_REBOOT).
		then(function (response) {
			// do nothing
			// $scope.$apply();
		}, function (response) {
			// do nothing
		});
	};

	$scope.setUploadFile = function (files) {
		$scope.update_files = files;
		$scope.$apply();
	};
	$scope.resetUploadFile = function () {
		$scope.update_files = '';
		$scope.$apply();
	};
	$scope.uploadFile = function () {
		var fd = new FormData();
		//Take the first selected file
		var file = $scope.update_files[0];
		// check for empty string
		if (file === undefined || file === null) {
			alert ("update file not selected");
			return;
		}
		var filename = file.name;
		// check for expected file naming convention
		var re = /^update.*\.sh$/;
		if (!re.exec(filename)) {
			alert ("file does not appear to be an update");
			return;
		}

		fd.append("update_file", file);

		$http.post(URL_UPDATE_UPLOAD, fd, {
			withCredentials: true,
			headers: {
				'Content-Type': undefined
			},
			transformRequest: angular.identity
		}).success(function (data) {
			alert("success. wait 60 seconds and refresh home page to verify new version.");
			window.location.replace("/");
		}).error(function (data) {
			alert("error");
		});

	};

	$scope.setOrientation = function(action) {
		// console.log("sending " + action + " message.");
		$http.post(URL_AHRS_ORIENT, action).
		then(function (response) {
			// console.log("sent " + action + " message.");
		}, function(response) {
			// failure: cancel the calibration
			// console.log(response.data);
			$scope.Orientation_Failure_Message = response.data;
			$scope.Ui.turnOff('modalCalibrateDone');
			$scope.Ui.turnOn("modalCalibrateFailed");
		});
	};

	$scope.calibrateGyros = function() {
	    console.log("sending calibrate message.");
	    $http.post(URL_AHRS_CAL).
            then(function(response) {
                console.log("Sent calibrate message.");
        }, function(response) {
                console.log(response.data);
                $scope.Calibration_Failure_Message = response.data;
                $scope.Ui.turnOff("modalCalibrateGyros");
                $scope.Ui.turnOn("modalCalibrateGyrosFailed");
        });
    };
}
<commit_msg>Increase suggested wait time on updates.<commit_after>angular.module('appControllers').controller('SettingsCtrl', SettingsCtrl); // get the main module contollers set
SettingsCtrl.$inject = ['$rootScope', '$scope', '$state', '$location', '$window', '$http']; // Inject my dependencies

// create our controller function with all necessary logic
function SettingsCtrl($rootScope, $scope, $state, $location, $window, $http) {

	$scope.$parent.helppage = 'plates/settings-help.html';

	var toggles = ['UAT_Enabled', 'ES_Enabled', 'Ping_Enabled', 'GPS_Enabled', 'IMU_Sensor_Enabled',
		'BMP_Sensor_Enabled', 'DisplayTrafficSource', 'DEBUG', 'ReplayLog', 'AHRSLog'];
	var settings = {};
	for (i = 0; i < toggles.length; i++) {
		settings[toggles[i]] = undefined;
	}
	$scope.update_files = '';

	function loadSettings(data) {
		settings = angular.fromJson(data);
		// consider using angular.extend()
		$scope.rawSettings = angular.toJson(data, true);
		$scope.visible_serialout = false;
		if ((settings.SerialOutputs !== undefined) && (settings.SerialOutputs !== null) && (settings.SerialOutputs['/dev/serialout0'] !== undefined)) {
			$scope.Baud = settings.SerialOutputs['/dev/serialout0'].Baud;
			$scope.visible_serialout = true;
		}
		$scope.UAT_Enabled = settings.UAT_Enabled;
		$scope.ES_Enabled = settings.ES_Enabled;
		$scope.Ping_Enabled = settings.Ping_Enabled;
		$scope.GPS_Enabled = settings.GPS_Enabled;

		$scope.IMU_Sensor_Enabled = settings.IMU_Sensor_Enabled;
		$scope.BMP_Sensor_Enabled = settings.BMP_Sensor_Enabled;
		$scope.DisplayTrafficSource = settings.DisplayTrafficSource;
		$scope.DEBUG = settings.DEBUG;
		$scope.ReplayLog = settings.ReplayLog;
		$scope.AHRSLog = settings.AHRSLog;

		$scope.PPM = settings.PPM;
		$scope.WatchList = settings.WatchList;
		$scope.OwnshipModeS = settings.OwnshipModeS;
		$scope.DeveloperMode = settings.DeveloperMode;
        $scope.GLimits = settings.GLimits;
	}

	function getSettings() {
		// Simple GET request example (note: response is asynchronous)
		$http.get(URL_SETTINGS_GET).
		then(function (response) {
			loadSettings(response.data);
			// $scope.$apply();
		}, function (response) {
			$scope.rawSettings = "error getting settings";
			for (i = 0; i < toggles.length; i++) {
				settings[toggles[i]] = false;
			}
		});
	}

	function setSettings(msg) {
		// Simple POST request example (note: response is asynchronous)
		$http.post(URL_SETTINGS_SET, msg).
		then(function (response) {
			loadSettings(response.data);
			// $scope.$apply();
		}, function (response) {
			$scope.rawSettings = "error setting settings";
			for (i = 0; i < toggles.length; i++) {
				settings[toggles[i]] = false;
			}

		});
	}

	getSettings();

	$scope.$watchGroup(toggles, function (newValues, oldValues, scope) {
		var newsettings = {};
		var dirty = false;
		for (i = 0; i < newValues.length; i++) {
			if ((newValues[i] !== undefined) && (settings[toggles[i]] !== undefined)) {
				if (newValues[i] !== settings[toggles[i]]) {
					settings[toggles[i]] = newValues[i];
					newsettings[toggles[i]] = newValues[i];
					dirty = true;
				}
			}
		}
		if (dirty) {
			// console.log(angular.toJson(newsettings));
			setSettings(angular.toJson(newsettings));
		}
	});

	$scope.updateppm = function () {
		settings["PPM"] = 0;
		if (($scope.PPM !== undefined) && ($scope.PPM !== null) && ($scope.PPM !== settings["PPM"])) {
			settings["PPM"] = parseInt($scope.PPM);
			newsettings = {
				"PPM": settings["PPM"]
			};
			// console.log(angular.toJson(newsettings));
			setSettings(angular.toJson(newsettings));
		}
	};

	$scope.updateBaud = function () {
		settings["Baud"] = 0;
		if (($scope.Baud !== undefined) && ($scope.Baud !== null) && ($scope.Baud !== settings["Baud"])) {
			settings["Baud"] = parseInt($scope.Baud);
			newsettings = {
				"Baud": settings["Baud"]
			};
			// console.log(angular.toJson(newsettings));
			setSettings(angular.toJson(newsettings));
		}
	};

    $scope.updatewatchlist = function () {
        if ($scope.WatchList !== settings["WatchList"]) {
            settings["WatchList"] = "";
            if ($scope.WatchList !== undefined) {
                settings["WatchList"] = $scope.WatchList.toUpperCase();
            }
            newsettings = {
                "WatchList": settings["WatchList"]
            };
            // console.log(angular.toJson(newsettings));
            setSettings(angular.toJson(newsettings));
        }
    };

	$scope.updatemodes = function () {
		if ($scope.OwnshipModeS !== settings["OwnshipModeS"]) {
			settings["OwnshipModeS"] = $scope.OwnshipModeS.toUpperCase();
			newsettings = {
				"OwnshipModeS": $scope.OwnshipModeS.toUpperCase()
			};
			// console.log(angular.toJson(newsettings));
			setSettings(angular.toJson(newsettings));
		}
	};

	$scope.updatestaticips = function () {
		if ($scope.StaticIps !== settings.StaticIps) {
			newsettings = {
				"StaticIps": $scope.StaticIps === undefined ? "" : $scope.StaticIps.join(' ')
			};
			// console.log(angular.toJson(newsettings));
			setSettings(angular.toJson(newsettings));
		}
	};

	$scope.updateGLimits = function () {
        if ($scope.GLimits !== settings["GLimits"]) {
            settings["GLimits"] = $scope.GLimits;
            newsettings = {
                "GLimits": settings["GLimits"]
            };
            // console.log(angular.toJson(newsettings));
            setSettings(angular.toJson(newsettings));
        }
    };

	$scope.postShutdown = function () {
		$window.location.href = "/";
		$location.path('/home');
		$http.post(URL_SHUTDOWN).
		then(function (response) {
			// do nothing
			// $scope.$apply();
		}, function (response) {
			// do nothing
		});
	};

	$scope.postReboot = function () {
		$window.location.href = "/";
		$location.path('/home');
		$http.post(URL_REBOOT).
		then(function (response) {
			// do nothing
			// $scope.$apply();
		}, function (response) {
			// do nothing
		});
	};

	$scope.setUploadFile = function (files) {
		$scope.update_files = files;
		$scope.$apply();
	};
	$scope.resetUploadFile = function () {
		$scope.update_files = '';
		$scope.$apply();
	};
	$scope.uploadFile = function () {
		var fd = new FormData();
		//Take the first selected file
		var file = $scope.update_files[0];
		// check for empty string
		if (file === undefined || file === null) {
			alert ("update file not selected");
			return;
		}
		var filename = file.name;
		// check for expected file naming convention
		var re = /^update.*\.sh$/;
		if (!re.exec(filename)) {
			alert ("file does not appear to be an update");
			return;
		}

		fd.append("update_file", file);

		$http.post(URL_UPDATE_UPLOAD, fd, {
			withCredentials: true,
			headers: {
				'Content-Type': undefined
			},
			transformRequest: angular.identity
		}).success(function (data) {
			alert("success. wait 5 minutes and refresh home page to verify new version.");
			window.location.replace("/");
		}).error(function (data) {
			alert("error");
		});

	};

	$scope.setOrientation = function(action) {
		// console.log("sending " + action + " message.");
		$http.post(URL_AHRS_ORIENT, action).
		then(function (response) {
			// console.log("sent " + action + " message.");
		}, function(response) {
			// failure: cancel the calibration
			// console.log(response.data);
			$scope.Orientation_Failure_Message = response.data;
			$scope.Ui.turnOff('modalCalibrateDone');
			$scope.Ui.turnOn("modalCalibrateFailed");
		});
	};

	$scope.calibrateGyros = function() {
	    console.log("sending calibrate message.");
	    $http.post(URL_AHRS_CAL).
            then(function(response) {
                console.log("Sent calibrate message.");
        }, function(response) {
                console.log(response.data);
                $scope.Calibration_Failure_Message = response.data;
                $scope.Ui.turnOff("modalCalibrateGyros");
                $scope.Ui.turnOn("modalCalibrateGyrosFailed");
        });
    };
}
<|endoftext|>


<commit_before>/* This file contains ASCII menus rendered as a monospace text over the game
 * board. */

/* Several menus are available as templates:
 *   1. Vanilla menu with no menu-specific functionality given (MenuBase)
 *   2. Menu for showing information only, has quit-option only (MenuInfoOnly)
 *   3. Menu with quit option provided (MenuWithQuit)
 *     - User must add their own selection choices
 *   4. Menu requiring a valid selection (MenuSelectRequired)
 *     - User must add their own selection choices
 *   5. Menu for selecting a cell (MenuSelectCell).
 */

/* Menus should follow these conventions:
 *   Each menu must have a select() function:
 *     select() function:
 *       return Menu.EXIT_MENU when the menu should be closed
 *       return a Menu object for nested menu
 *       return a function for action to take.
 *       Other values are invalid, and should not be returned
 *
 *   Each Menu must have getMenu(), unless showMenu() returns false.
 */

const RG = require('./rg');
const Keys = require('./keymap');

const {KeyMap} = Keys;

const Menu = {};
Menu.EXIT_MENU = null;

//------------------------------
/* Base class for all menus. */
//------------------------------
const MenuBase = function(args = []) {
    this.table = {};
    this.msg = '';

    this.parent = null; // Parent menu for this object

    args.forEach((item, i) => {
        const index = Keys.menuIndices[i];
        if (item.key) {
            const index = Keys.codeToIndex(item.key);
            this.table[index] = item.menu;
        }
        else if (item.length === 2) {
            this.table[index] = item;
        }
        else {
            let msg = 'Each item must have 2 values: menu msg and ret val';
            msg += '\nItem can also be {key: , menu: } for nested menus';
            RG.err('MenuBase', 'constructor', msg);
        }
    });

    this.setMsg = msg => {
        this.msg = msg;
    };

    this.showMsg = () => {
        if (this.msg.length > 0) {
            RG.gameMsg(this.msg);
        }
    };

    this.pre = [];
    this.post = [];

    this.showMenu = () => true;

    this.setParent = parent => {
        this.parent = parent;
    };

    this.getParent = () => this.parent;

    this.getMenu = () => {
        const obj = {};
        Object.keys(this.table).forEach(index => {
            const char = Keys.menuIndices[index];
            obj[char] = this.table[index][0];
        });
        obj.pre = this.pre;
        obj.post = this.post;
        return obj;
    };

    this.addPost = item => {
        if (Array.isArray(item)) {
            this.post = this.post.concat(item);
        }
        else {
            this.post.push(item);
        }
    };

    this.addPre = item => {
        if (Array.isArray(item)) {
            this.pre = this.pre.concat(item);
        }
        else {
            this.pre.push(item);
        }
    };

};
Menu.Base = MenuBase;

/* InfoOnly menu does not contain actual selection, but is intended to show
 * player crucial info they should not miss. Menu can be exited only by pressing
 * a specific key. */
const MenuInfoOnly = function() {
    MenuBase.call(this);

    this.getMenu = () => {
        const obj = {
            0: 'Back to game.'
        };
        obj.pre = this.pre;
        obj.post = this.post;
        return obj;
    };

    this.select = code => {
        const selection = Keys.codeToIndex(code);
        if (selection === 0) {
            return Menu.EXIT_MENU;
        }
        return this;
    };
};
RG.extend2(MenuInfoOnly, MenuBase);
Menu.InfoOnly = MenuInfoOnly;

/* This menu can be used when quit option is required. You can add a callback by
 * setting onQuit to a desired function. */
const MenuWithQuit = function(args) {
    MenuBase.call(this, args);
    const quitIndex = Keys.codeToIndex(Keys.KEY.QUIT_MENU);
    this.table[quitIndex] = ['Quit menu', Menu.EXIT_MENU];

    this.select = code => {
        const selection = Keys.codeToIndex(code);
        if (this.table.hasOwnProperty(selection)) {
            const value = this.table[selection][1];
            if (value === Menu.EXIT_MENU && this.onQuit) {
                this.onQuit();
            }
            return value;
        }
        return this;
    };

};
RG.extend2(MenuWithQuit, MenuBase);
Menu.WithQuit = MenuWithQuit;

/* This menu can be used for functionality requiring always a selection. */
const MenuSelectRequired = function(args) {
    MenuBase.call(this, args);

    this.select = code => {
        const selection = Keys.codeToIndex(code);
        if (this.table.hasOwnProperty(selection)) {
            return this.table[selection][1];
        }
        return this;
    };
};
RG.extend2(MenuSelectRequired, MenuBase);
Menu.SelectRequired = MenuSelectRequired;

/* This menu can be used when a cell needs to be selected. */
const MenuSelectCell = function(args) {
    MenuBase.call(this, args);
    this._enableSelectAll = false;
    if (args.enableSelectAll) {
        this.enableSelectAll = args.enableSelectAll;
    }

    this.setCallback = cb => {
        this.callback = cb;
    };

    this.showMenu = () => false;

    this.enableSelectAll = () => {
        this._enableSelectAll = true;
    };

    this.select = code => {
        if (KeyMap.inMoveCodeMap(code)) {
            this.callback(code);
            return this;
        }
        else if (KeyMap.isSelect(code)) {
            const keyIndex = Keys.codeToIndex(code);
            return this.table[keyIndex];
        }
        else if (this._enableSelectAll && KeyMap.isSelectAll(code)) {
            this.callback(code);
            return this;
        }
        return null;
    };

};
RG.extend2(MenuSelectCell, MenuBase);
Menu.SelectCell = MenuSelectCell;

module.exports = Menu;
<commit_msg>Added func and funcToCall support for menu items.<commit_after>/* This file contains ASCII menus rendered as a monospace text over the game
 * board. */

/* Several menus are available as templates:
 *   1. Vanilla menu with no menu-specific functionality given (MenuBase)
 *   2. Menu for showing information only, has quit-option only (MenuInfoOnly)
 *   3. Menu with quit option provided (MenuWithQuit)
 *     - User must add their own selection choices
 *   4. Menu requiring a valid selection (MenuSelectRequired)
 *     - User must add their own selection choices
 *   5. Menu for selecting a cell (MenuSelectCell).
 */

/* Menus should follow these conventions:
 *   Each menu must have a select() function:
 *     select() function:
 *       return Menu.EXIT_MENU when the menu should be closed
 *       return a Menu object for nested menu
 *       return a function for action to take.
 *       Other values are invalid, and should not be returned
 *
 *   Each Menu must have getMenu(), unless showMenu() returns false.
 *
 */

const RG = require('./rg');
const Keys = require('./keymap');

const {KeyMap} = Keys;

const Menu = {};
Menu.EXIT_MENU = null;

//------------------------------
/* Base class for all menus. */
//------------------------------
const MenuBase = function(args = []) {
    this.table = {};
    this.msg = '';

    this.parent = null; // Parent menu for this object

    args.forEach((item, i) => {
        const index = Keys.menuIndices[i];
        if (item.key) {
            const index = Keys.codeToIndex(item.key);
            if (item.menu) {
                this.table[index] = item.menu;
            }
            else if (item.func) {
                this.table[index] = item.func;
            }
            else if (item.funcToCall) {
                this.table[index] = {funcToCall: item.funcToCall};
            }
        }
        else if (item.length === 2) {
            this.table[index] = item;
        }
        else {
            let msg = 'Each item must have 2 values: menu msg and ret val';
            msg += '\nItem can also be {key: , menu: } for nested menus';
            RG.err('MenuBase', 'constructor', msg);
        }
    });

    this.setMsg = msg => {
        this.msg = msg;
    };

    this.showMsg = () => {
        if (this.msg.length > 0) {
            RG.gameMsg(this.msg);
        }
    };

    this.pre = [];
    this.post = [];

    this.showMenu = () => true;

    this.setParent = parent => {
        this.parent = parent;
    };

    this.getParent = () => this.parent;

    this.getMenu = () => {
        const obj = {};
        Object.keys(this.table).forEach(index => {
            const char = Keys.menuIndices[index];
            obj[char] = this.table[index][0];
        });
        obj.pre = this.pre;
        obj.post = this.post;
        return obj;
    };

    this.addPost = item => {
        if (Array.isArray(item)) {
            this.post = this.post.concat(item);
        }
        else {
            this.post.push(item);
        }
    };

    this.addPre = item => {
        if (Array.isArray(item)) {
            this.pre = this.pre.concat(item);
        }
        else {
            this.pre.push(item);
        }
    };

};
Menu.Base = MenuBase;

/* InfoOnly menu does not contain actual selection, but is intended to show
 * player crucial info they should not miss. Menu can be exited only by pressing
 * a specific key. */
const MenuInfoOnly = function() {
    MenuBase.call(this);

    this.getMenu = () => {
        const obj = {
            0: 'Back to game.'
        };
        obj.pre = this.pre;
        obj.post = this.post;
        return obj;
    };

    this.select = code => {
        const selection = Keys.codeToIndex(code);
        if (selection === 0) {
            return Menu.EXIT_MENU;
        }
        return this;
    };
};
RG.extend2(MenuInfoOnly, MenuBase);
Menu.InfoOnly = MenuInfoOnly;

/* This menu can be used when quit option is required. You can add a callback by
 * setting onQuit to a desired function. */
const MenuWithQuit = function(args) {
    MenuBase.call(this, args);
    const quitIndex = Keys.codeToIndex(Keys.KEY.QUIT_MENU);
    this.table[quitIndex] = ['Quit menu', Menu.EXIT_MENU];

    this.select = code => {
        const selection = Keys.codeToIndex(code);
        if (this.table.hasOwnProperty(selection)) {
            const value = this.table[selection][1];
            if (value === Menu.EXIT_MENU && this.onQuit) {
                this.onQuit();
            }
            return value;
        }
        return this;
    };

};
RG.extend2(MenuWithQuit, MenuBase);
Menu.WithQuit = MenuWithQuit;

/* This menu can be used for functionality requiring always a selection. */
const MenuSelectRequired = function(args) {
    MenuBase.call(this, args);

    this.select = code => {
        const selection = Keys.codeToIndex(code);
        if (this.table.hasOwnProperty(selection)) {
            return this.table[selection][1];
        }
        return this;
    };
};
RG.extend2(MenuSelectRequired, MenuBase);
Menu.SelectRequired = MenuSelectRequired;

/* This menu can be used when a cell needs to be selected. */
const MenuSelectCell = function(args) {
    MenuBase.call(this, args);
    this._enableSelectAll = false;
    if (args.enableSelectAll) {
        this.enableSelectAll = args.enableSelectAll;
    }

    this.setCallback = cb => {
        this.callback = cb;
    };

    this.showMenu = () => false;

    this.enableSelectAll = () => {
        this._enableSelectAll = true;
    };

    this.select = code => {
        if (KeyMap.inMoveCodeMap(code)) {
            this.callback(code);
            return this;
        }
        else if (KeyMap.isSelect(code)) {
            const keyIndex = Keys.codeToIndex(code);
            return this.table[keyIndex];
        }
        else if (this._enableSelectAll && KeyMap.isSelectAll(code)) {
            this.callback(code);
            return this;
        }
        return null;
    };

};
RG.extend2(MenuSelectCell, MenuBase);
Menu.SelectCell = MenuSelectCell;

module.exports = Menu;
<|endoftext|>


<commit_before>//Directive used to set metisMenu and minimalize button
angular.module('inspinia')
    .directive('sideNavigation', function ($timeout) {
        return {
            restrict: 'A',
            link: function (scope, element) {
                // Call metsi to build when user signup
                scope.$watch('authentication.user', function() {
                    $timeout(function() {
                        element.metisMenu();
                    });
                });

            }
        };
    })
    .directive('minimalizaSidebar', function ($timeout) {
        return {
            restrict: 'A',
            template: '',
            controller: function ($scope, $element) {
                $scope.minimalize = function () {
                    angular.element('body').toggleClass('mini-navbar');
                    if (!angular.element('body').hasClass('mini-navbar') || angular.element('body').hasClass('body-small')) {
                        // Hide menu in order to smoothly turn on when maximize menu
                        angular.element('#side-menu').hide();
                        // For smoothly turn on menu
                        $timeout(function () {
                            angular.element('#side-menu').fadeIn(500);
                        }, 100);
                    } else {
                        // Remove all inline style from jquery fadeIn function to reset menu state
                        angular.element('#side-menu').removeAttr('style');
                    }
                };
            }
        };
    })
    .directive('ideaFeed', function() {
        return {
            restrict: 'E',
            scope: {
                data: '=',
                group: '@'
            },
            controller: function($scope, firebaseHelper, $sce, $rootScope) {
                var date = new Date($scope.data.createdDate)
                var year = date.getFullYear();
                var month = date.getMonth() + 1;
                var day = date.getDate();
                var hour = date.getHours();
                var minute = date.getMinutes();
                var sec = date.getSeconds();
                if (month < 10) {month = "0" + month};
                if (day < 10) {day = "0" + day};
                if (hour < 10) {hour = "0" + hour};
                if (minute < 10) {minute = "0" + minute};
                if (sec < 10) {sec = "0" + sec};
                $scope.createdDate = year + "/" + month + "/" + day + " " + hour + ":" + minute + ":" + sec;

                $scope.$watch("data.title", function() {
                    if ($scope.data.title) {
                        $scope.title = $sce.trustAsHtml($scope.data.title.replace(/(?:\r\n|\r|\n)/g, '
'));
                    }
                })
                // $scope.title = $sce.trustAsHtml($scope.data.title.replace(/(?:\r\n|\r|\n)/g, '
'));

                $scope.user_profile = firebaseHelper.syncObject("profiles_pub/" + $scope.data.uid);
                $scope.created_user_profile = firebaseHelper.syncObject("profiles_pub/" + $scope.data.createdBy);
                $scope.gravatar = $rootScope.gravatar;

                // $scope.ideas_stat = firebaseHelper.syncObject(["ideas", $scope.group, $scope.data.$id, "stat"]);
                $scope.ideas_vote = firebaseHelper.syncObject(["ideas_votes", $scope.group, $scope.data.$id, firebaseHelper.getUID()]);

                var upvote = function(from_down_vote) {
                    firebaseHelper.transaction(["ideas", $scope.group, $scope.data.$id], function(data) {
                        if (!data) {
                            //data = {up_votes: 0, down_votes: 0, comments: 0, score: 0};
                            return;
                        }
                        data.up_votes = (data.up_votes || 0) + 1;
                        if (from_down_vote) {
                            data.down_votes = (data.down_votes || 0) - 1;
                        }
                        data.score = (data.up_votes || 0) - (data.down_votes || 0);
                        return data;
                    })
                }
                var downvote = function(from_up_vote) {
                    firebaseHelper.transaction(["ideas", $scope.group, $scope.data.$id], function(data) {
                        if (!data) {
                            // data = {up_votes: 0, down_votes: 0, comments: 0, score: 0};
                            return;
                        }
                        data.down_votes = (data.down_votes || 0) + 1;
                        if (from_up_vote) {
                            data.up_votes = (data.up_votes || 0) - 1;
                        }
                        data.score = (data.up_votes || 0) - (data.down_votes || 0);
                        return data;
                    })
                }

                $scope.onUpVote = function(from_down_vote) {
                    if (!firebaseHelper.getUID()) {
                        $rootScope.notifyError("Something wrong @@");
                        return;
                    }
                    firebaseHelper.transaction(["ideas_votes", $scope.group, $scope.data.$id, firebaseHelper.getUID()], function(data) {
                        if (!data) { //not vote yet
                            data = {value: 0};
                        }
                        if (data.value == 0) {
                            upvote(false);
                        } else if (data.value == -1){
                            upvote(true);
                        }
                        data.value = 1;
                        return data;
                    });
                }
                $scope.onDownVote = function() {
                    if (!firebaseHelper.getUID()) {
                        $rootScope.notifyError("Something wrong @@");
                        return;
                    }
                    firebaseHelper.transaction(["ideas_votes", $scope.group, $scope.data.$id, firebaseHelper.getUID()], function(data) {
                        if (!data) {
                            data = {value: 0};
                        }
                        if (data.value == 0) {
                            downvote(false);
                        } else if (data.value == 1){
                            downvote(true);
                        }
                        data.value = -1;
                        return data;
                    });
                }
                $scope.onComments = function() {
                    $rootScope.notifyError("This feature is not implemented yet")
                }
            },
            template: '\
                     \
                         \
                     \

 \
                         0" class="pull-right label label-info">{{data.score || 0}} pts \
                        <small ng-show="data.score < 0" class="pull-right label label-danger">{{data.score || 0}} pts \
                        {{data.score || 0}} pts \
                        {{user_profile.display_name}}
 \
                        {{createdDate}}
\
                        Created by: {{created_user_profile.display_name}} \

 \

 \
                             {{data.up_votes || 0}} \
                             {{data.down_votes || 0}} \
                             {{data.comments || 0}} \

 \

 \
            '
        }
    })

    .directive('newIdeaFeed', function($timeout) {
        return {
            restrict: 'E',
            scope: {
                onFinished: '&',
                group: '@'
            },
            controller: function($scope, firebaseHelper, $sce, $rootScope) {
                $scope.data = {
                    title: ""
                }
                $scope.gravatar = $rootScope.gravatar;

                $scope.onSave = function() {
                    if (!firebaseHelper.getUID()) {
                        $rootScope.notifyError("Something wrong @@");
                        $scope.onCancel();
                        return;
                    }
                    var ref = firebaseHelper.getFireBaseInstance(["ideas", $scope.group]);
                    var uid = firebaseHelper.getUID();
                    if ($scope.allowAssign && $scope.assigned_user) {
                        uid = $scope.assigned_user;
                    }
                    ref.push().setWithPriority({
                        createdDate: Date.now(),
                        title: $scope.data.title,
                        uid: uid,
                        createdBy: firebaseHelper.getUID(),
                    }, -Date.now(), function(ref) {
                        $scope.onCancel();
                    })
                };

                $scope.allowAssign = false;
                $scope.assigned_user = null;
                $scope.users = [];

                var doSync = function() {
                    console.log("xxxxxx");
                    if (firebaseHelper.getUID()) {
                        $scope.data.uid = firebaseHelper.getUID();
                        $scope.user_profile = firebaseHelper.syncObject(["profiles_pub", $scope.data.uid]);
                        $scope.allowAssign = firebaseHelper.getRole() === "admin" || firebaseHelper.getRole() === "mod";
                        if ($scope.allowAssign) {
                            $scope.users = [];
                            firebaseHelper.getFireBaseInstance("profiles_pub").once("value", function(snapshot) {
                                snapshot.forEach(function(childSnapshot) {
                                    $scope.users.push({
                                        display_name: childSnapshot.val().display_name,
                                        uid: childSnapshot.key()
                                    });
                                });
                                $scope.assigned_user = "";
                                $scope.$apply();
                            })
                        }
                        $timeout(function() {
                            $scope.$apply();
                        }, 100)
                    }
                }

                $scope.$on("user:login", function(data) {
                    console.log("yyyyyyy");
                    doSync();
                });
                doSync();

                $scope.onCancel = function() {
                    $scope.data.title = "";
                    if ($scope.onFinished) {
                        $scope.onFinished();
                    }
                }
            },
            template: '\
                     \
                         \
                     \

 \
                        {{createdDate}} \

{{user_profile.display_name}}
 \
                        <textarea maxlength="140" placeholder="Enter your idea here" class="form-control" rows="6" ng-model="data.title"> </textarea> \

 \

Idea of
 \
                        <select class="form-control m-b" name="account" ng-model="assigned_user"> \
                            <option value="">@me</option> \
                            <option ng-repeat="u in users" value="{{u.uid}}">{{u.display_name}}</option> \
                        </select> \

 \
                            {{140 - data.title.length}} chars left  \
                             Save \
                             Cancel \

 \

 \
            '
        }
    })

    ;
<commit_msg>remove log<commit_after>//Directive used to set metisMenu and minimalize button
angular.module('inspinia')
    .directive('sideNavigation', function ($timeout) {
        return {
            restrict: 'A',
            link: function (scope, element) {
                // Call metsi to build when user signup
                scope.$watch('authentication.user', function() {
                    $timeout(function() {
                        element.metisMenu();
                    });
                });

            }
        };
    })
    .directive('minimalizaSidebar', function ($timeout) {
        return {
            restrict: 'A',
            template: '',
            controller: function ($scope, $element) {
                $scope.minimalize = function () {
                    angular.element('body').toggleClass('mini-navbar');
                    if (!angular.element('body').hasClass('mini-navbar') || angular.element('body').hasClass('body-small')) {
                        // Hide menu in order to smoothly turn on when maximize menu
                        angular.element('#side-menu').hide();
                        // For smoothly turn on menu
                        $timeout(function () {
                            angular.element('#side-menu').fadeIn(500);
                        }, 100);
                    } else {
                        // Remove all inline style from jquery fadeIn function to reset menu state
                        angular.element('#side-menu').removeAttr('style');
                    }
                };
            }
        };
    })
    .directive('ideaFeed', function() {
        return {
            restrict: 'E',
            scope: {
                data: '=',
                group: '@'
            },
            controller: function($scope, firebaseHelper, $sce, $rootScope) {
                var date = new Date($scope.data.createdDate)
                var year = date.getFullYear();
                var month = date.getMonth() + 1;
                var day = date.getDate();
                var hour = date.getHours();
                var minute = date.getMinutes();
                var sec = date.getSeconds();
                if (month < 10) {month = "0" + month};
                if (day < 10) {day = "0" + day};
                if (hour < 10) {hour = "0" + hour};
                if (minute < 10) {minute = "0" + minute};
                if (sec < 10) {sec = "0" + sec};
                $scope.createdDate = year + "/" + month + "/" + day + " " + hour + ":" + minute + ":" + sec;

                $scope.$watch("data.title", function() {
                    if ($scope.data.title) {
                        $scope.title = $sce.trustAsHtml($scope.data.title.replace(/(?:\r\n|\r|\n)/g, '
'));
                    }
                })
                // $scope.title = $sce.trustAsHtml($scope.data.title.replace(/(?:\r\n|\r|\n)/g, '
'));

                $scope.user_profile = firebaseHelper.syncObject("profiles_pub/" + $scope.data.uid);
                $scope.created_user_profile = firebaseHelper.syncObject("profiles_pub/" + $scope.data.createdBy);
                $scope.gravatar = $rootScope.gravatar;

                // $scope.ideas_stat = firebaseHelper.syncObject(["ideas", $scope.group, $scope.data.$id, "stat"]);
                $scope.ideas_vote = firebaseHelper.syncObject(["ideas_votes", $scope.group, $scope.data.$id, firebaseHelper.getUID()]);

                var upvote = function(from_down_vote) {
                    firebaseHelper.transaction(["ideas", $scope.group, $scope.data.$id], function(data) {
                        if (!data) {
                            //data = {up_votes: 0, down_votes: 0, comments: 0, score: 0};
                            return;
                        }
                        data.up_votes = (data.up_votes || 0) + 1;
                        if (from_down_vote) {
                            data.down_votes = (data.down_votes || 0) - 1;
                        }
                        data.score = (data.up_votes || 0) - (data.down_votes || 0);
                        return data;
                    })
                }
                var downvote = function(from_up_vote) {
                    firebaseHelper.transaction(["ideas", $scope.group, $scope.data.$id], function(data) {
                        if (!data) {
                            // data = {up_votes: 0, down_votes: 0, comments: 0, score: 0};
                            return;
                        }
                        data.down_votes = (data.down_votes || 0) + 1;
                        if (from_up_vote) {
                            data.up_votes = (data.up_votes || 0) - 1;
                        }
                        data.score = (data.up_votes || 0) - (data.down_votes || 0);
                        return data;
                    })
                }

                $scope.onUpVote = function(from_down_vote) {
                    if (!firebaseHelper.getUID()) {
                        $rootScope.notifyError("Something wrong @@");
                        return;
                    }
                    firebaseHelper.transaction(["ideas_votes", $scope.group, $scope.data.$id, firebaseHelper.getUID()], function(data) {
                        if (!data) { //not vote yet
                            data = {value: 0};
                        }
                        if (data.value == 0) {
                            upvote(false);
                        } else if (data.value == -1){
                            upvote(true);
                        }
                        data.value = 1;
                        return data;
                    });
                }
                $scope.onDownVote = function() {
                    if (!firebaseHelper.getUID()) {
                        $rootScope.notifyError("Something wrong @@");
                        return;
                    }
                    firebaseHelper.transaction(["ideas_votes", $scope.group, $scope.data.$id, firebaseHelper.getUID()], function(data) {
                        if (!data) {
                            data = {value: 0};
                        }
                        if (data.value == 0) {
                            downvote(false);
                        } else if (data.value == 1){
                            downvote(true);
                        }
                        data.value = -1;
                        return data;
                    });
                }
                $scope.onComments = function() {
                    $rootScope.notifyError("This feature is not implemented yet")
                }
            },
            template: '\
                     \
                         \
                     \

 \
                         0" class="pull-right label label-info">{{data.score || 0}} pts \
                        <small ng-show="data.score < 0" class="pull-right label label-danger">{{data.score || 0}} pts \
                        {{data.score || 0}} pts \
                        {{user_profile.display_name}}
 \
                        {{createdDate}}
\
                        Created by: {{created_user_profile.display_name}} \

 \

 \
                             {{data.up_votes || 0}} \
                             {{data.down_votes || 0}} \
                             {{data.comments || 0}} \

 \

 \
            '
        }
    })

    .directive('newIdeaFeed', function($timeout) {
        return {
            restrict: 'E',
            scope: {
                onFinished: '&',
                group: '@'
            },
            controller: function($scope, firebaseHelper, $sce, $rootScope) {
                $scope.data = {
                    title: ""
                }
                $scope.gravatar = $rootScope.gravatar;

                $scope.onSave = function() {
                    if (!firebaseHelper.getUID()) {
                        $rootScope.notifyError("Something wrong @@");
                        $scope.onCancel();
                        return;
                    }
                    var ref = firebaseHelper.getFireBaseInstance(["ideas", $scope.group]);
                    var uid = firebaseHelper.getUID();
                    if ($scope.allowAssign && $scope.assigned_user) {
                        uid = $scope.assigned_user;
                    }
                    ref.push().setWithPriority({
                        createdDate: Date.now(),
                        title: $scope.data.title,
                        uid: uid,
                        createdBy: firebaseHelper.getUID(),
                    }, -Date.now(), function(ref) {
                        $scope.onCancel();
                    })
                };

                $scope.allowAssign = false;
                $scope.assigned_user = null;
                $scope.users = [];

                var doSync = function() {
                    // console.log("xxxxxx");
                    if (firebaseHelper.getUID()) {
                        $scope.data.uid = firebaseHelper.getUID();
                        $scope.user_profile = firebaseHelper.syncObject(["profiles_pub", $scope.data.uid]);
                        $scope.allowAssign = firebaseHelper.getRole() === "admin" || firebaseHelper.getRole() === "mod";
                        if ($scope.allowAssign) {
                            $scope.users = [];
                            firebaseHelper.getFireBaseInstance("profiles_pub").once("value", function(snapshot) {
                                snapshot.forEach(function(childSnapshot) {
                                    $scope.users.push({
                                        display_name: childSnapshot.val().display_name,
                                        uid: childSnapshot.key()
                                    });
                                });
                                $scope.assigned_user = "";
                                $scope.$apply();
                            })
                        }
                        $timeout(function() {
                            $scope.$apply();
                        }, 100)
                    }
                }

                $scope.$on("user:login", function(data) {
                    // console.log("yyyyyyy");
                    doSync();
                });
                doSync();

                $scope.onCancel = function() {
                    $scope.data.title = "";
                    if ($scope.onFinished) {
                        $scope.onFinished();
                    }
                }
            },
            template: '\
                     \
                         \
                     \

 \
                        {{createdDate}} \

{{user_profile.display_name}}
 \
                        <textarea maxlength="140" placeholder="Enter your idea here" class="form-control" rows="6" ng-model="data.title"> </textarea> \

 \

Idea of
 \
                        <select class="form-control m-b" name="account" ng-model="assigned_user"> \
                            <option value="">@me</option> \
                            <option ng-repeat="u in users" value="{{u.uid}}">{{u.display_name}}</option> \
                        </select> \

 \
                            {{140 - data.title.length}} chars left  \
                             Save \
                             Cancel \

 \

 \
            '
        }
    })

    ;
<|endoftext|>


<commit_before>import { moduleForComponent, test } from 'ember-qunit';
// import wait from 'ember-test-helpers/wait';
import hbs from 'htmlbars-inline-precompile';
import Ember from 'ember';

const firebaseStub = Ember.Service.extend({
  auth(){
    let reauth = this.get('needReauth');
    return {
      currentUser: {
        email: "example@test.com",
        delete(){
          return new Ember.RSVP.Promise((resolve, reject) => {
            if (reauth){
              reject({code: 'auth/requires-recent-login'});
            }else{
              resolve();
            }
          });
        },
      }
    };
  },
  needReauth: false
});

const notifyStub = Ember.Service.extend({
  alert(message){
    return message;
  }
});

const configStub = Ember.Service.extend({
  hardDelete: false,
  messages: {
    unsuccessfulDeleteAccount: 'We were unable to delete your account.',
    successfulDeleteAccount: 'You have successfully deleted your account!'
  }
});

const reauthenticateStub = Ember.Service.extend({
  shouldReauthenticate: false
});

// const routerStub = Ember.Service.extend({
//   transitionTo(route){
//     return route;
//   }
// });

moduleForComponent('delete-user', 'Integration | Component | delete user', {
  integration: true,
  beforeEach: function(){
    this.register('service:firebaseApp', firebaseStub);
    this.inject.service('firebaseApp');

    this.register('service:notify', notifyStub);
    this.register('service:account-config', configStub);
    this.register('service:reauthenticate', reauthenticateStub);
    this.inject.service('reauthenticate');
  }
});

test('it renders', function(assert) {
  this.render(hbs`{{#delete-user}}{{/delete-user}}`);

  assert.equal(this.$().text().trim().substring(0, 14), 'Delete Account');
});

test('Clicking submit without an e-mail should return an error', function(assert) {
  this.render(hbs`{{#delete-user}}{{/delete-user}}`);
  this.$('.common-button').click();

  assert.equal(this.$('.form-field--errors').text(), 'Incorrect email. Please re-enter your e-mail.');
});

test('Clicking submit with an incorrect e-mail should return an error', function(assert){
  this.render(hbs`{{#delete-user}}{{/delete-user}}`);

  this.$('input').val('wrong@email.com').trigger('change');
  this.$('button').click();

  assert.equal(this.$('.form-field--errors').text(), 'Incorrect email. Please re-enter your e-mail.');
});

test(('Correct submission, when reauthentication is needed, should trigger that'), function(assert){
  this.set("firebaseApp.needReauth", true);
  this.render(hbs`{{#delete-user}}{{/delete-user}}`);

  this.$('input').val("example@test.com").trigger('change');
  this.$('button').click();

  assert.notEqual(this.$('.form-field--errors').text(), 'Incorrect email. Please re-enter your e-mail.');
  assert.ok(this.get("reauthenticate.shouldReauthenticate"));
});<commit_msg>Fixed eslint for delete-user-test<commit_after>import { moduleForComponent, test } from 'ember-qunit';
// import wait from 'ember-test-helpers/wait';
import hbs from 'htmlbars-inline-precompile';
import Ember from 'ember';

const {
  Service,
  RSVP,
  get,
  set
} = Ember;

const firebaseStub = Service.extend({
  needReauth: false,
  auth() {
    let reauth = get(this, 'needReauth');
    return {
      currentUser: {
        email: 'example@test.com',
        delete() {
          return new RSVP.Promise((resolve, reject) => {
            if (reauth) {
              reject({ code: 'auth/requires-recent-login' });
            } else {
              resolve();
            }
          });
        }
      }
    };
  }
});

const notifyStub = Service.extend({
  alert(message) {
    return message;
  }
});

const configStub = Service.extend({
  hardDelete: false,
  messages: { // eslint-disable-line ember/avoid-leaking-state-in-components
    unsuccessfulDeleteAccount: 'We were unable to delete your account.',
    successfulDeleteAccount: 'You have successfully deleted your account!'
  }
});

const reauthenticateStub = Service.extend({
  shouldReauthenticate: false
});

// const routerStub = Service.extend({
//   transitionTo(route) {
//     return route;
//   }
// });

moduleForComponent('delete-user', 'Integration | Component | delete user', {
  integration: true,
  beforeEach() {
    this.register('service:firebaseApp', firebaseStub);
    this.inject.service('firebaseApp');

    this.register('service:notify', notifyStub);
    this.register('service:account-config', configStub);
    this.register('service:reauthenticate', reauthenticateStub);
    this.inject.service('reauthenticate');
  }
});

test('it renders', function(assert) {
  this.render(hbs`{{#delete-user}}{{/delete-user}}`);

  assert.equal(this.$().text().trim().substring(0, 14), 'Delete Account');
});

test('Clicking submit without an e-mail should return an error', function(assert) {
  this.render(hbs`{{#delete-user}}{{/delete-user}}`);
  this.$('.common-button').click();

  assert.equal(this.$('.form-field--errors').text(), 'Incorrect email. Please re-enter your e-mail.');
});

test('Clicking submit with an incorrect e-mail should return an error', function(assert) {
  this.render(hbs`{{#delete-user}}{{/delete-user}}`);

  this.$('input').val('wrong@email.com').trigger('change');
  this.$('button').click();

  assert.equal(this.$('.form-field--errors').text(), 'Incorrect email. Please re-enter your e-mail.');
});

test(('Correct submission, when reauthentication is needed, should trigger that'), function(assert) {
  set(this, 'firebaseApp.needReauth', true);
  this.render(hbs`{{#delete-user}}{{/delete-user}}`);

  this.$('input').val('example@test.com').trigger('change');
  this.$('button').click();

  assert.notEqual(this.$('.form-field--errors').text(), 'Incorrect email. Please re-enter your e-mail.');
  assert.ok(get(this, 'reauthenticate.shouldReauthenticate'));
});<|endoftext|>