managesieve.js 37.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
/**
 * (Manage)Sieve Filters plugin
 *
 * @licstart  The following is the entire license notice for the
 * JavaScript code in this file.
 *
 * Copyright (c) The Roundcube Dev Team
 *
 * The JavaScript code in this page is free software: you can redistribute it
 * and/or modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation, either version 3 of
 * the License, or (at your option) any later version.
 *
 * @licend  The above is the entire license notice
 * for the JavaScript code in this file.
 */

if (window.rcmail) {
  rcmail.addEventListener('init', function(evt) {
    // add managesieve-create command to message_commands array,
    // so it's state will be updated on message selection/unselection
    if (rcmail.env.task == 'mail') {
      if (rcmail.env.action != 'show')
        rcmail.env.message_commands.push('managesieve-create');
      else
        rcmail.enable_command('managesieve-create', true);
    }

    if (rcmail.env.task == 'mail' || rcmail.env.action.startsWith('plugin.managesieve')) {
      // Create layer for form tips
      if (!rcmail.env.framed) {
        rcmail.env.ms_tip_layer = $('<div id="managesieve-tip" class="popupmenu"></div>');
        rcmail.env.ms_tip_layer.appendTo(document.body);
      }
    }

    // register commands
    rcmail.register_command('plugin.managesieve-save', function() { rcmail.managesieve_save() });
    rcmail.register_command('plugin.managesieve-act', function() { rcmail.managesieve_act() });
    rcmail.register_command('plugin.managesieve-add', function() { rcmail.managesieve_add() });
    rcmail.register_command('plugin.managesieve-del', function() { rcmail.managesieve_del() });
    rcmail.register_command('plugin.managesieve-move', function() { rcmail.managesieve_move() });
    rcmail.register_command('plugin.managesieve-setadd', function() { rcmail.managesieve_setadd() });
    rcmail.register_command('plugin.managesieve-setdel', function() { rcmail.managesieve_setdel() });
    rcmail.register_command('plugin.managesieve-setact', function() { rcmail.managesieve_setact() });
    rcmail.register_command('plugin.managesieve-setget', function() { rcmail.managesieve_setget() });
    rcmail.register_command('plugin.managesieve-seteditraw', function() { rcmail.managesieve_seteditraw() });

    if (rcmail.env.action.startsWith('plugin.managesieve')) {
      if (rcmail.gui_objects.sieveform) {
        rcmail.enable_command('plugin.managesieve-save', true);
        sieve_form_init();
      }
      else if (rcmail.gui_objects.sievesetrawform) {
        rcmail.enable_command('plugin.managesieve-save', true);
        sieve_raw_editor_init();
      }
      else {
        rcmail.enable_command('plugin.managesieve-add', !rcmail.env.sieveconnerror && $.inArray('new_filter', rcmail.env.managesieve_disabled_actions) == -1);
        rcmail.enable_command('plugin.managesieve-setadd', !rcmail.env.sieveconnerror && $.inArray('new_set', rcmail.env.managesieve_disabled_actions) == -1);
      }

      var setcnt, set = rcmail.env.currentset;

      if (rcmail.gui_objects.filterslist) {
        rcmail.filters_list = new rcube_list_widget(rcmail.gui_objects.filterslist,
          {multiselect:false, draggable:true, keyboard:true});

        rcmail.filters_list
          .addEventListener('select', function(o) { rcmail.managesieve_select(o); })
          .addEventListener('keypress', function(o) { rcmail.list_keypress(o, {del: 'plugin.managesieve-del'}); })
          .addEventListener('dragstart', function(o) { rcmail.managesieve_dragstart(o); })
          .addEventListener('dragend', function(o) { rcmail.managesieve_dragend(o); })
          .addEventListener('initrow', function(row) {
            row.obj.onmouseover = function() { rcmail.managesieve_focus_filter(row); };
            row.obj.onmouseout = function() { rcmail.managesieve_unfocus_filter(row); };
          })
          .init();
      }

      if (rcmail.gui_objects.filtersetslist) {
        rcmail.filtersets_list = new rcube_list_widget(rcmail.gui_objects.filtersetslist,
          {multiselect:false, draggable:false, keyboard:true});

        rcmail.filtersets_list.init().focus();

        if (set != null) {
          $('#filterset-name').text(set);
          set = rcmail.managesieve_setid(set);
          rcmail.filtersets_list.select(set);
        }

        // attach select event after initial record was selected
        rcmail.filtersets_list.addEventListener('select', function(e) { rcmail.managesieve_setselect(e); });

        setcnt = rcmail.filtersets_list.rowcount;
        rcmail.enable_command('plugin.managesieve-set', true);
        rcmail.enable_command('plugin.managesieve-setact', setcnt > 0 && $.inArray('enable_disable_set', rcmail.env.managesieve_disabled_actions) == -1);
        rcmail.enable_command('plugin.managesieve-setget', setcnt > 0 && $.inArray('download_set', rcmail.env.managesieve_disabled_actions) == -1);
        rcmail.enable_command('plugin.managesieve-setdel', setcnt > 1 && $.inArray('delete_set', rcmail.env.managesieve_disabled_actions) == -1);
        rcmail.enable_command('plugin.managesieve-seteditraw', setcnt > 0 && rcmail.env.raw_sieve_editor);

        // Fix dragging filters over sets list
        $('tr', rcmail.gui_objects.filtersetslist).each(function (i, e) { rcmail.managesieve_fixdragend(e); });
      }
    }
  });
};

/*********************************************************/
/*********       Managesieve UI methods          *********/
/*********************************************************/

rcube_webmail.prototype.managesieve_add = function()
{
  this.load_managesieveframe('_nav=hide', true);
};

rcube_webmail.prototype.managesieve_del = function()
{
  var id = this.filters_list.get_single_selection();
  this.confirm_dialog(this.get_label('managesieve.filterdeleteconfirm'), 'delete', function(e, ref) {
      var post = '_act=delete&_fid=' + ref.filters_list.rows[id].uid,
        lock = ref.set_busy(true, 'loading');

      ref.http_post('plugin.managesieve-action', post, lock);
    });
};

rcube_webmail.prototype.managesieve_act = function()
{
  var id = this.filters_list.get_single_selection(),
    lock = this.set_busy(true, 'loading');

  this.http_post('plugin.managesieve-action',
    '_act=act&_fid='+this.filters_list.rows[id].uid, lock);
};

// Filter selection
rcube_webmail.prototype.managesieve_select = function(list)
{
  var id = list.get_single_selection();

  if (id != null) {
    id = list.rows[id].uid;
    this.load_managesieveframe('_fid=' + id);
  }

  var has_id = typeof(id) != 'undefined' && id != null;

  this.enable_command('plugin.managesieve-act', has_id);
  this.enable_command('plugin.managesieve-del', has_id && $.inArray('delete_filter', rcmail.env.managesieve_disabled_actions) == -1);
};

// Set selection
rcube_webmail.prototype.managesieve_setselect = function(list)
{
  this.enable_command('plugin.managesieve-setdel', list.rowcount > 1 && $.inArray('delete_set', rcmail.env.managesieve_disabled_actions) == -1);
  this.enable_command('plugin.managesieve-setact', list.rowcount > 0 && $.inArray('enable_disable_set', rcmail.env.managesieve_disabled_actions) == -1);
  this.enable_command('plugin.managesieve-setget', list.rowcount > 0 && $.inArray('delete_set', rcmail.env.managesieve_disabled_actions) == -1);
  this.enable_command('plugin.managesieve-seteditraw', list.rowcount > 0 && this.env.raw_sieve_editor);

 if (rcmail.env.contextmenu_opening)
   return;

  this.show_contentframe(false);
  this.filters_list.clear(true);

  var id = list.get_single_selection();
  if (id != null) {
    this.managesieve_list(this.env.filtersets[id]);
    $('#filterset-name').text(this.env.filtersets[id]);
  }
};

rcube_webmail.prototype.managesieve_rowid = function(id)
{
  var i, rows = this.filters_list.rows;

  for (i in rows)
    if (rows[i] != null && rows[i].uid == id)
      return i;
};

// Returns set's identifier
rcube_webmail.prototype.managesieve_setid = function(name)
{
  for (var i in this.env.filtersets)
    if (this.env.filtersets[i] == name)
      return i;
};

// Filters listing request
rcube_webmail.prototype.managesieve_list = function(script)
{
  var lock = this.set_busy(true, 'loading');

  this.http_post('plugin.managesieve-action', '_act=list&_set='+urlencode(script), lock);
};

// Script download request
rcube_webmail.prototype.managesieve_setget = function()
{
  var id = this.filtersets_list.get_single_selection(),
    script = this.env.filtersets[id];

  this.goto_url('plugin.managesieve-action', {_act: 'setget', _set: script}, false, true);
};

// Set activate/deactivate request
rcube_webmail.prototype.managesieve_setact = function()
{
  var id = this.filtersets_list.get_single_selection(),
   lock = this.set_busy(true, 'loading'),
    script = this.env.filtersets[id],
    action = $('#rcmrow'+id).hasClass('disabled') ? 'setact' : 'deact';

  this.http_post('plugin.managesieve-action', '_act='+action+'&_set='+urlencode(script), lock);
};

// Set delete request
rcube_webmail.prototype.managesieve_setdel = function()
{
  var id = this.filtersets_list.get_single_selection();
  this.confirm_dialog(this.get_label('managesieve.setdeleteconfirm'), 'delete', function(e, ref) {
      var script = ref.env.filtersets[id],
        lock = ref.set_busy(true, 'loading');

      ref.http_post('plugin.managesieve-action', '_act=setdel&_set=' + urlencode(script), lock);
    });
};

// Set edit raw request
rcube_webmail.prototype.managesieve_seteditraw = function()
{
  var id = this.filtersets_list.get_single_selection(),
    script = this.env.filtersets[id];

  this.load_managesieveframe('_nav=hide&_seteditraw=1&_set=' + urlencode(script), true);
};

// Set add request
rcube_webmail.prototype.managesieve_setadd = function()
{
  this.load_managesieveframe('_nav=hide&_newset=1', true);
};

rcube_webmail.prototype.managesieve_updatelist = function(action, o)
{
  this.set_busy(true);

  switch (action) {
    // Delete filter row
    case 'del':
      var id = o.id, list = this.filters_list;

      list.remove_row(this.managesieve_rowid(o.id));
      this.show_contentframe(false);
      this.reset_filters_list();

      // filter identifiers changed, fix the list
      $('tr', this.filters_list.list).each(function() {
        // remove hidden (deleted) rows
        if (this.style.display == 'none') {
          $(this).detach();
          return;
        }

        var rowid = this.id.substr(6);

        // remove all attached events
        $(this).off();

        // update row id
        if (rowid > id) {
          this.uid = String(rowid - 1);
          $(this).attr('id', 'rcmrow' + this.uid);
        }
      });
      list.init();

      break;

    // Update filter row
    case 'update':
      var i, row = $('#rcmrow'+this.managesieve_rowid(o.id));

      if (o.name)
        $('td', row).text(o.name);
      if (o.disabled)
        row.addClass('disabled');
      else
        row.removeClass('disabled');

      $('#fenabled', $('iframe').contents()).prop('checked', !o.disabled);

      break;

    // Add filter row to the list
    case 'add':
      var list = this.filters_list,
        row = $('<tr><td class="name"></td></tr>');

      $('td', row).text(o.name);
      row.attr('id', 'rcmrow'+o.id);
      if (o.disabled)
        row.addClass('disabled');

      list.insert_row(row.get(0));
      list.highlight_row(o.id);

      this.enable_command('plugin.managesieve-del', $.inArray('delete_rule', rcmail.env.managesieve_disabled_actions) == -1);
      this.enable_command('plugin.managesieve-act', true);

      break;

    // Filling rules list
    case 'list':
      var i, tr, td, el, list = this.filters_list;

      if (o.clear)
        list.clear();

      for (i in o.list) {
        el = o.list[i];
        tr = document.createElement('TR');
        td = document.createElement('TD');

        $(td).text(el.name);
        td.className = 'name';
        tr.id = 'rcmrow' + el.id;
        if (el['class'])
            tr.className = el['class'];
        tr.appendChild(td);

        list.insert_row(tr);
      }

      if (o.set)
        list.highlight_row(o.set);
      else
        this.enable_command('plugin.managesieve-del', 'plugin.managesieve-act', false);

      break;

    // Activate/Deactivate the set
    case 'setact':
      var id = this.managesieve_setid(o.name), row = $('#rcmrow' + id);
      if (o.active) {
        if (o.all)
          $('tr', this.gui_objects.filtersetslist).addClass('disabled');
        row.removeClass('disabled');
      }
      else
        row.addClass('disabled');

      break;

    // Delete set row
    case 'setdel':
      var id = this.managesieve_setid(o.name);

      this.filters_list.clear();
      this.show_contentframe(false);
      this.enable_command('plugin.managesieve-setdel', 'plugin.managesieve-setact',
        'plugin.managesieve-setget', 'plugin.managesieve-seteditraw', false);

      this.filtersets_list.remove_row(id, true);
      delete this.env.filtersets[id];
      break;

    // Create set row
    case 'setadd':
      var id = 'S' + new Date().getTime(),
        list = this.filtersets_list,
        row = $('<tr class="disabled"><td class="name"></td></tr>');

      $('td', row).text(o.name);
      row.attr('id', 'rcmrow'+id);

      this.env.filtersets[id] = o.name;
      list.insert_row(row.get(0));

      // move row into its position on the list
      if (o.index != list.rowcount-1) {
        row.detach();
        var elem = $('tr:visible', list.list).get(o.index);
        row.insertBefore(elem);
      }

      list.select(id);

      // Fix dragging filters over sets list
      this.managesieve_fixdragend(row);

      break;

    case 'refresh':
      this.reset_filters_list(true);
      break;
  }

  this.set_busy(false);
};

// Resets filters list state
rcube_webmail.prototype.reset_filters_list = function(reload)
{
  this.filters_list.clear_selection();
  this.enable_command('plugin.managesieve-act', 'plugin.managesieve-del', false);

  if (reload) {
    var id = this.filtersets_list.get_single_selection();

    this.filters_list.clear(true);
    this.managesieve_list(this.env.filtersets[id]);
  }
};

// load filter frame
rcube_webmail.prototype.load_managesieveframe = function(add_url, reset)
{
  if (reset)
    this.reset_filters_list();

  var target = this.get_frame_window(this.env.contentframe),
    url = this.url('plugin.managesieve-action', '_framed=1' + (add_url ? ('&' + add_url) : ''));

  if (target) {
    this.location_href(url, target, true);
  }
};

// load filter frame
rcube_webmail.prototype.managesieve_dragstart = function(list)
{
  var id = this.filters_list.get_single_selection();

  this.drag_active = true;
  this.drag_filter = id;
};

rcube_webmail.prototype.managesieve_dragend = function(e)
{
  if (this.drag_active) {
    if (this.drag_filter_target) {
      var lock = this.set_busy(true, 'loading');

      this.show_contentframe(false);
      this.http_post('plugin.managesieve-action', '_act=move&_fid='+this.drag_filter
        +'&_to='+this.drag_filter_target, lock);
    }
    this.drag_active = false;
  }
};

// Fixes filters dragging over sets list
// @TODO: to be removed after implementing copying filters
rcube_webmail.prototype.managesieve_fixdragend = function(elem)
{
  var p = this;
  $(elem).on('mouseup' + ((bw.iphone || bw.ipad) ? ' touchend' : ''), function(e) {
    if (p.drag_active)
      p.filters_list.drag_mouse_up(e);
  });
};

rcube_webmail.prototype.managesieve_focus_filter = function(row)
{
  var id = row.id.replace(/^rcmrow/, '');
  if (this.drag_active && id != this.drag_filter) {
    this.drag_filter_target = id;
    $(row.obj).addClass(id < this.drag_filter ? 'filtermoveup' : 'filtermovedown');
  }
};

rcube_webmail.prototype.managesieve_unfocus_filter = function(row)
{
  if (this.drag_active) {
    $(row.obj).removeClass('filtermoveup filtermovedown');
    this.drag_filter_target = null;
  }
};

/*********************************************************/
/*********          Filter Form methods          *********/
/*********************************************************/

// Form submission
rcube_webmail.prototype.managesieve_save = function()
{
  if (this.env.action == 'plugin.managesieve-vacation') {
    var data = $(this.gui_objects.sieveform).serialize();
    this.http_post('plugin.managesieve-vacation', data, this.display_message(this.get_label('managesieve.vacation.saving'), 'loading'));
    return;
  }

  if (this.env.action == 'plugin.managesieve-forward') {
    var data = $(this.gui_objects.sieveform).serialize();
    this.http_post('plugin.managesieve-forward', data, this.display_message(this.get_label('managesieve.forward.saving'), 'loading'));
    return;
  }

  if (this.gui_objects.sieveform) {
    if (parent.rcmail && parent.rcmail.filters_list && this.gui_objects.sieveform.name != 'filtersetform') {
      var id = parent.rcmail.filters_list.get_single_selection();
      if (id != null)
        this.gui_objects.sieveform.elements['_fid'].value = parent.rcmail.filters_list.rows[id].uid;
    }
    this.gui_objects.sieveform.submit();
  }
  else if (this.gui_objects.sievesetrawform) {
    this.gui_objects.sievesetrawform.submit();
  }
};

// Operations on filters form
rcube_webmail.prototype.managesieve_ruleadd = function(id)
{
  this.http_post('plugin.managesieve-action', '_act=ruleadd&_rid='+id);
};

rcube_webmail.prototype.managesieve_rulefill = function(content, id, after)
{
  if (content != '') {
    // create new element
    var div = $('#rules')[0],
      row = $('<div>').attr({'class': 'rulerow', id: 'rulerow'+id})
        .html(content);

    this.managesieve_insertrow(div, row, after);

    // initialize smart list inputs
    $('textarea[data-type="list"]', row).each(function() {
      smart_field_init(this);
    });

    this.managesieve_formbuttons(div);
  }
};

rcube_webmail.prototype.managesieve_ruledel = function(id)
{
  if ($('#ruledel'+id).hasClass('disabled'))
    return;

  this.confirm_dialog(this.get_label('managesieve.ruledeleteconfirm'), 'delete', function(e, ref) {
      var row = document.getElementById('rulerow'+id);
      row.parentNode.removeChild(row);
      ref.managesieve_formbuttons(document.getElementById('rules'));
    });
};

rcube_webmail.prototype.managesieve_actionadd = function(id)
{
  this.http_post('plugin.managesieve-action', '_act=actionadd&_aid='+id);
};

rcube_webmail.prototype.managesieve_actionfill = function(content, id, after)
{
  if (content != '') {
    var div = $('#actions')[0],
      row = $('<div>').attr({'class': 'actionrow', id: 'actionrow'+id})
        .html(content);

    this.managesieve_insertrow(div, row, after);

    // initialize smart list inputs
    $('textarea[data-type="list"]', row).each(function() {
      smart_field_init(this);
    });

    this.managesieve_formbuttons(div);
  }
};

rcube_webmail.prototype.managesieve_actiondel = function(id)
{
  if ($('#actiondel'+id).hasClass('disabled'))
    return;

  this.confirm_dialog(this.get_label('managesieve.actiondeleteconfirm'), 'delete', function(e, ref) {
      var row = document.getElementById('actionrow'+id);
      row.parentNode.removeChild(row);
      ref.managesieve_formbuttons(document.getElementById('actions'));
    });
};

// insert rule/action row in specified place on the list
rcube_webmail.prototype.managesieve_insertrow = function(div, row, after)
{
  var node = $('#' + ($(div).attr('id') == 'rules' ? 'rulerow' : 'actionrow')  + after)[0];

  if (node)
    $(row).insertAfter(node);
  else
    $(div).append(row);

  this.triggerEvent('managesieve.insertrow', {obj: row});
};

// update Delete buttons status
rcube_webmail.prototype.managesieve_formbuttons = function(div)
{
  var buttons = $('a.delete', div);

  buttons.removeClass('disabled');
  if (buttons.length == 1)
    buttons.addClass('disabled');
};

// update vacation addresses field with user identities
rcube_webmail.prototype.managesieve_vacation_addresses = function(id)
{
  var lock = this.set_busy(true, 'loading');
  this.http_post('plugin.managesieve-action', {_act: 'addresses', _aid: id}, lock);
};

// update vacation addresses field with user identities
rcube_webmail.prototype.managesieve_vacation_addresses_update = function(id, addresses)
{
  var field = $('#vacation_addresses,#action_addresses' + (id || ''));
  smart_field_reset(field.get(0), addresses);
};

function rule_header_select(id)
{
  var is_header,
    obj = document.getElementById('header' + id),
    size = document.getElementById('rule_size' + id),
    spamtest = document.getElementById('rule_spamtest' + id),
    msg = document.getElementById('rule_message' + id),
    op = document.getElementById('rule_op' + id),
    header = document.getElementById('custom_header' + id + '_list'),
    custstr = document.getElementById('custom_var' + id + '_list'),
    mod = document.getElementById('rule_mod' + id),
    trans = document.getElementById('rule_trans' + id),
    comp = document.getElementById('rule_comp' + id),
    mime = document.getElementById('rule_mime' + id),
    mime_part = document.getElementById('rule_mime_part' + id),
    datepart = document.getElementById('rule_date_part' + id),
    dateheader = document.getElementById('rule_date_header_div' + id),
    rule = $('#rule_op' + id),
    h = obj.value,
    set = [op, header, custstr, mod, trans, comp, size, mime, mime_part];

  if (h == 'size') {
    if (msg) set.push(msg);
    $.each(set, function() { if (this != window) this.style.display = 'none'; });
    spamtest.style.display = 'none';
    size.style.display = '';
  }
  else if (h == 'spamtest') {
    if (msg) set.push(msg);
    $.each(set, function() { if (this != window) this.style.display = 'none'; });
    spamtest.style.display = '';
    size.style.display = 'none';
  }
  else if (h == 'message' && msg) {
    $.each(set, function() { if (this != window)  this.style.display = 'none'; });
    msg.style.display = '';
  }
  else {
    is_header = h != 'body' && h != 'currentdate' && h != 'date' && h != 'string';
    header.style.display = h != '...' ? 'none' : '';
    custstr.style.display = h != 'string' ? 'none' : '';
    size.style.display = 'none';
    spamtest.style.display = 'none';
    op.style.display = '';
    comp.style.display = '';
    mod.style.display = is_header ? '' : 'none';
    trans.style.display = h == 'body' ? '' : 'none';
    if (mime)
      mime.style.display =  is_header ? '' : 'none';
    if (mime_part)
      mime_part.style.display = is_header ? '' : 'none';
    if (msg)
      msg.style.display = h == 'message' ? '' : 'none';
  }

  if (datepart)
    datepart.style.display = h == 'currentdate' || h == 'date' ? 'inline' : 'none';
  if (dateheader)
    dateheader.style.display = h == 'date' ? '' : 'none';

  $('[value="exists"],[value="notexists"]', rule).prop('disabled', h == 'string');
  if (!rule.val())
    rule.val('contains');

  rule_op_select(op, id, h);
  rule_mod_select(id, h, !is_header);
  rule_mime_select(id);
  rule_spamtest_select(id);

  obj.style.width = h == '...' ? '40px' : '';
};

function rule_op_select(obj, id, header)
{
  var target = document.getElementById('rule_target' + id + '_list');

  if (!header)
    header = document.getElementById('header' + id).value;

  target.style.display = obj.value.match(/^(exists|notexists)$/) || header.match(/^(size|spamtest|message)$/) ? 'none' : '';
};

function rule_trans_select(id)
{
  var obj = document.getElementById('rule_trans_op' + id),
    target = document.getElementById('rule_trans_type' + id);

  target.style.display = obj.value != 'content' ? 'none' : 'inline';
};

function rule_mod_select(id, header, reset)
{
  var obj = document.getElementById('rule_mod_op' + id),
    target = document.getElementById('rule_mod_type' + id),
    duplicate = document.getElementById('rule_duplicate_div' + id),
    index = document.getElementById('rule_index_div' + id);

  if (reset)
    obj.value = '';

  if (!header)
    header = document.getElementById('header' + id).value;

  target.style.display = obj.value != 'address' && obj.value != 'envelope' ? 'none' : '';

  if (index)
    index.style.display = !header.match(/^(body|currentdate|size|spamtest|message|string)$/) && obj.value != 'envelope'  ? '' : 'none';

  if (duplicate)
    duplicate.style.display = header == 'message' ? '' : 'none';
};

function rule_spamtest_select(id)
{
  var obj = document.getElementById('rule_spamtest_op' + id),
    target = document.getElementById('rule_spamtest_target' + id);

  target.style.display = obj.value ? '' : 'none';
  $(obj)[obj.value ? 'removeClass' : 'addClass']('rounded-right');
};

function rule_join_radio(value)
{
  $('#rules').css('display', value == 'any' ? 'none' : 'block');
};

function rule_adv_switch(id, elem)
{
  var elem = $(elem), enabled = elem.hasClass('hide'), adv = $('#rule_advanced'+id);

  if (enabled) {
    adv.get(0).style.display = 'none';
    elem.removeClass('hide').addClass('show');
  }
  else {
    adv.get(0).style.display = '';
    elem.removeClass('show').addClass('hide');
  }
};

function rule_mime_select(id)
{
  var elem = $('#rule_mime_type' + id),
    param_elem = $('#rule_mime_param' + id + '_list');

  if (param_elem.length)
    param_elem[0].style.display = elem.val() == 'param' ? '' : 'none';
};

function action_type_select(id)
{
  var obj = document.getElementById('action_type' + id),
    v = obj.value, enabled = {},
    elems = {
      mailbox: document.getElementById('action_mailbox' + id),
      target: document.getElementById('redirect_target' + id),
      target_area: document.getElementById('action_target_area' + id),
      flags: document.getElementById('action_flags' + id),
      vacation: document.getElementById('action_vacation' + id),
      forward: document.getElementById('action_forward' + id),
      set: document.getElementById('action_set' + id),
      notify: document.getElementById('action_notify' + id),
      addheader: document.getElementById('action_addheader' + id),
      deleteheader: document.getElementById('action_deleteheader' + id)
    };

  if (v == 'fileinto' || v == 'fileinto_copy') {
    enabled.mailbox = 1;
  }
  else if (v == 'redirect' || v == 'redirect_copy') {
    enabled.target = 1;
  }
  else if (v.match(/^reject|ereject$/)) {
    enabled.target_area = 1;
  }
  else if (v.match(/^(add|set|remove)flag$/)) {
    enabled.flags = 1;
  }
  else if (v.match(/^(vacation|forward|set|notify|addheader|deleteheader)$/)) {
    enabled[v] = 1;
  }

  for (var x in elems) {
    if (elems[x])
      elems[x].style.display = !enabled[x] ? 'none' : '';
  }
};

function vacation_action_select()
{
  var selected = $('#vacation_action').val();

  $('#action_target_span')[selected == 'discard' || selected == 'keep' ? 'hide' : 'show']();
};

// Initializes smart list input
function smart_field_init(field)
{
  if (window.UI && UI.smart_field_init)
    return UI.smart_field_init(field);

  var id = field.id + '_list',
    area = $('<span class="listarea"></span>'),
    list = field.value ? field.value.split("\n") : [''];

  if ($('#'+id).length)
    return;

  // add input rows
  $.each(list, function(i, v) {
    area.append(smart_field_row(v, i, field));
  });

  area.attr('id', id);
  field = $(field);

  if (field.attr('disabled'))
    area.hide();
  // disable the original field anyway, we don't want it in POST
  else
    field.prop('disabled', true);

  if (field.data('hidden'))
    area.hide();

  field.after(area);

  if (field.hasClass('error')) {
    area.addClass('error');
    rcmail.managesieve_tip_register([[id, field.data('tip-class'), field.data('tip-msg')]]);
  }
};

function smart_field_row(value, idx, field)
{
  // build row element content
  var input, content = '<span class="listelement">'
      + '<span class="reset"></span><input type="text"></span>',
    elem = $(content),
    attrs = {
      value: value,
      name: field.name + '[]',
      size: $(field).data('size'),
      title: field.title,
      placeholder: $(field).attr('placeholder')
    };

  input = elem.find('input').attr(attrs).keydown(function(e) {
    var input = $(this);

    // element creation event (on Enter)
    if (e.which == 13) {
      var elem = smart_field_row('', (new Date()).getTime(), field);

      input.parent().after(elem);
      $('input', elem).focus();
    }
    // backspace or delete: remove input, focus previous one
    else if ((e.which == 8 || e.which == 46) && input.val() == '') {

      var parent = input.parent(), siblings = parent.parent().children();

      if (siblings.length > 1) {
        if (parent.prev().length)
          parent.prev().children('input').focus();
        else
          parent.next().children('input').focus();

        parent.remove();
        return false;
      }
    }
  });

  // element deletion event
  $('span[class="reset"]', elem).click(function() {
    var span = $(this.parentNode);

    if (span.parent().children().length > 1)
      span.remove();
    else
      $('input', span).val('').focus();
  });

  return elem;
}

// Reset and fill the smart list input with new data
function smart_field_reset(field, data)
{
  if (window.UI && UI.smart_field_reset)
    return UI.smart_field_reset(field, data);

  var id = field.id + '_list',
    list = data.length ? data : [''];
    area = $('#' + id);

  area.empty();

  // add input rows
  $.each(list, function(i, v) {
    area.append(smart_field_row(v, i, field));
  });
}

// Register onmouse(leave/enter) events for tips on specified form element
rcube_webmail.prototype.managesieve_tip_register = function(tips)
{
  if (window.UI && UI.form_errors)
    return UI.form_errors(tips);

  var n, framed = parent.rcmail,
    tip = framed ? parent.rcmail.env.ms_tip_layer : rcmail.env.ms_tip_layer;

  for (n in tips) {
    $('#'+tips[n][0])
      .data('tip-class', tips[n][1])
      .data('tip-msg', tips[n][2])
      .mouseleave(function(e) { tip.hide(); })
      .mouseenter(function(e) {
        var elem = $(this),
          offset = elem.offset(),
          left = offset.left,
          top = offset.top - 12,
          minwidth = elem.width(),
          span = $('<span>').addClass(elem.data('tip-class')).text(elem.data('tip-msg'));

        if (framed) {
          offset = $((rcmail.env.task == 'mail'  ? '#sievefilterform > iframe' : '#filter-box'), parent.document).offset();
          top  += offset.top;
          left += offset.left;
        }

        tip.html('').append(span);
        top -= tip.height();

        tip.css({left: left, top: top, minWidth: (minwidth-2) + 'px'}).show();
      });
  }
};

// format time string
function sieve_formattime(hour, minutes)
{
  var i, c, h, time = '', format = rcmail.env.time_format || 'H:i';

  for (i=0; i<format.length; i++) {
    c = format.charAt(i);
    switch (c) {
      case 'a': time += hour >= 12 ? 'pm' : 'am'; break;
      case 'A': time += hour >= 12 ? 'PM' : 'AM'; break;
      case 'g':
      case 'h':
        h = hour == 0 ? 12 : hour > 12 ? hour - 12 : hour;
        time += (c == 'h' && hour < 10 ? '0' : '') + hour;
        break;
      case 'G': time += hour; break;
      case 'H': time += (hour < 10 ? '0' : '') + hour; break;
      case 'i': time += (minutes < 10 ? '0' : '') + minutes; break;
      case 's': time += '00';
      default: time += c;
    }
  }

  return time;
}

function sieve_form_init()
{
  var form = rcmail.gui_objects.sieveform;

  // resize dialog window
  if (rcmail.env.action == 'plugin.managesieve' && rcmail.env.task == 'mail') {
    parent.rcmail.managesieve_dialog_resize(form);
  }

  $('input[type="text"]', form).first().focus();

  // initialize smart list inputs
  $('textarea[data-type="list"]', form).each(function() {
    smart_field_init(this);
  });

  // initialize rules form(s)
  $('[name^="_header"]', form).each(function() {
    if (/([0-9]+)$/.test(this.id)) {
      rule_header_select(RegExp.$1);
    }
  });

  // enable date pickers on date fields
  if ($.datepicker && rcmail.env.date_format) {
    $.datepicker.setDefaults({
      dateFormat: rcmail.env.date_format,
      changeMonth: true,
      showOtherMonths: true,
      selectOtherMonths: true,
      onSelect: function(dateText) { $(this).focus().val(dateText); }
    });
    $('input.datepicker').datepicker();
  }

  // configure drop-down menu on time input fields based on jquery UI autocomplete
  $('#vacation_timefrom, #vacation_timeto')
    .attr('autocomplete', "off")
    .autocomplete({
      delay: 100,
      minLength: 1,
      source: function(p, callback) {
        var h, result = [];
        for (h = 0; h < 24; h++)
          result.push(sieve_formattime(h, 0));
        result.push(sieve_formattime(23, 59));

        return callback(result);
      },
      open: function(event, ui) {
        // scroll to current time
        var $this = $(this), val = $this.val(),
          widget = $this.autocomplete('widget').css('width', '10em'),
          menu = $this.data('ui-autocomplete').menu;

        if (val && val.length)
          widget.children().each(function() {
            var li = $(this);
            if (li.text().indexOf(val) == 0)
              menu._scrollIntoView(li);
          });
      },
      select: function(event, ui) {
        $(this).val(ui.item.value);
        return false;
      }
    })
    .click(function() {  // show drop-down upon clicks
      $(this).autocomplete('search', $(this).val() || ' ');
    })

  // display advanced controls when contain errors
  $('input.error').each(function() {
    if (String(this.id).match(/([0-9]+)$/)) {
      $('#ruleadv' + RegExp.$1 + '.show').click();
    }
  });
}

/*********************************************************/
/*********        RAW editor methods             *********/
/*********************************************************/

var cmeditor;

function cmCreateErrorElem(msg)
{
  var marker = document.createElement("div");
  marker.style.color = "#822";
  marker.innerHTML = "●";
  marker.title = msg;

  return marker;
}

function cmScrollToError()
{
  var line = $('.CodeMirror-lines .line-error'),
    scroll = $('.CodeMirror-scroll'),
    h = line.parent();

  scroll.scrollTop(line.offset().top - scroll.offset().top - Math.round(scroll.height()/2));
}

function sieve_raw_editor_init()
{
  var textArea = document.getElementById('rawfiltersettxt');
  if (textArea && !cmeditor) {
    cmeditor = CodeMirror.fromTextArea(textArea, {
      mode: 'sieve',
      lineNumbers: true,
      gutters: ["CodeMirror-linenumbers", "errorGutter"],
      styleActiveLine: true
    });

    // fetching errors from environment and setting the line background
    // and a gutter element with the error message accordingly
    $.each(rcmail.env.sieve_errors || [], function(i, err) {
      var lineNo = Number(err.line) - 1;
      cmeditor.addLineClass(lineNo, 'background', 'line-error');
      cmeditor.setGutterMarker(lineNo, 'errorGutter', cmCreateErrorElem(err.msg));
      if (!i) cmScrollToError();
    });
  }
}


/*********************************************************/
/*********           Mail UI methods             *********/
/*********************************************************/

rcube_webmail.prototype.managesieve_create = function(force)
{
  if (!force && this.env.action != 'show') {
    var uid = this.message_list.get_single_selection(),
      lock = this.set_busy(true, 'loading');

    this.http_post('plugin.managesieve-action', {_uid: uid}, lock);
    return;
  }

  if (!this.env.sieve_headers || !this.env.sieve_headers.length)
    return;

  var i, buttons = {},
    title = this.get_label('managesieve.newfilter'),
    dialog = $('<div id="sievefilterform" class="propform"></div>'),
    props = {minWidth: 600, minHeight: 250, height: 300};


  // build dialog window content
  dialog.append($('<fieldset>')
    .append($('<legend>').text(this.get_label('managesieve.usedata')))
    .append($('<ul class="proplist">'))
  );

  $.each(this.env.sieve_headers, function(i, v) {
    var attr = {type: 'checkbox', name: 'headers[]', id: 'sievehdr' + i, value: i,  checked: true},
      label = rcmail.env.sieve_headers[i][0] + ': ' + rcmail.env.sieve_headers[i][1];

    $('ul', dialog).append($('<li>')
      .append($('<input>').attr(attr))
      .append($('<label>').attr('for', 'sievehdr' + i).text(label))
    );
  });

  // [Next Step] button action
  buttons[this.get_label('managesieve.nextstep')] = function () {
    // check if there's at least one checkbox checked
    var hdrs = $('input[name="headers[]"]:checked', dialog);
    if (!hdrs.length) {
      rcmail.alert_dialog(rcmail.get_label('managesieve.nodata'));
      return;
    }

    // build frame URL
    var url = rcmail.get_task_url('mail');
    url = rcmail.add_url(url, '_action', 'plugin.managesieve');
    url = rcmail.add_url(url, '_framed', 1);

    hdrs.map(function() {
      var val = rcmail.env.sieve_headers[this.value];
      url = rcmail.add_url(url, 'r['+this.value+']', val[0]+':'+val[1]);
    });

    // load form in the iframe
    var buttons = {}, iframe = $('<iframe>').attr({src: url, frameborder: 0});

    // Change [Next Step] button with [Save] button
    buttons[rcmail.get_label('save')] = function() {
      var win = $('iframe', dialog).get(0).contentWindow;
      win.rcmail.managesieve_save();
    };
    buttons[rcmail.get_label('cancel')] = function() { $(this).dialog('destroy'); };

    dialog.dialog('destroy');

    rcmail.env.managesieve_dialog = dialog = rcmail.show_popup_dialog(
      iframe, title, buttons, $.extend(props, {button_classes: ['mainaction save', 'cancel']})
    );
  };

  buttons[this.get_label('cancel')] = function() { $(this).dialog('destroy'); };

  this.env.managesieve_dialog = dialog = this.show_popup_dialog(
    dialog, title, buttons, $.extend(props, {button_classes: ['mainaction next', 'cancel']})
  );
}

rcube_webmail.prototype.managesieve_dialog_close = function()
{
  this.env.managesieve_dialog.dialog('destroy');
}

rcube_webmail.prototype.managesieve_dialog_resize = function(o)
{
  var dialog = this.env.managesieve_dialog,
    win = $(window), form = $(o);
    width = $('fieldset', o).first().width(), // fieldset width is more appropriate here
    height = form.height(),
    w = win.width(), h = win.height();

  if (height < 100)
    return;

  dialog.dialog('option', { height: Math.min(h-20, height+120), width: Math.min(w-20, width+65) });
}