lexeme-edit.js 36.8 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136
/* global $dj, edit, slickgrid, common, getBusyOverlay, gettext, ngettext, interpolate */

var prompter_ctrl;

var new_cr_row_counter = 1;

var auto_derivatives;

var AJAX_URLS = {
    'edit': $dj.ajax_edit_form,
    'variant0': $dj.ajax_inflection_tables,
    'variant1': $dj.ajax_inflection_tables,
    'odm': $dj.ajax_odm_forms,
    'history': $dj.ajax_history_table
};

$.extend(edit, {
    form_id: 'lexeme-edit-form',
    form_cancel_class: 'lexeme-edit-cancel',
    form_submit_class: 'lexeme-edit-submit',

    load_content: function(id, is_created, check_callback) {
        "use strict";
        var tabs = $('#lexeme-tabs');
        tabs.find('.ui-tabs-panel').each(function(i, tab) {
            $(tab).empty();
        });
        var tab_no = tabs.tabs('option', 'active');
        var tab_id = tabs.children().get(tab_no + 1).id;
        edit.load_tab(tab_id, id, check_callback);
        edit.created = Boolean(is_created);
        edit.active_id = id;
    },
    load_tab: function(tab_id, lexeme_id, check_callback) {
        "use strict";
        var key, callback;
        if (tab_id === 'edit') {
            key = 'id';
            callback = edit.form_init;
        } else {
            key = 'lexeme_id';
            callback = function() {
                edit.busy_off();
                if (tab_id === 'variant0' || tab_id === 'variant1') {
                    $('#' + tab_id).find('.form').each(function() {
                        if ($(this).text().trim() === edit.highlight_form) {
                            $(this).addClass('searched-form');
                        }
                    });
                }
            };
        }
        var data = {};
        data[key] = lexeme_id;
        if (tab_id === 'variant0') {
            data.variant = 0;
        }
        if (tab_id === 'variant1') {
            data.variant = 1;
        }
        $.ajaxJSON({
            method: 'get',
            url: AJAX_URLS[tab_id],
            dest: $('#' + tab_id),
            data: data,
            callback: callback,
            check_callback: check_callback,
            error_callback: function() {
                edit.busy_off();
            }
        });
    },

    init_form_widgets: function() {
        "use strict";
        $(document).on('click', '.lip-row span.remove', function () {
            var li = $(this).closest('li');
            var name = $('input', li)[0].name;
            var gender = li.find('.gender option:selected').text();
            if (gender) {
                var genders = get_gender_ids();
                genders.splice(genders.indexOf(gender), 1);
                var stale_attrs = check_attrs(genders);
                if (stale_attrs.length > 0) {
                    var fmt = ngettext(
                        "Atrybut: %s zostanie usunięty.",
                        "Atrybuty: %s zostaną usunięte.", stale_attrs.length);
                    if (!window.confirm(interpolate(fmt, [stale_attrs]) +
                        ' ' + gettext("Kontynuować?"))) {
                        return;
                    }
                }
            }
            if (name.substring(0, 7) !== 'lip_add')
                deleted.push(name.split('-')[0]);
            li.remove();
            edit.show_changed();
            $('#table-preview').html('');
            if (gender)
                reload_attributes();
        });
        $(document).on('click', '#add-row', function () {
            var id = edit.get_id();
            var new_row = $(get_new_row_html(id));
            init_selection(new_row.find('.gender'));
            var pattern_list = $('#pattern-list');
            pattern_list.append(new_row);
            edit.qualifier_select(pattern_list.find('.lip-qualifiers').last());
            edit.show_changed();
        });

        $(document).on('click', '.cr-row span.remove', function () {
            var li = $(this).closest('li');
            if (!li.hasClass('cr-add'))
                deleted_cr.push(Number(li[0].id.split('-')[1]));
            li.remove();
            edit.show_changed();
        });
        $(document).on('click', '#add-cr-row', function () {
            var id = edit.get_id();
            var pos = get_pos();
            $.ajaxJSON({
                method: 'get',
                url: $dj.ajax_new_cr_row,
                data: {id: id, pos_id: pos, num: new_cr_row_counter},
                callback: function(data) {
                    $('#cr-list').append(data.html);
                    new_cr_row_counter++;
                    edit.show_changed();
                }
            });
        });

        var update_preview = function () {
            var lip_row = $(this).closest('.lip-row');
            if (lip_row.hasClass('lip-row-active')) {
                set_active_lip_row.call(lip_row);
            }
        };
        $(document).on(
            'change', '#' + edit.form_id + ' input', update_preview);
        $(document).on(
            'change', '#' + edit.form_id + ' textarea', update_preview);
        $(document).on(
            'change', '#' + edit.form_id + ' select', update_preview);

        $(document).on('click', '.lip-row', set_active_lip_row);

        $(document).on('click', '.lexeme-edit-delete', delete_lexeme);

        $(document).on('change', '.cr-add .entry', set_cr_homonym_number);
        $(document).on('click', '.cr-add .homonym-number', set_cr_homonym_number);

        $('#load-filter-dialog').dialog({
            autoOpen: false,
            width: 'auto',
            modal: true
        });
        $('#choose-homonym-dialog').dialog({
            autoOpen: false,
            width: 'auto',
            modal: true
        });
        $('#prompter-dialog').dialog({
            autoOpen: false,
            width: 'auto',
            modal: true,
            buttons: [
                {
                    text: gettext("Anuluj"),
                    click: function () {
                        $(this).dialog('close');
                    }
                },
                {
                    text: gettext("Wybierz"),
                    click: input_prompter_pattern
                }
            ]
        });
        $('#auto-derivatives-dialog').dialog({
            autoOpen: false,
            width: 'auto',
            modal: true,
            buttons: [
                {
                    text: gettext("Anuluj"),
                    click: function() {
                        $(this).dialog('close');
                    }
                },
                {
                    text: gettext("Utwórz"),
                    click: create_auto_derivatives
                }
            ]
        });
        $('#action-button').click(function () {
            $('#group-action-dialog').dialog('open');
        });
        var add_action = $('#add-action');
        add_action.click(new_action_row);
        $(document).on('change', '.field-choice', update_action_row);
        $(document).on('click', '.delete-action-row', function () {
            $(this).closest('tr').remove();
        });
        $('#group-action-dialog').dialog({
            autoOpen: false,
            modal: true,
            width: 'auto',
            buttons: [
                {
                    text: gettext("Wykonaj"),
                    click: execute_actions
                }
            ]
        });
        add_action.click();
        $(document).on('click', 'button.prompter', display_prompter);
        $(document).on('click', '.prompter-row', set_active_prompter_row);
        $(document).on('click', '#prompter-checkboxes :checkbox', reload_prompter);

        $('#add-button').click(add_lexeme);
        $('#default-owner-dialog').dialog({
            autoOpen: false,
            modal: true,
            buttons: [
                {
                    text: gettext("Anuluj"),
                    click: function () {
                        $(this).dialog('close');
                    }
                },
                {
                    text: gettext("Wybierz"),
                    click: function () {
                        var value = $('#default-owner').find(':checked').val();
                        if (value) {
                            set_default_owner(value);
                            $(this).dialog('close');
                            make_new_lexeme();
                        }
                    }
                }
            ]
        });

        $(document).on('click', '#move-lexeme .label', function () {
            $('#move-lexeme').toggleClass('move-hidden');
        });
        $(document).on('change', '#id_part_of_speech', check_pos);
        $(document).on('change', '#id_new_owner', function () {
            var stale_classifications = check_classifications(), confirmed;
            if (stale_classifications.length > 0) {
                var msg = ngettext(
                    "Zostanie usunięta klasyfikacja:",
                    "Zostaną usunięte klasyfikacje:",
                    stale_classifications.length);
                confirmed = window.confirm(
                    msg + ' ' +  join_classifications(stale_classifications) +
                    '. ' + gettext("Kontynuować?"));
                if (!confirmed) {
                    revert_selection($(this));
                }
            }
            if (confirmed || stale_classifications.length === 0) {
                confirm_selection($(this));
                reload_classifications();
            }
        });
        $(document).on('change', '.gender', function () {
            var new_genders = get_gender_ids();
            var stale_attrs = check_attrs(new_genders);
            var confirmed;
            if (stale_attrs.length > 0) {
                var fmt = ngettext(
                    "Atrybut: %s zostanie usunięty.",
                    "Atrybuty: %s zostaną usunięte.", stale_attrs.length);
                confirmed = window.confirm(
                    interpolate(fmt, [join_attrs(stale_attrs)]) +
                    ' ' + gettext("Kontynuować?"));
                if (!confirmed) {
                    revert_selection($(this));
                }
            }
            if (confirmed || stale_attrs.length === 0) {
                confirm_selection($(this));
                reload_attributes();
            }
        });
        $(document).on('keyup', '#id_entry', show_homonym_count);

        $('#edit').on('scroll', function() {
            if (common.multiselect_is_open) {
                $(this).find('select[multiple]').multiselect2('close');
            }
            $('#id_new_owner').selectmenu('close');
        });

        $('#clone-lexeme-button').on('click', function() {
            clone_lexeme();
            $('#more-actions-dialog').dialog('close');
        });

        $(document).on('focus', '.derivative-input', function() {
            $(this).parent().find(':checkbox').prop('checked', true);
        });
    },
    form_init: function() {
        "use strict";
        $('button', '#edit').button();
        $('#pattern-list.editable').sortable().sortable({
            change: function () {
                edit.show_changed();
            }
        });
        //$('#pattern-list').disableSelection();
        $('.lip-row', '#pattern-list').first().click();
        $('#id_vocabularies').multiSelect({
            noneSelectedText: gettext("Wybierz słowniki"),
            selectedText: gettext("# słowników"),
            selectedList: 4
        });
        var scope_qual = $('#id_scope_qualifiers');
        edit.qualifier_select($('select.qualifiers'));
        if (scope_qual.val()) {
            $('#specialist').show();
        }
        scope_qual.bind('multiselectclick', function(event, ui) {
            var show = scope_qual.multiselect2('getChecked').length > 0;
            if ($('#specialist').is(':visible') !== show) {
                toggle_specialist(show);
            }
        });
        edit.qualifier_select($('select.lip-qualifiers'));
        init_classification_forms();
        init_extra_attr_widgets();
        $('button.prompter').button();
        var new_owner_elem = $('#id_new_owner');
        var owner = new_owner_elem.find(':selected').text();
        var bold_owner = function (text) {
            if (text === owner)
                return '<strong>' + text + '</strong>';
            else
                return text;
        };
        new_owner_elem.selectmenu({
            width: 'auto', style: 'popup', format: bold_owner});
        show_homonym_count();
        deleted = [];
        deleted_cr = [];
        edit.created = false;
        init_selection($('#id_part_of_speech'));
        init_selection($('.gender'));
        init_selection(new_owner_elem);
        edit.hide_changed();
        edit.busy_off();
    },

    form_submit: function(form_data) {
        "use strict";
        form_data.push({name: 'deleted', value: deleted});
        form_data.push({name: 'deleted_cr', value: deleted_cr});
        var vocabularies = [];
        var style_qualifiers = [], scope_qualifiers = [];
        var cvs = {};
        var multi_attrs = {};
        form_data = $.map(form_data, function (elem) {
            if (elem.name !== 'vocabularies' &&
                    elem.name.indexOf('_qualifiers') === -1 &&
                    !(/^cl[0-9]+-values$/.test(elem.name)) &&
                    !(/^attrmulti[0-9]+-value$/.test(elem.name)))
                return elem;
            else {
                if (elem.name === 'vocabularies')
                    vocabularies.push(elem.value);
                if (elem.name === 'style_qualifiers')
                    style_qualifiers.push(elem.value);
                if (elem.name === 'scope_qualifiers')
                    scope_qualifiers.push(elem.value);
                if (/^cl[0-9]+-values$/.test(elem.name)) {
                    if (cvs[elem.name] === undefined)
                        cvs[elem.name] = [];
                    cvs[elem.name].push(elem.value);
                }
                if (/^attrmulti[0-9]+-value$/.test(elem.name)) {
                    if (multi_attrs[elem.name] === undefined)
                        multi_attrs[elem.name] = [];
                    multi_attrs[elem.name].push(elem.value);
                }
                return null;
            }
        });
        form_data.push({name: 'vocabularies', value: vocabularies});
        form_data.push({name: 'style_qualifiers', value: style_qualifiers});
        form_data.push({name: 'scope_qualifiers', value: scope_qualifiers});
        $.each(cvs, function (name, value) {
            form_data.push({name: name, value: value});
        });
        $.each(multi_attrs, function (name, value) {
            form_data.push({name: name, value: value});
        });
        form_data.push({name: 'classification_values', value: cvs});
        edit.busy_on();
        var result = $.ajaxJSON({
            method: 'post',
            url: $dj.ajax_update_lexeme,
            save: true,
            data: {
                form_data: form_data
            },
            description: gettext("Zapisanie zmian"),
            callback: function (data) {
                edit.hide_changed();
                var edit_id = edit.get_id();
                var grid_id = slickgrid.active_id();
                slickgrid.reload_data(); // dziwne miejsce
                if (edit_id !== grid_id) {
                    slickgrid.row_index(edit_id);
                } else {
                    edit.load_content(edit_id);
                }
                if (data.derivatives.length > 0) {
                    auto_derivatives = data.derivatives;
                    var ul = $('#auto-derivatives-list');
                    ul.empty();
                    $.each(data.derivatives, function(i, der_data) {
                        var li = $('<li/>');
                        var name = 'der' + i;
                        var input = $('<input/>').attr('type', 'checkbox')
                            .attr('name', name).attr('id', name);
                        var label = $('<label/>').attr('for', name);
                        li.append(input).append(label).appendTo(ul);
                        if (der_data.entry) {
                            label.text(der_data.pos + ', ' + der_data.entry);
                        } else {
                            var der_input = $('<input/>').attr('type', 'text')
                                .addClass('derivative-input');
                            label.text(der_data.pos + ', ');
                            li.append(der_input);
                        }
                    });
                    $('#auto-derivatives-dialog').dialog('open');
                }
            },
            error_callback: function (xhr, status, error) {
                common.error_alert(status + ': ' + error);
                edit.busy_off();
            },
            bad_data_callback: function () {
                edit.busy_off();
                return true;
            }
        });
        if (result === false) {
            edit.busy_off();
        }
    }
});

function create_auto_derivatives() {
    "use strict";
    // zebrać numery derywatów do utworzenia
    var ul = $('#auto-derivatives-list');
    var chosen_derivatives = [];
    ul.find(':checked').each(function(i, elem) {
        var der_data = auto_derivatives[parseInt(elem.name.substr(3), 10)];
        var input = $(elem).next().next();
        if (input.is('input')) {
            der_data.entry = input.value();
        }
        chosen_derivatives.push(der_data);
    });
    var edit_id = edit.get_id();
    $.ajaxJSON({
        method: 'post',
        url: $dj.ajax_create_derivatives,
        data: {
            lexeme_id: edit_id,
            chosen_derivatives: chosen_derivatives
        },
        callback: function() {
            $('#auto-derivatives-dialog').dialog('close');
            slickgrid.reload_data();
            if (edit_id !== slickgrid.active_id()) {
                slickgrid.row_index(edit_id);
            } else {
                edit.load_content(edit_id);
            }
        },
        description: gettext("Utworzenie derywatów")
    });
}

var deleted, deleted_cr;

function init_selection(jq) {
    "use strict";
    jq.find('option:selected').addClass('last-selected');
}

function revert_selection(jq) {
    "use strict";
    jq.find('option.last-selected').prop('selected', true);
}

function confirm_selection(jq) {
    "use strict";
    jq.find('option.last-selected').removeClass('last-selected');
    jq.find('option:selected').addClass('last-selected');
}

function get_pos() {
    "use strict";
    return $('#id_part_of_speech').val();
}

function get_gender_ids() {
    "use strict";
    return $('.gender').map(function (i, el) {
        return parseInt($(el).val(), 10);
    }).toArray();
}

function get_attr_data() {
    "use strict";
    return $('.closed-attr').map(function(i, elem) {
        var val = $(elem).val();
        if (val !== '') return parseInt(val, 10);
        return undefined;
    }).toArray();
}

function get_attr_values() {
    "use strict";
    function get_attr_id(elem) {
        return parseInt($(elem).attr('data-attr_id'), 10);
    }
    var attr_values = $('.open-attr').map(function() {
        return [[get_attr_id(this), this.value]];
    }).toArray();
    attr_values = attr_values.concat($('.closed-attr').map(function() {
        return [[get_attr_id(this), parseInt(this.value, 10)]];
    }).toArray());
    return attr_values.concat($('.multiple-attr').map(function() {
        return [[
            get_attr_id(this),
            $.map($(this).val(), function(s) {return parseInt(s, 10);})
        ]];
    }).toArray());
}

function get_entry() {
    "use strict";
    return $('#id_entry').val();
}

function get_owner() {
    "use strict";
    return $('#id_new_owner').val() || $('#owner-vocabulary').text();
}

function join_attrs(attrs) {
    "use strict";
    return $.map(attrs,function (attr) {
        return $("[for='id_attr" + attr + "-value']").text().replace(':', '');
    }).join(', ');
}

function join_classifications(clas_ids) {
    "use strict";
    return $.map(clas_ids,function (c_id) {
        return $("[for='id_cl" + c_id + "-values']").text().replace(':', '');
    }).join(', ');
}

// TODO zachować wybrane wartości
function reload_classifications() {
    "use strict";
    var data = {
        lexeme_id: edit.get_id(),
        vocab_id: get_owner(),
        pos: get_pos()
    };
    $.ajaxJSON({
        method: 'get',
        url: $dj.ajax_classification_forms,
        data: data,
        dest: $('#classifications'),
        callback: init_classification_forms,
        description: gettext("Przeładowanie klasyfikacji")
    });
}

function reload_attributes() {
    "use strict";
    // TODO zachować wartości atrybutów
    var data = {
        lexeme_id: edit.get_id(),
        pos: get_pos(),
        genders: get_gender_ids()
    };
    $.ajaxJSON({
        method: 'get',
        url: $dj.ajax_extra_attributes,
        data: data,
        dest: $('#extra-attributes'),
        description: gettext("Przeładowanie atrybutów"),
        callback: init_extra_attr_widgets
    });
}

function init_classification_forms() {
    "use strict";
    $('.classification-values').multiSelect();
}

function init_extra_attr_widgets() {
    "use strict";
    $('#extra-attributes').find('select[multiple]').multiSelect();
}

function before_save() {
    "use strict";
    // sprawdzić wzór z rodzajem
    var ok = true;
    $('.lip-row').each(function () {
        var gender = $(this).find('.gender').val();
        var pattern = $(this).find('.pattern').val();
        if (gender) {
            var answer = $.ajaxJSON({
                method: 'get',
                url: $dj.ajax_check_pattern,
                data: {pattern_name: pattern, gender_id: gender},
                async: false
            }).answer;
            if (answer !== 'yes')
                ok = false;
        }
    });
    return (ok || window.confirm(
        gettext("Wzór nie pasuje do rodzaju — na pewno zapisać?")));
}

var new_row_counter = 1; // potrzebne tylko dla niepowtarzalności idów
function get_new_row_html(id) {
    "use strict";
    var new_row_html = $.ajaxJSON({
        method: 'get',
        url: $dj.ajax_new_lip_row,
        data: {lexeme_id: id, pos_id: get_pos(), num: new_row_counter},
        async: false // w zasadzie się tak nie powinno robić
    }).html;
    new_row_counter++;
    return new_row_html;
}

var set_active_lip_row = function () {
    "use strict";
    $('.lip-row-active').removeClass('lip-row-active ui-state-active');
    $(this).addClass('lip-row-active ui-state-active');
    // tabelka
    var data = {
        lexeme_id: edit.get_id(),
        entry: get_entry(),
        pos: get_pos(),
        pattern: $('input.pattern', this).value(),
        gender: $('.gender', this).value(),
        attr_data: get_attr_data(),
        lip_id: $('input.pattern', this)[0].name.split('-')[0]
    };
    $.ajaxJSON({
        method: 'get',
        dest: $('#table-preview'),
        url: $dj.ajax_table_preview,
        data: data,
        error_callback: function () {
            $('#table-preview').html('');
        }
    });
};

function delete_lexeme() {
    "use strict";
    var id = edit.get_id();
    if (window.confirm(gettext("Na pewno usunąć leksem?"))) {
        slickgrid.loader.onDataLoading.notify();
        $.ajaxJSON({
            method: 'post',
            url: $dj.ajax_delete_lexeme,
            data: {lexeme_id: id},
            description: gettext("Usunięcie leksemu"),
            callback: function () {
                edit.hide_changed();
                slickgrid.reload_data();
                slickgrid.search();
            }
        });
    }
}

// podpowiadacz

var display_prompter = function () {
    "use strict";
    var prompter_checkboxes = $('#prompter-checkboxes');
    var prompter_commonness = $('#prompter-commonness');
    var prompter_gender = $('#prompter-gender');
    $('#prompter-list').html('');
    $('#prompter-table-preview').html('');
    prompter_checkboxes.hide();
    prompter_checkboxes.find(':checkbox').prop('checked', true);
    if (['subst', 'skrs', 'osc'].indexOf(get_pos()) === -1 ||
            $(this).closest('li').find('.gender').val() === '') {
        prompter_gender.prop('checked', false).disable();
        prompter_gender.next().addClass('disabled');
    } else {
        prompter_gender.enable();
        prompter_gender.next().removeClass('disabled');
    }
    var cvs = $('#id_cl' + $dj.commonness + '-values').val();
    if (!cvs || cvs.length === 0) {
        prompter_commonness.prop('checked', false).disable();
        prompter_commonness.next().addClass('disabled');
    } else {
        prompter_commonness.enable();
        prompter_commonness.next().removeClass('disabled');
    }
    $('#prompter-dialog').dialog('open');
    reload_prompter({button: this});
};

function reload_prompter(arg) {
    "use strict";
    prompter_ctrl = getBusyOverlay(
        $('#prompter-dialog')[0],
        {},
        {size: 30});
    // załadować dane do promptera
    var elem;
    if (arg.button)
        elem = $(arg.button).closest('.lip-row');
    else
        elem = $('.lip-row-active');
    var gender = elem.find('.gender').val();
    var id = edit.get_id();
    var cvs = $('#id_cl' + $dj.commonness + '-values').val();
    if (!cvs) cvs = [];
    var gender_check, cv_check, bl_check;
    var entry = get_entry();
    var pos = get_pos();
    gender_check = $('#prompter-gender').prop('checked');
    cv_check = $('#prompter-commonness').prop('checked');
    bl_check = $('#prompter-blacklist').prop('checked');
    $.ajaxJSON({
        method: 'get',
        dest: $('#prompter-list'),
        url: $dj.ajax_prompter_list,
        data: {
            gender_id: gender,
            lexeme_id: id,
            entry: entry,
            pos_id: pos,
            commonness_ids: cvs,
            gender_check: gender_check,
            cv_check: cv_check,
            bl_check: bl_check
        },
        callback: function () {
            prompter_ctrl.remove();
            $('#prompter-list').children().first().click();
            $('#prompter-checkboxes').show();
        }
    });
}

var set_active_prompter_row = function () {
    "use strict";
    $('.prompter-row-active').removeClass('prompter-row-active');
    $(this).addClass('prompter-row-active');
    // tabelka
    var data = {
        lexeme_id: edit.get_id(),
        entry: get_entry(),
        pos: get_pos(),
        pattern: $('.pattern', this).text(),
        gender: $('.gender-id', this).text(),
        attr_data: get_attr_data(),
        lip_id: 'lip_add'
    };
    $.ajaxJSON({
        method: 'get',
        dest: $('#prompter-table-preview'),
        url: $dj.ajax_table_preview,
        data: data,
        error_callback: function () {
            $('#prompter-table-preview').html('');
        }
    });
};

function input_prompter_pattern() {
    "use strict";
    var active = $('.prompter-row-active');
    var pattern;
    if (active.length > 0) {
        $('#prompter-dialog').dialog('close');
        pattern = active.find('.pattern').text();
        $('.lip-row-active').find('input.pattern').val(pattern);
        edit.show_changed();
    }
}

function check_classifications() {
    "use strict";
    var new_classifications = $.ajaxJSON({
        method: 'get',
        url: $dj.ajax_check_classifications,
        data: {lexeme_id: edit.get_id(), pos: get_pos(), owner_id: get_owner()},
        async: false
    }).classifications;
    var old_classifications = $('#classifications').find('.classification-values')
        .map(function () {
            if($(this).find(':selected').length > 0)
                return parseInt(this.id.replace('id_cl', '').replace('-values', ''), 10);
            return null;
        });
    var stale_classifications = [];
    old_classifications.each(function (i, c_id) {
        if (new_classifications.indexOf(c_id) === -1)
            stale_classifications.push(c_id);
    });
    return stale_classifications;
}

function check_attrs(genders) {
    "use strict";
    var new_attrs = $.ajaxJSON({
        method: 'get',
        url: $dj.ajax_check_attributes,
        data: {lexeme_id: edit.get_id(), pos: get_pos(), genders: genders},
        async: false
    }).attrs;
    var old_attrs = $('#extra-attributes').find('select').map(function (i, el) {
        if (el.id.indexOf('id_attr') !== -1) {
            return parseInt(
                el.id.split('-')[0].substring('id_attr'.length), 10);
        }
    });
    var stale_attrs = [];
    old_attrs.each(function (i, attr) {
        if (new_attrs.indexOf(attr) === -1 && !isNaN(attr))
            stale_attrs.push(attr);
    });
    return stale_attrs;
}

var check_pos = function () {
    "use strict";
    var pos = get_pos();
    if (!pos)
        return;
    var bad_lips = false, good_genders = [], confirmed, had_gender;
    var lip_row_elems = $('.lip-row'), cr_row_elems = $('.cr-row');
    if (lip_row_elems.length > 0) {
        had_gender = $(lip_row_elems[0]).find('select.gender').length > 0;
        var pattern = $(this).find('input.pattern').val();
        var answer = $.ajaxJSON({
            method: 'get',
            url: $dj.ajax_check_pos,
            data: {pos_id: pos, had_gender: had_gender},
            async: false
        }).answer;
        if (answer !== 'yes')
            bad_lips = true;
    }
    if (!bad_lips && had_gender) {
        good_genders = lip_row_elems.map(function(i, elem) {
            return $(elem).find('.gender').val();
        }).toArray();
    }
    var stale_attrs = check_attrs(good_genders);
    var stale_classifications = check_classifications();
    if (bad_lips || cr_row_elems.length > 0 ||
        stale_attrs.length > 0 || stale_classifications.length > 0) {
        var lips_text = '', cr_text = '';
        if (bad_lips > 0) {
            lips_text = gettext("wszystkie sposoby odmiany") + '\n';
        }
        if (cr_row_elems.length > 0) {
            cr_text += gettext("wszystkie odsyłacze") + '\n';
        }
        var attr_text = '';
        if (stale_attrs.length > 0) {
            attr_text = gettext("atrybuty") + ': ' +
                join_attrs(stale_attrs) + '\n';
        }
        var clas_text = '';
        if (stale_classifications.length > 0) {
            clas_text = gettext("klasyfikacje") + ': ' +
                join_classifications(stale_classifications) + '\n';
        }
        confirmed = window.confirm(
            gettext("Zostaną usunięte:") + '\n' + lips_text + cr_text +
            attr_text + clas_text + gettext("Kontynuować?"));
        if (!confirmed) {
            revert_selection($(this));
        }
    }
    if (confirmed || !(bad_lips || cr_row_elems.length > 0 ||
        stale_attrs.length > 0 || stale_classifications.length > 0)) {
        confirm_selection($(this));
        var reload_preview = false;
        if (bad_lips) {
            lip_row_elems.each(function () {
                var li = $(this);
                // copypasta...
                var name = li.find('input')[0].name;
                if (name.substring(0, 7) !== 'lip_add')
                    deleted.push(name.split('-')[0]);
                li.remove();
                reload_preview = true;
            });
        }
        lip_row_elems.find('.lip-lc').val($dj.lexical_classes[pos]);
        if (reload_preview)
            $('#table-preview').html('');
        cr_row_elems.each(function () {
            var li = $(this);
            // copypasta...
            if (!li.hasClass('cr-add'))
                deleted_cr.push(Number(li[0].id.split('-')[1]));
            li.remove();
        });
        reload_attributes();
        reload_classifications();
    }
};

// dodawanie

function add_lexeme() {
    "use strict";
    // trzeba zdecydować, jaki słownik właściciel
    if ($dj.default_owner === '') {
        $('#default-owner-dialog').dialog('open');
    } else {
        make_new_lexeme();
    }
}

function set_default_owner(vocab_id) {
    "use strict";
    $dj.default_owner = vocab_id;
    $.ajaxJSON({
        method: 'post',
        url: $dj.ajax_save_default_owner,
        data: {vocab_id: vocab_id},
        description: gettext("Zapisanie domyślnego słownika")
    });
}

function make_new_lexeme() {
    "use strict";
    $.ajaxJSON({
        method: 'post',
        url: $dj.ajax_create_lexeme,
        data: {},
        description: gettext("Utworzenie leksemu"),
        callback: function(data) {
            edit.load_content(data.id, true);
        }
    });
}

function clone_lexeme() {
    "use strict";
    edit.busy_on();
    $.ajaxJSON({
        method: 'post',
        url: $dj.ajax_clone_lexeme,
        data: {lexeme_id: edit.get_id()},
        description: gettext("Sklonowanie leksemu"),
        callback: function(data) {
            slickgrid.reload_data();
            slickgrid.row_index(data.new_id);
        }
    });
}

function show_homonym_count() {
    "use strict";
    var entry = get_entry();
    $.ajaxJSON({
        method: 'get',
        url: $dj.ajax_homonym_count,
        data: {entry: entry, lexeme_id: edit.get_id()},
        descripton: gettext("Pobranie liczby homonimów"),
        callback: function (data) {
            var info = '';
            if (entry === get_entry()) {
                if (data.count > 0) {
                    info = data.count + ' homonim';
                    if (data.count > 1 && data.count < 5)
                        info += 'y';
                    else if (data.count >= 5)
                        info += 'ów'; // "22 homonimów", ale nigdy nie będzie aż tyle
                }
                $('#homonym-count').text(info);
            }
        }
    });
}

// odsyłacze

function homonym_choice(labels, lexemes, hom_field) {
    "use strict";
    var table = $('#homonym-list');
    var thead = table.find('thead');
    var tbody = table.find('tbody');
    thead.html('');
    $.each(labels, function(i, label) {
        var item = $('<th/>').text(label);
        thead.append(item);
    });
    tbody.html('');
    // napakować okienko na podstawie wyniku z ajaxa
    $.each(lexemes, function (i, data) {
        var item = $('<tr/>').addClass('ui-state-default')
            .attr('id', 'hom' + data.homonym_number);
        $.each(data, function(i, data_item) {
            item.append($('<td/>').text(data_item));
        });
        item.click(function () {
            hom_field.val($(this).children().first().text());
            $('#choose-homonym-dialog').dialog('close');
        });
        tbody.append(item);
    });
    $('#choose-homonym-dialog').dialog('open');
}

var set_cr_homonym_number = function () {
    "use strict";
    var $t = $(this).parent();
    $.ajaxJSON({
        method: 'get',
        url: $dj.ajax_cr_homonyms,
        data: {
            entry: $t.find('.entry').val(),
            cr_type: $t.find('.type').val()
        },
        description: gettext("Sprawdzenie homonimów"),
        callback: function (data) {
            var lexemes = data.lexemes;
            if (lexemes.length === 1)
                $t.find('.homonym-number').val(lexemes[0][0]);
            else if (lexemes.length > 1) {
                homonym_choice(
                    data.labels, lexemes, $t.find('.homonym-number'));
            } else { // nie ma żadnego
                window.alert(gettext("Brak pasujących leksemów."));
                $t.find('.entry').val('');
                $t.find('.homonym-number').val('');
            }
        }
    });
};

// akcje grupowe

var update_action_row = function () {
    "use strict";
    var num = this.id.split('-')[0].split('_')[2];
    var row = $(this).closest('tr');
    var field_name = $(this).val();
    $.ajaxJSON({
        method: 'get',
        url: $dj.ajax_dynamic_fields,
        data: {field_name: field_name},
        callback: function (data) {
            row.find('.action').html(data.action.replace('NUM', num));
            row.find('.value').html(data.value.replace('NUM', num));
        }
    });
};

var filter_row_counter = 1; // dla niepowtarzalności idów

function new_action_row() {
    "use strict";
    $.ajaxJSON({
        method: 'get',
        url: $dj.ajax_new_action_row,
        data: {num: filter_row_counter},
        callback: function(data) {
            var action_tr = $(data.html);
            $('#action-list').append(action_tr);
            action_tr.find('.field-choice').change();
            filter_row_counter++;
        }
    });
}

var execute_actions = function () {
    "use strict";
    var actions = $('#action-list').find('tr').map(function () {
        var $t = $(this);
        return {
            field: $t.find('.field-choice').val(),
            type: $t.find('.action-choice').val(),
            value: $t.find('.value-choice').val()
        };
    }).get();
    var filter = slickgrid.loader.getFilter();
    var $t = $(this);
    $.ajaxJSON({
        method: 'post',
        url: $dj.ajax_execute_actions,
        data: {filter: filter, actions: actions},
        callback: function () {
            $t.dialog('close');
            slickgrid.loader.setFilter(filter);
        }
    });
};

// specjalistyczność

function toggle_specialist(show) {
    "use strict";
    var sp =  $('#specialist');
    sp.toggle(show);
    sp.find('input').prop('checked', show);
}