lexeme-view.js 34.6 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 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257
var prompter_ctrl, created;

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 selected_qualifiers_text(num, total, checked) {
  "use strict";
  if (num >= 4)
    return num + ' kwalifikatorów';
  var grouped = {};
  $.each(checked, function(i, elem) {
    var id = elem.value;
    var vocab = $dj.vocabs[id];
    if (grouped[vocab] === undefined)
      grouped[vocab] = [];
    grouped[vocab].push(elem.title);
  });
  var vocab_table = [];
  var owner = $('#owner-vocabulary').text();
  if (grouped[owner])
    vocab_table.push(owner + ': ' + grouped[owner].join(', '));
  $.each(grouped, function(vocab, qualifiers) {
    if (vocab !== owner)
      vocab_table.push(vocab + ': ' + qualifiers.join(', '));
  });
  return vocab_table.join('; ');
}

function selected_cvs_text(num, total, checked) {
  "use strict";
  if (num >= 4)
    return num + ' wartości';
  var values = $.map(checked, function(elem) {
    return common.strip(elem.title);
  });
  return values.join(', ');
}

var main_field = 'entry';
var qualifier_options = {
  noneSelectedText: 'Wybierz',
    selectedText: selected_qualifiers_text,//'# kwalifikatorów',
    selectedList: 4,
    header: false,
    create: function() {
    "use strict";
    var select = $(this);
    var selected = select.val();
    if (selected) {
      $.each(selected, function(i, value) {
        toggle_excluded(select, value, false);
      });
    }
  },
  click: function(event, ui) {
    "use strict";
    toggle_excluded(this, ui.value, !ui.checked);
  }
};

function list_searchoptions(list) {
  "use strict";
  return {
    searchhidden: true,
    sopt: ['eq', 'ne'],
    value: list
  };
}

function list_column(name, displayed, list) {
  "use strict";
  return {
    name: name,
    index: name,
    hidden: true,
    hidedlg: !displayed,
    sortable: false,
    searchoptions: list_searchoptions(list),
    stype: 'select'
  };
}

function text_column(name) {
  "use strict";
  return {
    name: name,
    index: name,
    hidden: true,
    hidedlg: true,
    sortable: false,
    searchoptions: {searchhidden: true}
  };
}

function lip_column(name) {
  "use strict";
  return {
    name: name,
    index: name,
    hidden: true,
    sortable: false,
    searchoptions: {searchhidden: true, sopt: ['eq', 'ne']}
  };
}

function count_column(name) {
  "use strict";
  return {
    name: name,
    index: name,
    hidden: true,
    hidedlg: true,
    sortable: false,
    searchoptions: {searchhidden: true, sopt: ['eq', 'ge', 'le']}
  };
}

$.extend(jqgrid, {
  main_field: main_field,
  initialColModel: [
    {name: 'id', index: 'id', search: false, hidden: true},
    {name: 'entry',index: 'entry'},
    {
      name: 'part_of_speech',
      index: 'part_of_speech',
      searchoptions: list_searchoptions($dj.parts_of_speech),
      stype: 'select'
    },
    lip_column('pattern_name'),
    count_column('pattern_count'),
    lip_column('inflection_characteristic'),
    count_column('ic_count'),
    {
      name: 'form',
      index: 'form',
      hidden: true,
      hidedlg: true,
      sortable: false,
      searchoptions: {searchhidden: true}
    },
    list_column('containing_vocabulary', true, $dj.visible_vocabularies),
    list_column('owner_vocabulary', true, $dj.visible_vocabularies),
    list_column('status', true, $dj.status_options),
    text_column('comment'),
    list_column('lexeme_qualifier', false, $dj.qualifier_options),
    list_column('lip_qualifier', false, $dj.qualifier_options),
    list_column('qualifier', false, $dj.qualifier_options),
    list_column('classification_value', false, $dj.cv_options),
    text_column('gloss'),
    text_column('note'),
    list_column('cr_type', false, $dj.cr_type_options)
  ],
  initialColNames: [
    'Id', 'Hasło','Część mowy', 'Wzór', 'Liczba wzorów', 'Char. fleks.',
    'Liczba char. fleks.', 'Forma', 'Słownik używający', 'Słownik właściciel',
    'Status', 'Komentarz', 'Kwal. leksemu', 'Kwal. odmieniasia',
    'Kwal. przy dow. formie', 'Wartość klasyfikacji', 'Glosa', 'Nota',
    'Typ odsyłacza'
  ],
  initial_sort_rules: [{field: main_field, order: 'asc', a_tergo: false}],
  grid_caption: "Leksemy",
  edit_form_id: 'lexeme-edit-form',
  edit_form_cancel_id: 'lexeme-edit-cancel',
  edit_form_submit_id: 'lexeme-edit-submit',
  reverse_exclusion_classes: {}
});
var deleted, deleted_cr;
$dj.reverse_exclusion_classes = {};

$.each($dj.exclusion_classes, function(ec, qualifiers) {
  "use strict";
  $.each(qualifiers, function(i, q_id) {
    $dj.reverse_exclusion_classes[q_id] = ec;
  });
});

function toggle_excluded(select, value, enable) {
  "use strict";
  var ec = $dj.reverse_exclusion_classes[Number(value)],
      values = $dj.exclusion_classes[ec];
  if (values)
    $.each(values, function(i, v) {
      if (v !== Number(value))
        common.multiselect_toggle(select, v, enable);
    });
}

function sort_rule_special_features(rule) {
  "use strict";
  $('#entries_a_tergo').prop('checked', rule.a_tergo);
}
jqgrid.sort_rule_special_features = sort_rule_special_features;

function prepare_sort_rules(sort_rules, old_sort_rules) {
  "use strict";
  if (sort_rules[0].field === 'entry') {
    var a_tergo = false;
    $.each(old_sort_rules, function(i, rule) {
      if (rule.field === 'entry') {
        a_tergo = rule.a_tergo;
        return false;
      }
      return null;
    });
    sort_rules[0].a_tergo = a_tergo;
  }
}
jqgrid.prepare_sort_rules = prepare_sort_rules;

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

function get_ics() {
  "use strict";
  return $('.inflection-characteristic').map(function(i, el) {
    return parseInt($(el).val(), 10);}).toArray();
}

function get_ic_symbols() {
  "use strict";
  return $('.inflection-characteristic option:selected').map(function(i, el) {
    return $(el).text();}).toArray();
}

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

function get_owner() {
  "use strict";
  return $('#id_new_owner').val();
}

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(', ');
}

function init_form_widgets() {
  "use strict";
  $(document).on('click', '.lip-row span.remove', function() {
    var li = $(this).closest('li');
    var name = $('input', li)[0].name;
    var ic_symbol = li.find('.inflection-characteristic option:selected').text();
    var ics = get_ic_symbols();
    ics.splice(ics.indexOf(ic_symbol), 1);
    var stale_attrs = check_attrs(ics);
    if (stale_attrs.length > 0) {
      if (!window.confirm("Atrybuty: " + join_attrs(stale_attrs) +
        ' zostaną usunięte. Kontynouwać?')) {
        return;
      }
    }
    if (name.substring(0,7) !== 'lip_add')
      deleted.push(name.split('-')[0]);
    li.remove();
    jqgrid.show_changed();
    $('#table-preview').html('');
    reload_attributes();
  });
  $(document).on('click', '#add-row', function() {
    var id = lexeme_id();
    var new_row = $(get_new_row_html(id));
    init_selection(new_row.find('.inflection-characteristic'));
    var pattern_list = $('#pattern-list');
    pattern_list.append(new_row);
    var elem = pattern_list.find('.lip-qualifiers').last();
    elem.multiselect2(qualifier_options);
    elem.next().width('220px');
    jqgrid.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();
    jqgrid.show_changed();
  });
  $(document).on('click', '#add-cr-row', function() {
    var id = lexeme_id();
    var pos = get_pos();
    var new_row = $(get_new_cr_row_html(id, pos));
    $('#cr-list').append(new_row);
    jqgrid.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', '#' + jqgrid.edit_form_id + ' input', update_preview);
  $(document).on(
    'change', '#' + jqgrid.edit_form_id + ' textarea', update_preview);
  $(document).on(
    'change', '#' + jqgrid.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: "Anuluj",
        click: function() { $(this).dialog("close"); }
      },
      {
        text: "Wybierz",
        click: input_prompter_pattern
      }
    ]
  });
  $('#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: "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: "Anuluj",
        click: function() { $(this).dialog("close"); }
      },
      {
        text: "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) {
      confirmed = window.confirm(
        'Zostaną usunięte klasyfikacje: ' +
          join_classifications(stale_classifications) +  '. Kontynuować?');
      if (!confirmed) {
        revert_selection($(this));
      }
    }
    if (confirmed || stale_classifications.length === 0) {
      confirm_selection($(this));
      reload_classifications();
    }
  });
  $(document).on('change', '.inflection-characteristic', function() {
    var new_ics = get_ic_symbols();
    var stale_attrs = check_attrs(new_ics);
    var confirmed;
    if (stale_attrs.length > 0) {
      confirmed = window.confirm("Atrybuty: " + join_attrs(stale_attrs) +
        ' zostaną usunięte. Kontynouwać?');
      if (!confirmed) {
        revert_selection($(this));
      }
    }
    if (confirmed || stale_attrs.length === 0) {
      confirm_selection($(this));
      reload_attributes();
    }
  });
  $(document).on('keyup', '#id_entry', show_homonym_count);
}
jqgrid.init_form_widgets = init_form_widgets;

function lexeme_id() {
  "use strict";
  return $('#' + jqgrid.edit_form_id).find('input[name=id]').value();
}

// TODO zachować wybrane wartości
function reload_classifications() {
  "use strict";
  var data = {
    lexeme_id: lexeme_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: "Przeładowanie klasyfikacji"
  });
}

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

function load_content(id, is_created) {
  "use strict";
  $.ajaxJSON({
    method: 'get',
    url: $dj.ajax_edit_form,
    dest: $('#edit'),
    data: {id: id},
    callback: function() {
      edit_form_init();
      created = Boolean(is_created);
    }
  });
  $.ajaxJSON({
    method: 'get',
    url: $dj.ajax_inflection_tables,
    dest: $('#variant0'),
    data: {lexeme_id: id, variant: 0}
  });
  $.ajaxJSON({
    method: 'get',
    url: $dj.ajax_inflection_tables,
    dest: $('#variant1'),
    data: {lexeme_id: id, variant: 1}
  });
  $.ajaxJSON({
    method: 'get',
    url: $dj.ajax_odm_forms,
    dest: $('#odm'),
    data: {lexeme_id: id}
  });
  $.ajaxJSON({
    method: 'get',
    url: $dj.ajax_history_table,
    dest: $('#history'),
    data: {lexeme_id: id}
  });
  jqgrid.grid.jqGrid('setGridParam', {'lastSelectedId' : id});
}
jqgrid.load_content = load_content;

function init_classification_forms() {
  "use strict";
  $('.classification-values').multiselect2({
    noneSelectedText: 'Wybierz',
    selectedText: selected_cvs_text,//'# wartości',
    selectedList: 4,
    header: false
  });
}

function edit_form_init() {
  "use strict";
  $('button', '#edit').button();
  $('#pattern-list.editable').sortable().sortable({
    change: function() {
      jqgrid.show_changed();
    }
  });
  //$('#pattern-list').disableSelection();
  $('.lip-row', '#pattern-list').first().click();
  $('#id_vocabularies').multiselect2({
    noneSelectedText: 'Wybierz słowniki',
    selectedText: '# słowników',
    selectedList: 4,
    header: false
  });
  $('#id_qualifiers').multiselect2(qualifier_options);
  $('.lip-qualifiers').multiselect2(qualifier_options).next().width('220px');
  init_classification_forms();
  $('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 = [];
  created = false;
  init_selection($('#id_part_of_speech'));
  init_selection($('.inflection-characteristic'));
  init_selection(new_owner_elem);
  jqgrid.hide_changed();
  if (jqgrid.ctrl)
    jqgrid.ctrl.remove();
}
jqgrid.edit_form_init = edit_form_init;

jqgrid.edit_form_submit = function() {
  "use strict";
  var this_form = $(this);
  var form_data = this_form.serializeArray();
  form_data.push({name: 'deleted', value: deleted});
  form_data.push({name: 'deleted_cr', value: deleted_cr});
  var vocabularies = [];
  var qualifiers = [];
  var cvs = {};
  var multi_attrs = {};
  form_data = $.map(form_data, function(elem) {
    if (elem.name !== 'vocabularies' && elem.name !== 'qualifiers' &&
        !(/^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 === 'qualifiers')
        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: 'qualifiers', value: 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});
  jqgrid.ctrl = getBusyOverlay(
    'viewport',
    {color: 'black', opacity: 0.5},
    {size: 100});
  var result = $.ajaxJSON({
    method: 'post',
    url: $dj.ajax_update_lexeme,
    save: true,
    data: {
      form_data: form_data,
      mask: jqgrid.grid.jqGrid('getGridParam', 'postData').mask
    },
    description: "Zapisanie zmian",
    callback: function() {
      jqgrid.hide_changed();
      jqgrid.grid.jqGrid('setGridParam', {'setOnComplete' : true});
      jqgrid.grid.trigger("reloadGrid");
      load_content(lexeme_id());
    },
    error_callback: function(xhr, status, error) {
      common.error_alert(status + ': ' + error);
      if (jqgrid.ctrl)
        jqgrid.ctrl.remove();
    },
    bad_data_callback: function() {
      if (jqgrid.ctrl)
        jqgrid.ctrl.remove();
      return true;
    }
  });
  if (result === false && jqgrid.ctrl) {
    jqgrid.ctrl.remove();
  }
  return false;
};

function before_save(){
  "use strict";
  // sprawdzić wzór z charflem
  var ok = true;
  $('.lip-row').each(function() {
    var ic = $(this).find('select.inflection-characteristic').val();
    var pattern = $(this).find('input.pattern').val();
    var result = $.ajax({
      type: 'get',
      url: $dj.ajax_check_pattern,
      data: {pattern_name: pattern, ic_id: ic},
      async: false
    }).responseText;
    if ($.parseJSON(result).answer !== 'yes')
      ok = false;
  });
  return (ok ||
    window.confirm("Wzór nie pasuje do charakterystyki - 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 new_cr_row_counter = 1; // potrzebne tylko dla niepowtarzalności idów
function get_new_cr_row_html(id, pos) {
  "use strict";
  var new_row_html = $.ajax({
    type: 'get',
    url: $dj.ajax_new_cr_row,
    data: {id: id, pos_id: pos},
    async: false
  }).responseText;
  var row_html = new_row_html.replace(/NUM/g, new_cr_row_counter);
  new_cr_row_counter++;
  return 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: lexeme_id(),
    entry: get_entry(),
    pattern: $('input.pattern', this).value(),
    inflection_characteristic:
      $('.inflection-characteristic', this).value(),
    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 = lexeme_id();
  if (window.confirm("Na pewno usunąć leksem?")) {
    $.ajaxJSON({
      method: 'post',
      url: $dj.ajax_delete_lexeme,
      data: {lexeme_id: id},
      description: 'Usunięcie leksemu',
      callback: function() {
        jqgrid.grid.trigger("reloadGrid");
        jqgrid.findAndScroll();
      }
    });
  }
}

// filtry

function create_button(button_class, icon_class, text) {
  "use strict";
  var button = $('<a/>')
    .addClass('ui-state-default ui-corner-all ' + button_class)
    .addClass('fm-button fm-button-icon-left');
  var icon = $('<span/>').addClass('ui-icon ' + icon_class);
  button.append(icon).append(text);
  return button;
}

function add_buttons(f) {
  "use strict";
  if (f[0].p) {
    var button_save = create_button(
      'ui-save', 'ui-icon-disk', 'Zapisz filtr');
    var button_load = create_button(
      'ui-load', 'ui-icon-arrowthickstop-1-s', 'Załaduj filtr');
    f.next().find('tr').last().children().first()
      .append(button_save).append(button_load);
    button_save.click(function() {
      var filter_name, filters, post_data;
      filter_name = window.prompt("Wybierz nazwę filtru do zapisania");
      if(filter_name) {
        filters = $('.searchFilter').jqFilter('filterData');
        post_data = {
          name: filter_name,
          serialized_filter: $.toJSON(filters)
        };
        var save_filter_data = {
          method: 'post',
          url: $dj.ajax_save_filter,
          data: post_data,
          description: 'Zapisanie filtru'
        };
        $.ajaxJSON($.extend(save_filter_data, {
          callback: function(data) {
            if (data.exists &&
                window.confirm("Filtr o tej nazwie już istnieje. Nadpisać?")) {
              $.ajaxJSON($.extend(save_filter_data, {
                data: $.extend(post_data, {force: true})
              }));
            }
          }
        }));
      }
      return false;
    });
    button_load.click(function() {
      $.ajaxJSON({
        method: 'get',
        url: $dj.ajax_get_filters,
        data: {},
        description: 'Pobranie listy filtrów',
        callback: filter_choice
      });
      return false;
    });
  }
}
jqgrid.add_buttons = add_buttons;

function filter_choice(ajax_data) {
  "use strict";
  var filters = ajax_data.filters;
  var list = $('#filter-list');
  list.html('');
  // napakować okienko na podstawie wyniku z ajaxa
  $.each(filters, function(i, filter) {
    var item = $('<li/>').addClass('ui-state-default').attr('id', filter.id);
    var delete_button = $('<span/>')
      .addClass('remove ui-icon ui-icon-closethick');
    delete_button.click(function() {
      if (window.confirm('Usunąć filtr "' + filter.name + '"?')) {
        $.ajaxJSON({
          method: 'post',
          url: $dj.ajax_delete_filter,
          data: {id: filter.id},
          description: 'Usunięcie filtru',
          callback: function() {
            item.remove();
          }
        });
      }
      return false;
    });
    item.append(delete_button);
    item.append(filter.name);
    item.click(function() {
      jqgrid.put_filter(filter.json);
      $("#load-filter-dialog").dialog('close');
    });
    list.append(item);
  });
  $("#load-filter-dialog").dialog('open');
}

// podpowiadacz

var display_prompter = function() {
  "use strict";
  var prompter_checkboxes = $('#prompter-checkboxes');
  var prompter_commonness = $('#prompter-commonness');
  $('#prompter-list').html('');
  $('#prompter-table-preview').html('');
  prompter_checkboxes.hide();
  prompter_checkboxes.find(':checkbox').prop('checked', true);
  var cvs = $('#id_cl' + $dj.commonness + '-values').val();
  if (!cvs || cvs.length === 0) {
    prompter_commonness.prop('checked', false);
    prompter_commonness.prop('disabled', true);
    prompter_commonness.next().addClass('disabled');
  } else {
    prompter_commonness.prop('disabled', false);
    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 ic = elem.find('select.inflection-characteristic').val();
  var id = lexeme_id();
  var cvs = $('#id_cl' + $dj.commonness + '-values').val();
  if (!cvs) cvs = [];
  var ic_check, cv_check, bl_check;
  var entry = get_entry();
  var pos = get_pos();
  ic_check = $('#prompter-ic').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: {
      ic_id: ic,
      lexeme_id: id,
      entry: entry,
      pos_id: pos,
      commonness_ids: cvs,
      ic_check: ic_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: lexeme_id(),
    entry: get_entry(),
    pos: get_pos(),
    pattern: $('.pattern', this).text(),
    inflection_characteristic: $('.ic-id', this).text(),
    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);
    jqgrid.show_changed();
  }
}

function check_classifications() {
  "use strict";
  var new_classifications = $.ajaxJSON({
    method: 'get',
    url: $dj.ajax_check_classifications,
    data: {lexeme_id: lexeme_id(), pos: get_pos(), owner_id: get_owner()},
    async: false
  }).classifications;
  var old_classifications = $('#classifications').find('.classification-values')
    .map(function(i, el) {
      return parseInt(el.id.replace('id_cl', '').replace('-values', ''), 10);
    });
  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(ics) {
  "use strict";
  var new_attrs = $.ajaxJSON({
    method: 'get',
    url: $dj.ajax_check_attributes,
    data: {lexeme_id: lexeme_id(), pos: get_pos(), ics: ics},
    async: false
  }).attrs;
  var old_attrs = $('#extra-attributes').find('select').map(function(i, el) {
    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)
      stale_attrs.push(attr);
  });
  return stale_attrs;
}

var check_pos = function() {
  "use strict";
  var pos = get_pos();
  var bad_lips = [], good_ics = [], confirmed;
  var lip_row_elems = $('.lip-row'), cr_row_elems = $('.cr-row');
  lip_row_elems.each(function() {
    var ic = $(this).find('select.inflection-characteristic').val();
    var ic_symbol = $(this).find(
      'select.inflection-characteristic :selected').text();
    var pattern = $(this).find('input.pattern').val();
    var answer = $.ajaxJSON({
      method: 'get',
      url: $dj.ajax_check_pos,
      data: {pos_id: pos, ic_id: ic},
      async: false
    }).answer;
    if (answer !== 'yes')
      bad_lips.push({ic: ic_symbol, pattern: pattern});
    else
      good_ics.push(ic_symbol);
  });
  var stale_attrs = check_attrs(good_ics);
  var stale_classifications = check_classifications();
  if (bad_lips.length > 0 || cr_row_elems.length > 0 ||
      stale_attrs.length > 0 || stale_classifications.length > 0) {
    var lips_text = '', cr_text = '', lips = [];
    if (bad_lips.length > 0) {
      $.each(bad_lips, function(i, t) {
        lips.push('(' + t.ic + ', ' + t.pattern + ')');
      });
    }
    if (lips.length > 0) {
      lips_text = "sposoby odmiany: " + lips.join(', ') + '\n';
    }
    if (cr_row_elems.length > 0) {
      cr_text += "wszystkie odsyłacze\n";
    }
    var attr_text = '';
    if (stale_attrs.length > 0) {
      attr_text = "atrybuty: " + join_attrs(stale_attrs) + '\n';
    }
    var clas_text = '';
    if (stale_classifications.length > 0) {
      clas_text = "klasyfikacje: " +
        join_classifications(stale_classifications) + '\n';
    }
    confirmed = window.confirm(
      'Zostaną usunięte:\n' + lips_text + cr_text + attr_text + clas_text +
        'Kontynuować?');
    if (!confirmed) {
      revert_selection($(this));
    }
  }
  if (confirmed || !(bad_lips.length > 0 || cr_row_elems.length > 0 ||
        stale_attrs.length > 0 || stale_classifications.length > 0)) {
    confirm_selection($(this));
    var result = $.ajax({ // znowu brzydko...
      type: 'get',
      url: $dj.ajax_get_ics,
      data: {pos_id: pos},
      async: false
    });
    var ics = $.parseJSON(result.responseText).ics;
    var ic_symbols = $.map(ics, function(a) { return a[1]; });
    var reload_preview = false;
    lip_row_elems.each(function() {
      var select = $(this).find('select.inflection-characteristic');
      var ic_symbol = select.find(':selected').text();
      var index;
      // chyba trochę przekombinowane...
      if (ic_symbols.indexOf(ic_symbol) !== -1) {
        select.empty();
        $.each(ics, function(i, a) {
          var option = new Option(a[1], a[0]);
          if (a[1] === ic_symbol) {
            index = i;
          }
          select.prop('options').add(option);
        });
        select[0].selectedIndex = index;
      } else {
        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;
      }
    });
    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: "Zapisanie domyślnego słownika"
  });
}

function make_new_lexeme() {
  "use strict";
  // stworzyć ajaxem nowy leksem i go po prostu otworzyć...
  $.ajaxJSON({
    method: 'post',
    url: $dj.ajax_create_lexeme,
    data: {vocab_id: $dj.default_owner},
    description: "Utworzenie leksemu",
    callback: function(data) {
      load_content(data.id, true);
    }
  });
}

function show_homonym_count() {
  "use strict";
  var entry = get_entry();
  $.ajaxJSON({
    method: 'get',
    url: $dj.ajax_homonym_count,
    data: {entry: entry, lexeme_id: lexeme_id()},
    descripton: "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(lexemes, hom_field) {
  "use strict";
  var table = $('#homonym-list').find('tbody');
  table.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);
    item.append($('<td/>').text(data.homonym_number));
    item.append($('<td/>').text(data.lip_data.inflection_characteristics));
    item.append($('<td/>').text(data.lip_data.patterns));
    item.click(function() {
      hom_field.val($(this).children().first().text());
      $("#choose-homonym-dialog").dialog('close');
    });
    table.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: "Sprawdzenie homonimów",
    callback: function(data) {
      var lexemes = data.lexemes;
      if (lexemes.length === 1)
        $t.find('.homonym-number').val(lexemes[0].homonym_number);
      else if (lexemes.length > 1) {
        homonym_choice(lexemes, $t.find('.homonym-number'));
      } else { // nie ma żadnego
        window.alert('Brak pasujących leksemów.');
        $t.find('.entry').val('');
        $t.find('.homonym-number').val('');
      }
    }
  });
};

// akcje grupowe

var filter_row_counter = 1; // dla niepowtarzalności idów
function new_action_row_html() {
  "use strict";
  var new_row_html = $.ajax({
    type: 'get',
    url: $dj.ajax_new_action_row,
    async: false
  }).responseText.replace(/NUM/g, filter_row_counter);
  filter_row_counter++;
  return new_row_html;
}

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));
    }
  });
};

function new_action_row() {
  "use strict";
  var row_html = new_action_row_html();
  var action_tr = $(row_html);
  $('#action-list').append(action_tr);
  action_tr.find('.field-choice').change();
}

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 filters = jqgrid.grid.jqGrid('getGridParam', 'postData').filters;
  var $t = $(this);
  $.ajaxJSON({
    method: 'post',
    url: $dj.ajax_execute_actions,
    data: {filters: filters, actions: actions},
    callback: function() {
      $t.dialog("close");
      jqgrid.grid.jqGrid('getGridParam', 'postData').force_reload = true;
      jqgrid.grid.trigger('reloadGrid');
    }
  });
};