jqgrid.js 14.6 KB
var sort_rules = $dj.sort_rules, colModel = $dj.colModel,
    colNames = $dj.colNames;
var timeoutHnd;
var jqgrid = {
    grid: undefined,

    created: false,

    changed: false,

    filteroptions: null,

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

    refresh_column_headers: function() {
        "use strict";
        var thd = $("thead:first", $('#scroll')[0].grid.hDiv).get(0);
        var rules = $.evalJSON(
            jqgrid.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>');
        }
    },

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

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

    doSearch: function() {
        "use strict";
        if (!$dj.auto_search)
            return;
        if (timeoutHnd)
            clearTimeout(timeoutHnd);
        timeoutHnd = setTimeout(jqgrid.findAndScroll, 500);
    },

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

    show_changed: function() {
        "use strict";
        if (!jqgrid.changed) {
            jqgrid.changed = true;
            $('#' + jqgrid.edit_form_submit_id).button('enable');
            $('#' + jqgrid.edit_form_cancel_id).button('enable');
            $('#edit-tab').html('<strong>Edycja (niezapisane)</strong>');
            $(window).on('beforeunload', function () {
                return "Są niezapisane zmiany.";
            });
        }
    },

    hide_changed: function() {
        "use strict";
        if (jqgrid.changed) {
            jqgrid.changed = false;
            $('#edit-tab').html('Edycja');
            $(window).off('beforeunload');
        }
    }
};

$(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 () {
            var init = {
                "groupOp": "AND",
                rules: [
                    {"field": jqgrid.main_field, "op": "eq", "data": ""}
                ]
            };
            jqgrid.put_filter(init);
        },
        onSearch: function () {
            $('#phrase_box').val('');
            jqgrid.grid.jqGrid('getGridParam', 'postData').force_reload = true;
        },
        onInitializeSearch: jqgrid.add_buttons
    };

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

    jqgrid.grid = $('#scroll');
    var session_data = {};
    if ($dj.filters) {
        session_data.filters = $dj.filters;
    }
    if (sort_rules) {
        sort_rules = $.evalJSON(sort_rules);
    } else {
        sort_rules = jqgrid.initial_sort_rules;
    }
    session_data.sort_rules = $.toJSON(sort_rules);
    jqgrid.grid.jqGrid({
        url: $dj.ajax_get_page,
        findIdUrl: $dj.ajax_find_id,
        datatype: "json",
        colNames: colNames,
        colModel: colModel,
        rowNum: 50,
        rowList: [20, 30, 50],
        scroll: 1,
        autowidth: true,
        height: $('#left').height() - 27 - $('#search-panel').height(),
        mtype: "GET",
        rownumbers: false,
        gridview: true,
        viewrecords: true,
        caption: jqgrid.grid_caption,
        sortname: jqgrid.main_field,
        sortorder: 'asc',
        forceFit: true,
        beforeSelectRow: function () {
            var ok = true;
            if (jqgrid.changed) {
                ok = window.confirm('Czy chcesz porzucić niezapisane zmiany?');
            }
            return ok;
        },
        onSelectRow: function (id) {
            common.busy_on();
            jqgrid.load_content(id);
        },
        beforeRequest: function () {
            var empty, filters;
            if (!jqgrid.grid.jqGrid('getGridParam', 'search')) {
                empty = true;
            } else {
                filters = jqgrid.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 (jqgrid.grid.jqGrid('getGridParam', 'setOnComplete') === true) {
                jqgrid.grid.jqGrid('scrollToLastSelection');
                jqgrid.grid.jqGrid('setGridParam', {'setOnComplete': false});
            }
        },
        onSortCol: jqgrid.sort_column,
        loadComplete: function (data) {
            var num = data.records;
            document.title = jqgrid.grid_caption + ' (' + num + ')';
            if (jqgrid.grid.jqGrid('getGridParam', 'postData').force_reload === true) {
                jqgrid.grid.jqGrid('getGridParam', 'postData').force_reload = false;
                setTimeout(jqgrid.findAndScroll, 100);
            }
            layout.adjust_grid_width();
        },
        remapColumns: $dj.remap,
        postData: session_data,
        search: Boolean(session_data.filters)
    });
    // nawigacja klawiaturą powoduje zmulenie,
    // bo wszystkie leksemy muszą się załadować
    //jqgrid.grid.jqGrid('bindKeys');
    $('#filter-button').click(function () {
        jqgrid.grid.jqGrid('searchGrid', jqgrid.filteroptions);
    });

    jqgrid.refresh_column_headers();
    jqgrid.findAndScroll();

    $(document).on('submit', '#' + jqgrid.edit_form_id, jqgrid.edit_form_submit);
    $(document).on('click', '#' + jqgrid.edit_form_cancel_id, function () {
        var id = $('input[name=id]', this.form).value();
        $.ajaxJSON({
            method: 'get',
            dest: $('#edit'),
            url: $dj.ajax_edit_form,
            data: {id: id},
            callback: jqgrid.edit_form_init
        });
    });
    var keyup = function () {
        if (this.value !== this.defaultValue) {
            jqgrid.show_changed();
        }
    };
    $(document).on('keyup', '#' + jqgrid.edit_form_id + ' input', keyup);
    $(document).on('keyup', '#' + jqgrid.edit_form_id + ' textarea', keyup);
    $(document).on('change', '#' + jqgrid.edit_form_id + ' select', keyup);
    $(document).on(
        'change', '#' + jqgrid.edit_form_id + ' input[type=checkbox]',
        jqgrid.show_changed);

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

    for (var i = 0; i < colNames.length; i++) {
        if (colModel[i].sortable !== false) {
            var label = colNames[i];
            var index = colModel[i].index;
            var li = $(
                '<li class="ui-state-default">' +
                    '<span class="sort-column"></span>' +
                    '<span class="sort-dir">' +
                    '<select>' +
                    '<option value="asc">Rosnąco</option>' +
                    '<option value="desc">Malejąco</option>' +
                    '</select>' +
                    '</span>' +
                    '</li>');
            li.attr('id', index);
            $('.sort-column', li).text(label);
            $('select', li).attr('id', 'order-' + index);
            if (index === 'entry') {
                var span = $(
                    '<span class="sort-a-tergo">' +
                        '<input type="checkbox" id="entries_a_tergo"/> a tergo' +
                        '</span>');
                span.appendTo(li);
            }
            li.appendTo($('#sort-rule-list'));
        }
    }
    $("#sort-dialog").dialog({
        autoOpen: false,
        height: 'auto',
        width: 'auto',
        modal: true
    });
    $("#sort-rule-list").sortable();

    $('#cancel-sort-order').click(function () {
        $("#sort-dialog").dialog("close");
    });

    $('#save-sort-order').click(function () {
        var a_tergo = $('#sort-dialog').find('#entries_a_tergo').value();
        var list_table = $('#sort-rule-list').find('li');
        //lista par (nazwa pola - porzadek sortowania)
        var rules = [];
        for (var i = 0; i < list_table.length; i++) {
            var col_name = list_table[i].id;
            var rule = {
                field: col_name,
                order: $('#order-' + col_name).value()
            };
            if (col_name === 'entry') {
                rule.a_tergo = a_tergo;
            }
            rules.push(rule);
        }
        //dobieramy sie do danych grida
        $('#scroll').jqGrid('getGridParam', 'postData').sort_rules = $.toJSON(rules);
        jqgrid.grid.jqGrid('setGridParam', {'setOnComplete': true});

        //zmiany w nagłówkach kolumn
        jqgrid.refresh_column_headers();

        $("#sort-dialog").dialog("close");
        jqgrid.grid.trigger("reloadGrid");
    });

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

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

    $(document).on('keypress', '.searchFilter input', 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);
        }
    });

    jqgrid.init_form_widgets();
    // brzydko, ale cóż
    layout.adjust_tabs();
});