jqgrid.js 10.4 KB
/*global window, $, main_field, initialColModel, initialColNames,
  initial_sort_rules, ajax_get_page, ajax_find_id, grid_caption, load_content,
  */
var grid, sort_rules = window.sort_rules, colModel = window.colModel,
  colNames = window.colNames, jqgrid_filteroptions;
var timeoutHnd;
var changed;
var ctrl; // do pokazywania, ze laduje

function put_filter(filter) {
  "use strict";
  grid.jqGrid('getGridParam', 'postData').filters = filter;
  var filter_element = $('.searchFilter')[0],
    coord = $.jgrid.findPos(filter_element);
  grid.jqGrid('searchGrid', $.extend(jqgrid_filteroptions, {
    left: coord[0] - filter_element.offsetLeft,
    top: coord[1] - filter_element.offsetTop,
    recreateFilter: true,
    loadDefaults: true
  }));
}

function refresh_column_headers() {
  "use strict";
  var thd= $("thead:first", $('#scroll')[0].grid.hDiv).get(0);
  var rules = $.evalJSON(grid.jqGrid('getGridParam', 'postData').sort_rules);
  $("tr th span.s-ico",thd).hide();
  $("tr th span.ui-icon",thd).addClass('ui-state-disabled');
  $("text").remove('.sort_priority');
  for (var i = 0; i < rules.length; i++) {
    $("tr th[id='scroll_"+rules[i].field+"'] span.s-ico",thd).show();
    $("tr th[id='scroll_"+rules[i].field+"'] span.ui-icon-" + rules[i].order,thd).removeClass('ui-state-disabled');
    $('tr th div#jqgh_'+rules[i].field+"'", thd).append('<text class="sort_priority">'+(i+1)+'</text>');
  }
}

function sort_column(colName, index, order) {
  "use strict";
  var data = grid.jqGrid('getGridParam', 'postData');
  var sort_rules = [{field: colName, order: order}];
  if ($.isFunction(window.prepare_sort_rules)) {
    var old_sort_rules = $.evalJSON(data.sort_rules);
    window.prepare_sort_rules(sort_rules, old_sort_rules);
  }

  data.sort_rules = $.toJSON(sort_rules);
  grid.jqGrid('setGridParam', {setOnComplete: true});
  refresh_column_headers();
}

$(function() {
  "use strict";
  jqgrid_filteroptions = {
    multipleSearch: true,
    overlay: false,
    top: 300,
    left: 300,
    sopt: ['eq','ne','bw','bn','ew','en','cn','nc', 're', 'nr'],
    ops: [
      {"name": "eq", "description": "equal", "operator":"="},
      {"name": "ne", "description": "not equal", "operator":"<>"},
      {"name": "lt", "description": "less", "operator":"<"},
      {"name": "le", "description": "less or equal","operator":"<="},
      {"name": "gt", "description": "greater", "operator":">"},
      {"name": "ge", "description": "greater or equal", "operator":">="},
      {"name": "bw", "description": "begins with", "operator":"LIKE"},
      {"name": "bn", "description": "does not begin with", "operator":"NOT LIKE"},
      {"name": "in", "description": "in", "operator":"IN"},
      {"name": "ni", "description": "not in", "operator":"NOT IN"},
      {"name": "ew", "description": "ends with", "operator":"LIKE"},
      {"name": "en", "description": "does not end with", "operator":"NOT LIKE"},
      {"name": "cn", "description": "contains", "operator":"LIKE"},
      {"name": "nc", "description": "does not contain", "operator":"NOT LIKE"},
      {"name": "nu", "description": "is null", "operator":"IS NULL"},
      {"name": "nn", "description": "is not null", "operator":"IS NOT NULL"},
      {"name": "re", "description": "matches regex", "operator":"REGEXP"},
      {"name": "nr", "description": "does not match regex", "operator":"NOT REGEXP"},
      {"name": "se", "description": "equal for sure", "operator":"="},
      {"name": "sd", "description": "different for sure", "operator":"<>"},
      {"name": "me", "description": "maybe equal", "operator":"="},
      {"name": "md", "description": "maybe different", "operator":"<>"}
    ],
    beforeShowSearch: function(f) {
      f.closest('.ui-jqdialog').appendTo('body')
       .dialog('option', 'position', 'center');
      return true;
    },
    onReset: function(f) {
      var init = {
        "groupOp": "AND",
        rules: [{"field": main_field, "op": "eq", "data": ""}]
      };
      put_filter(init);
    },
    onSearch: function() {
      $('#phrase_box').val('');
      grid.jqGrid('getGridParam', 'postData').filtering = true;
    },
    onInitializeSearch: window.add_buttons
  };

  if (!colModel) {
    colModel = initialColModel;
  }
  if (!colNames) {
    colNames = initialColNames;
  }

  grid = $('#scroll');
  var session_data = {}, data = grid.jqGrid('getGridParam', 'postData');
  if (window.filters) {
    session_data.filters = window.filters;
  }
  if (sort_rules) {
    sort_rules = $.evalJSON(sort_rules);
  } else {
    sort_rules = initial_sort_rules;
  }
  session_data.sort_rules = $.toJSON(sort_rules);
  grid.jqGrid({
    url: ajax_get_page,
    findIdUrl : ajax_find_id,
    datatype: "json",
    colNames: colNames,
    colModel: colModel,
    rowNum: 50,
    rowList : [20,30,50],
    scroll: 1,
    autowidth: true,
    height: $('#left').height() - 25 - $('#search-panel').height(),
    mtype: "GET",
    rownumbers: false,
    gridview: true,
    //pager: '#pager',
    viewrecords: true,
    caption: grid_caption,
    sortname: main_field,
    sortorder: 'asc',
    beforeSelectRow: function() {
      var ok = true;
      if (changed) {
        ok = window.confirm('Czy chcesz porzuci\u0107 niezapisane zmiany?');
      }
      return ok;
    },
    onSelectRow: load_content,
    beforeRequest: function() {
      var empty, filters;
      if (!grid.jqGrid('getGridParam', 'search')) {
        empty = true;
      } else {
        filters = grid.jqGrid('getGridParam', 'postData').filters;

        if (typeof(filters) === "string") {
          filters = $.parseJSON(filters);
        }
        if (typeof(filters) !== "object" || filters === null || !filters.rules) {
          empty = true;
        } else {
          empty = (filters.rules.length === 0);
        }
      }
      $('#filter-button').children().first().toggleClass('ui-state-highlight', !empty);
    },
    gridComplete: function() {
      if (grid.jqGrid('getGridParam', 'setOnComplete') === true) {
        grid.jqGrid('scrollToLastSelection');
        grid.jqGrid('setGridParam', {'setOnComplete' : false});
      }
    },
    onSortCol: sort_column,
    loadComplete: function(data) {
      var num = data.records;
      document.title = grid_caption + ' (' + num + ')';
      if (grid.jqGrid('getGridParam', 'postData').filtering == true) {
        grid.jqGrid('getGridParam', 'postData').filtering = false;
        setTimeout(findAndScroll, 100);
      }
    },
    remapColumns: window['remap']? remap : undefined,
    postData: session_data,
    search: Boolean(session_data.filters)
  });
  // nawigacja klawiaturą powoduje zmulenie,
  // bo wszystkie leksemy muszą się załadować
  //grid.jqGrid('bindKeys');
  $('#filter-button').click(function() {
    grid.jqGrid('searchGrid', jqgrid_filteroptions);
  });

  refresh_column_headers();
  findAndScroll();

  $('#' + edit_form_id).live('submit', edit_form_submit);
  $('#' + edit_form_cancel_id).live('click', function() {
    var id = $('input[name=id]', this.form).value()
    $('#edit').load(ajax_edit_form, 'id='+id, edit_form_init);
  });
  function keyup() {
    if (this.value != this.defaultValue) {
      show_changed();
    };
  };
  $('#' + edit_form_id + ' input').live('keyup', keyup);
  $('#' + edit_form_id + ' textarea').live('keyup', keyup);
  $('#' + edit_form_id + ' select').live('change', keyup);
  $('#' + edit_form_id + ' input[type=checkbox]').live('change', show_changed);

  $('#searchButton').click(findAndScroll);
  $('#phrase_box').keydown(doSearch);

  // ajax niepotrzebny...
  $("#sort-dialog-div").load(ajax_sort_rules,
    {
      colModel : $.toJSON(grid.jqGrid('getGridParam', 'colModel')),
      colNames : $.toJSON(grid.jqGrid('getGridParam', 'colNames'))
    },
    function(){
      $("#sort-dialog-form").dialog({
        autoOpen: false,
        height: 'auto',
        width: 'auto',
        modal: true
      });
    });

  $("#open-sort-dialog").click(function() {
    $("#sort-dialog-form").dialog("open");
    var rules = $.evalJSON($('#scroll').jqGrid(
      'getGridParam', 'postData').sort_rules);
    $('#sort-rule-list li').removeClass('ui-state-default');
    $.each(rules.reverse(), function(i, rule) {
      var colName = rule.field,
          li = $('li#' + colName);
      if ($.isFunction(window.sort_rule_special_features))
        sort_rule_special_features(rule);
      li.addClass('ui-state-default');
      li.find('select').val(rule.order);
      $('#sort-rule-list').prepend(li);
    });
  });

  $("#show-columns-button").click(function(){
    grid.jqGrid('columnChooser', {
      done: function(perm) {
        if (perm) this.jqGrid("remapColumns", perm, true);
        var col_model = grid.jqGrid('getGridParam', 'colModel');
        var col_names = grid.jqGrid('getGridParam', 'colNames');
        var remap = grid.jqGrid('getGridParam', 'remapColumns');
        $.ajaxJSON({
          method: 'post',
          url: ajax_save_columns,
          data: {col_model: col_model, col_names: col_names, remap: remap},
        });
      }
    });
    if ($.isFunction(window.afterShowColumnChooser))
      afterShowColumnChooser();
  });

  $("#load-filter-dialog").dialog({
    autoOpen: false,
    height: 'auto',
    width: 'auto',
    modal: true
  });

  $('.searchFilter input').live('keypress', function(e) {
    if (e.which == 13) { // enter
      $(this).change();
      // powinno być .ui-search, niegroźny byk w jqGrid
      setTimeout(function () {
        $('.searchFilter').next().find('.ui-reset').click();}, 100);
    }
  });

  init_form_widgets();
});

function doSearch(ev){
  if(!auto_search)
    return;
  if(timeoutHnd)
    clearTimeout(timeoutHnd);
  timeoutHnd = setTimeout(findAndScroll, 500);
}

function findAndScroll(){
  data = grid.jqGrid('getGridParam', 'postData');
  data.mask = $("#phrase_box").val();
  // przeładowanie można pominąć jeśli nie jesteśmy w trybie filtrowania
  if (filtering_mode) {
    grid.trigger('reloadGrid');
  }
  $.get(ajax_location, data, function(resp) {
    var selectedRow = resp['selected_id'] + "";
    var rowIndex = resp['rowIndex'];
    var recordsCount = resp['records'];
    if (recordsCount > 0) {
      grid.jqGrid('scrollAndSet', selectedRow, rowIndex, recordsCount);
    }
  });
}

function show_changed() {
  if (!changed) {
    changed = true;
    $('#' + edit_form_submit_id).button('enable');
    $('#' + edit_form_cancel_id).button('enable');
    $('#edit-tab').html('<strong>Edycja (niezapisane)</strong>');
  }
}

function hide_changed() {
  if (changed) {
    changed = false;
    $('#edit-tab').html('Edycja');
  }
}