Many resources are needed to download a project. Please understand that we have to compensate our server costs. Thank you in advance. Project price only 1 $
You can buy this project and download/modify it how often you want.
// ==ClosureCompiler==
// @compilation_level SIMPLE_OPTIMIZATIONS
/**
* @license jqGrid 4.15.5-pre - free jqGrid: https://github.com/free-jqgrid/jqGrid
* Copyright (c) 2008-2014, Tony Tomov, [email protected]
* Copyright (c) 2014-2018, Oleg Kiriljuk, [email protected]
* Dual licensed under the MIT and GPL licenses
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl-2.0.html
* Date: 2018-08-12
*/
//jsHint options
/*jshint eqnull:true */
/*jslint browser: true, evil: true, devel: true, white: true */
/*global jQuery, define, HTMLElement, HTMLTableRowElement, module, require */
(function (global, factory) {
"use strict";
if (typeof define === "function" && define.amd) {
// AMD. Register as an anonymous module.
//console.log("grid.base AMD");
define([
"jquery"
], function ($) {
//console.log("grid.base AMD: define callback");
return factory($, global.document);
});
} else if (typeof module === "object" && module.exports) {
// Node/CommonJS
//console.log("grid.base CommonJS");
module.exports = function (root, $) {
//console.log("grid.base CommonJS: in module.exports");
if (!root) {
root = window;
}
//console.log("grid.base CommonJS: before require('jquery')");
if ($ === undefined) {
// require("jquery") returns a factory that requires window to
// build a jQuery instance, we normalize how we use modules
// that require this pattern but the window provided is a noop
// if it's defined (how jquery works)
$ = typeof window !== "undefined" ?
require("jquery") :
require("jquery")(root);
}
//global.jQuery = $;
//root.jQuery = $;
//console.log("grid.base CommonJS: before factory");
factory($, root.document);
return $;
};
} else {
// Browser globals
//console.log("grid.base Browser: before factory");
factory(jQuery, global.document);
}
}(typeof window !== "undefined" ? window : this, function ($, document) {
"use strict";
// begin module grid.base
/** @const */
var englishLanguageDefaults = {
name: "English (United States)",
nameEnglish: "English (United States)",
isRTL: false,
defaults: {
recordtext: "View {0} - {1} of {2}",
emptyrecords: "No records to view",
loadtext: "Loading...",
pgtext: "Page {0} of {1}",
pgfirst: "First Page",
pglast: "Last Page",
pgnext: "Next Page",
pgprev: "Previous Page",
pgrecs: "Records per Page",
showhide: "Toggle Expand Collapse Grid",
savetext: "Saving..."
},
search: {
caption: "Search...",
Find: "Find",
Reset: "Reset",
odata: [
{ oper: "eq", text: "equal" },
{ oper: "ne", text: "not equal" },
{ oper: "lt", text: "less" },
{ oper: "le", text: "less or equal" },
{ oper: "gt", text: "greater" },
{ oper: "ge", text: "greater or equal" },
{ oper: "bw", text: "begins with" },
{ oper: "bn", text: "does not begin with" },
{ oper: "in", text: "is in" },
{ oper: "ni", text: "is not in" },
{ oper: "ew", text: "ends with" },
{ oper: "en", text: "does not end with" },
{ oper: "cn", text: "contains" },
{ oper: "nc", text: "does not contain" },
{ oper: "nu", text: "is null" },
{ oper: "nn", text: "is not null" }
],
groupOps: [
{ op: "AND", text: "all" },
{ op: "OR", text: "any" }
],
addGroupTitle: "Add subgroup",
deleteGroupTitle: "Delete group",
addRuleTitle: "Add rule",
deleteRuleTitle: "Delete rule",
operandTitle: "Click to select search operation.",
resetTitle: "Reset Search Value"
},
edit: {
addCaption: "Add Record",
editCaption: "Edit Record",
bSubmit: "Submit",
bCancel: "Cancel",
bClose: "Close",
saveData: "Data has been changed! Save changes?",
bYes: "Yes",
bNo: "No",
bExit: "Cancel",
msg: {
required: "Field is required",
number: "Please, enter valid number",
minValue: "value must be greater than or equal to ",
maxValue: "value must be less than or equal to",
email: "is not a valid e-mail",
integer: "Please, enter valid integer value",
date: "Please, enter valid date value",
url: "is not a valid URL. Prefix required ('http://' or 'https://')",
nodefined: " is not defined!",
novalue: " return value is required!",
customarray: "Custom function should return array!",
customfcheck: "Custom function should be present in case of custom checking!"
}
},
view: {
caption: "View Record",
bClose: "Close"
},
del: {
caption: "Delete",
msg: "Delete selected record(s)?",
bSubmit: "Delete",
bCancel: "Cancel"
},
nav: {
edittext: "",
edittitle: "Edit selected row",
addtext: "",
addtitle: "Add new row",
deltext: "",
deltitle: "Delete selected row",
searchtext: "",
searchtitle: "Find records",
refreshtext: "",
refreshtitle: "Reload Grid",
alertcap: "Warning",
alerttext: "Please, select row",
viewtext: "",
viewtitle: "View selected row",
savetext: "",
savetitle: "Save row",
canceltext: "",
canceltitle: "Cancel row editing"
},
col: {
caption: "Select columns",
bSubmit: "Ok",
bCancel: "Cancel"
},
errors: {
errcap: "Error",
nourl: "No url is set",
norecords: "No records to process",
model: "Length of colNames <> colModel!"
},
formatter: {
integer: {
thousandsSeparator: ",",
defaultValue: "0"
},
number: {
decimalSeparator: ".",
thousandsSeparator: ",",
decimalPlaces: 2,
defaultValue: "0.00"
},
currency: {
decimalSeparator: ".",
thousandsSeparator: ",",
decimalPlaces: 2,
prefix: "",
suffix: "",
defaultValue: "0.00"
},
date: {
dayNames: [
"Sun", "Mon", "Tue", "Wed", "Thr", "Fri", "Sat",
"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
],
monthNames: [
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
],
AmPm: ["am", "pm", "AM", "PM"],
S: function (j) {
var ending = ["st", "nd", "rd", "th"];
return j < 11 || j > 13 ? ending[Math.min((j - 1) % 10, 3)] : "th";
},
srcformat: "Y-m-d",
newformat: "n/j/Y",
masks: {
// see http://php.net/manual/en/function.date.php for PHP format used in jqGrid
// and see http://docs.jquery.com/UI/Datepicker/formatDate
// and https://github.com/jquery/globalize#dates for alternative formats used frequently
// one can find on https://github.com/jquery/globalize/tree/master/lib/cultures many
// information about date, time, numbers and currency formats used in different countries
// one should just convert the information in PHP format
// short date:
// n - Numeric representation of a month, without leading zeros
// j - Day of the month without leading zeros
// Y - A full numeric representation of a year, 4 digits
// example: 3/1/2012 which means 1 March 2012
ShortDate: "n/j/Y", // in jQuery UI Datepicker: "M/d/yyyy"
// long date:
// l - A full textual representation of the day of the week
// F - A full textual representation of a month
// d - Day of the month, 2 digits with leading zeros
// Y - A full numeric representation of a year, 4 digits
LongDate: "l, F d, Y", // in jQuery UI Datepicker: "dddd, MMMM dd, yyyy"
// long date with long time:
// l - A full textual representation of the day of the week
// F - A full textual representation of a month
// d - Day of the month, 2 digits with leading zeros
// Y - A full numeric representation of a year, 4 digits
// g - 12-hour format of an hour without leading zeros
// i - Minutes with leading zeros
// s - Seconds, with leading zeros
// A - Uppercase Ante meridiem and Post meridiem (AM or PM)
FullDateTime: "l, F d, Y g:i:s A", // in jQuery UI Datepicker: "dddd, MMMM dd, yyyy h:mm:ss tt"
// month day:
// F - A full textual representation of a month
// d - Day of the month, 2 digits with leading zeros
MonthDay: "F d", // in jQuery UI Datepicker: "MMMM dd"
// short time (without seconds)
// g - 12-hour format of an hour without leading zeros
// i - Minutes with leading zeros
// A - Uppercase Ante meridiem and Post meridiem (AM or PM)
ShortTime: "g:i A", // in jQuery UI Datepicker: "h:mm tt"
// long time (with seconds)
// g - 12-hour format of an hour without leading zeros
// i - Minutes with leading zeros
// s - Seconds, with leading zeros
// A - Uppercase Ante meridiem and Post meridiem (AM or PM)
LongTime: "g:i:s A", // in jQuery UI Datepicker: "h:mm:ss tt"
// month with year
// Y - A full numeric representation of a year, 4 digits
// F - A full textual representation of a month
YearMonth: "F, Y" // in jQuery UI Datepicker: "MMMM, yyyy"
}
}
}
};
$.jgrid = $.jgrid || {};
var jgrid = $.jgrid;
jgrid.locales = jgrid.locales || {};
var locales = jgrid.locales;
/**
* Enum with different components of jqGrid.
* @enum {number} @const
*/
/*var INPUT_NAME_TYPE = {
COL_NAME: 0,
ADDITIONAL_PROPERTY: 1,
ROWID: 2
};*/
/**
* Enum with different components of jqGrid.
* @enum {number} @const
*/
var COMPONENT_NAMES = {
// let us this -
from which grid is created. Then
// gBox (grid box) - outer div which includes all grid components: $(this).closest(".ui-jqgrid")[0]
// In the same way
GRID_BOX_DIV: 0, // tagName: "div". class: "ui-jqgrid". Id: "gbox_" + gridId
GRID_OVERLAY_DIV: 1, // tagName: "div". class: "jqgrid-overlay". Id: "lui_" + gridId
LOADING_DIV: 2, // tagName: "div". class: "loading". Id: "load_" + gridId
DIALOG_ALERT_DIV: 3, // tagName: "div". class: "ui-jqdialog". Id: "alertmod_" + gridId
DIALOG_SEARCH_DIV: 4, // tagName: "div". class: "ui-jqdialog". Id: "searchmodfbox_" + gridId
DIALOG_VIEW_DIV: 5, // tagName: "div". class: "ui-jqdialog". Id: "viewmod" + gridId
DIALOG_EDIT_DIV: 6, // tagName: "div". class: "ui-jqdialog". Id: "editmod" + gridId
DIALOG_DELETE_DIV: 7, // tagName: "div". class: "ui-jqdialog". Id: "delmod" + gridId
GRID_VIEW_DIV: 8, // tagName: "div". class: "ui-jqgrid-view". Id: "gview_" + gridId
TITLE_BAR_DIV: 9, // tagName: "div". class: "ui-jqgrid-titlebar" and either "ui-jqgrid-caption" or "ui-jqgrid-caption-rtl"
UPPER_TOOLBAR_DIV: 10, // tagName: "div". class: "ui-userdata". Id: "tb_" + gridId
TOP_PAGER_DIV: 11, // tagName: "div". class: "ui-jqgrid-toppager". Id: gridId + "_toppager"
HEADER_DIV: 12, // tagName: "div". class: "ui-jqgrid-hdiv"
HEADER_BOX_DIV: 13, // tagName: "div". class: either "ui-jqgrid-hdiv" or "ui-jqgrid-hbox-rtl"
HEADER_TABLE: 14, // tagName: "table". class: "ui-jqgrid-htable"
HEADER_COLS_ROW: 15, // tagName: "tr". class: "jqgfirstrow" or the row with column headers
HEADER_COLS: 16, // tagName: "th". class: either "ui-first-th-rtl" or "ui-first-th-rtl"
HEADER_ROWS: 47, // tagName: "tr". class: "ui-jqgrid-labels"
HEADER_TH: 48, // tagName: "th". class: "ui-th-column" and either "ui-th-ltr" or "ui-th-rtl"
HEADER_SORTABLE_DIV: 49, // tagName: "div". class: "ui-jqgrid-labels"
HEADER_RESIZABLE_SPAN: 50, // tagName: "span". class: "ui-jqgrid-resize" and either "ui-jqgrid-resize-ltr" or "ui-jqgrid-resize-rtl"
HEADER_SELECT_ALL_ROWS_CHECKBOX: 45, // tagName: "input" (can be changed to "button" in the future). class: "cbox". Id: "cb_" + gridId
SEARCH_TOOLBAR: 17, // tagName: "tr". class: "ui-search-toolbar". Its direct children are th having class "ui-th-column" and optionally "ui-th-rtl"
BODY_DIV: 18, // tagName: "div". class: "ui-jqgrid-bdiv"
BODY_SCROLL_FULL_DIV: 19, // tagName: "div" - It can have height CSS property which simulate the total size of virtual data.
BODY_SCROLL_TOP_DIV: 20, // tagName: "div" - It can have height CSS property which simulate virtual data before the current displayed in btable.
BODY_TABLE: 21, // tagName: "table". class: "ui-jqgrid-btable". Id: gridId
GRID: 21, // tagName: "table". class: "ui-jqgrid-btable". Id: gridId
BODY_COLS_ROW: 22, // tagName: "tr". class: "jqgfirstrow"
BODY_COLS: 23, // tagName: "td"
BODY_DATA_ROWS: 24, // tagName: "tr". class: "jqgrow" and optionally "ui-row-rtl"
FOOTER_DIV: 25, // tagName: "div". class: "ui-jqgrid-sdiv"
FOOTER_BOX_DIV: 26, // tagName: "div". class: either "ui-jqgrid-hdiv" or "ui-jqgrid-hbox-rtl". ??? is it really needed ???
FOOTER_TABLE: 27, // tagName: "table". class: "ui-jqgrid-ftable"
FOOTER_DATA_ROWS: 28, // tagName: "tr". class: "footrow", optionally additionally "footrow-rtl"
BOTTOM_TOOLBAR_DIV: 29, // tagName: "div". class: "ui-userdata". Id: "tb_" + gridId
FROZEN_HEADER_DIV: 30, // tagName: "div". class: "frozen-div" and "ui-jqgrid-hdiv"
// no hBox currently exists
FROZEN_HEADER_TABLE: 31, // tagName: "table". class: "ui-jqgrid-htable"
FROZEN_HEADER_COLS_ROW: 32, // tagName: "tr". class: "jqgfirstrow"
FROZEN_HEADER_COLS: 33, // tagName: "th". class: either "ui-first-th-rtl" or "ui-first-th-rtl"
FROZEN_SEARCH_TOOLBAR: 34, // tagName: "tr". class: "ui-search-toolbar". Its direct children are th having class "ui-th-column" and optionally "ui-th-rtl"
// TODO: fix id of children of .ui-search-input to have no id duplicates with the main grid
FROZEN_FOOTER_DIV: 35, // tagName: "div". class: "frozen-div" and "ui-jqgrid-sdiv"
FROZEN_FOOTER_TABLE: 36, // tagName: "table". class: "ui-jqgrid-ftable"
FROZEN_FOOTER_DATA_ROWS: 37, // tagName: "tr". class: "footrow", optionally additionally "footrow-rtl"
FROZEN_BODY_DIV: 38, // tagName: "div". class: "frozen-div" and "ui-jqgrid-bdiv"
// no full scroll div and top scroll div is currently exist
FROZEN_BODY_TABLE: 39, // tagName: "table". class: "ui-jqgrid-btable". Id: gridId + "_frozen"
FROZEN_BODY_COLS_ROW: 40, // tagName: "tr". class: "jqgfirstrow"
FROZEN_BODY_COLS: 41, // tagName: "td"
FROZEN_BODY_DATA_ROWS: 42, // tagName: "tr". class: "jqgrow" and optionally "ui-row-rtl"
// TODO: fix id of children of .jqgrow to have no id duplicates with the main grid
COLUMN_RESIZER_DIV: 43, // tagName: "div". class: "ui-jqgrid-resize-mark". Id: "rs_m" + gridId
BOTTOM_PAGER_DIV: 44, // tagName: "div". class: "ui-jqgrid-pager"
SEARCH_OPERATION_MENU_UL: 46 // tagName: "ul". class: "ui-search-menu". id="sopt_menu"
};
if (jgrid.defaults == null || $.isEmptyObject(locales) || locales["en-US"] === undefined) {
// set English options only if no grid.locale-XX.js file are included before jquery.jqGrid.min.js or jquery.jqGrid.src.js
// the files included AFTER jquery.jqGrid.min.js or jquery.jqGrid.src.js will just overwrite all the settings which were set previously
// We can set locInfo under $.jgrid additionally to setting under $.jgrid.locales[locale]
// only to have more compatibility with the previous version of jqGrid.
// We don't make this currently.
if (locales["en-US"] === undefined) {
$.extend(true, jgrid, /*englishLanguageDefaults,*/ {
locales: {
"en-US": englishLanguageDefaults // and for English US
}
});
}
jgrid.defaults = jgrid.defaults || {};
if (jgrid.defaults.locale === undefined) {
jgrid.defaults.locale = "en-US";
}
}
jgrid.defaults = jgrid.defaults || {};
var defaults = jgrid.defaults;
//if (jgrid.defaults.locale && locales[jgrid.defaults.locale]) {
// $.extend(true, $.jgrid, locales[jgrid.defaults.locale]); // add to improve compatibility only
//}
$.extend(true, jgrid, {
/** @const */
version: "4.15.5-pre",
/** @const */
productName: "free jqGrid",
defaults: {},
search: {},
edit: {},
view: {},
del: {},
nav: {},
col: {},
errors: {},
formatter: {
unused: "" // used only to detect whether the changes are overwritten because of wrong usage
},
icons: {
jQueryUI: {
common: "ui-icon",
pager: {
first: "ui-icon-seek-first",
prev: "ui-icon-seek-prev",
next: "ui-icon-seek-next",
last: "ui-icon-seek-end"
},
sort: {
asc: "ui-icon-triangle-1-n",
desc: "ui-icon-triangle-1-s"
},
gridMinimize: {
visible: "ui-icon-circle-triangle-n",
hidden: "ui-icon-circle-triangle-s"
},
nav: {
edit: "ui-icon-pencil",
add: "ui-icon-plus",
del: "ui-icon-trash",
search: "ui-icon-search",
refresh: "ui-icon-refresh",
view: "ui-icon-document",
save: "ui-icon-disk",
cancel: "ui-icon-cancel",
newbutton: "ui-icon-newwin"
},
actions: {
edit: "ui-icon-pencil",
del: "ui-icon-trash",
save: "ui-icon-disk",
cancel: "ui-icon-cancel"
},
form: {
close: "ui-icon-closethick",
prev: "ui-icon-triangle-1-w",
next: "ui-icon-triangle-1-e",
save: "ui-icon-disk",
undo: "ui-icon-close",
del: "ui-icon-scissors",
cancel: "ui-icon-cancel",
resizableLtr: "ui-resizable-se ui-icon ui-icon-gripsmall-diagonal-se"
},
search: {
search: "ui-icon-search",
reset: "ui-icon-arrowreturnthick-1-w",
query: "ui-icon-comment"
},
subgrid: {
plus: "ui-icon-plus",
minus: "ui-icon-minus",
openLtr: "ui-icon-caret-1-sw",
openRtl: "ui-icon-caret-1-se"
},
grouping: {
plus: "ui-icon-circlesmall-plus",
minus: "ui-icon-circlesmall-minus"
},
treeGrid: {
minus: "ui-icon-triangle-1-s",
leaf: "ui-icon-radio-off",
plusLtr: "ui-icon-triangle-1-e",
plusRtl: "ui-icon-triangle-1-w"
}
},
fontAwesome: {
common: "fa",
pager: {
common: "fa-fw",
first: "fa-step-backward",
prev: "fa-backward",
next: "fa-forward",
last: "fa-step-forward"
},
sort: {
common: "fa-lg", // common: "",
asc: "fa-sort-asc", // asc: "fa-sort-amount-asc",
desc: "fa-sort-desc" // desc: "fa-sort-amount-desc"
},
gridMinimize: {
visible: "fa-chevron-circle-up",
hidden: "fa-chevron-circle-down"
},
nav: {
common: "fa-lg fa-fw",
edit: "fa-pencil",
add: "fa-plus",
del: "fa-trash-o",
search: "fa-search",
refresh: "fa-refresh",
view: "fa-file-o",
save: "fa-floppy-o",
cancel: "fa-ban",
newbutton: "fa-external-link"
},
actions: {
common: "fa-fw",
edit: "fa-pencil",
del: "fa-trash-o",
save: "fa-floppy-o",
cancel: "fa-ban"
},
form: {
close: "fa-times",
prev: "fa-caret-left",
next: "fa-caret-right",
save: "fa-floppy-o",
undo: "fa-undo",
del: "fa-trash-o",
cancel: "fa-ban",
resizableLtr: "fa-rss fa-rotate-270"
},
search: {
search: "fa-search",
reset: "fa-undo",
query: "fa-comments-o"
},
subgrid: {
common: "fa-fw",
plus: "fa-plus",
minus: "fa-minus",
openLtr: "fa-reply fa-rotate-180",
openRtl: "fa-share fa-rotate-180"
},
grouping: {
common: "fa-fw",
plus: "fa-plus-square-o",
minus: "fa-minus-square-o"
},
treeGrid: {
common: "fa-fw",
minus: "fa-lg fa-sort-desc",
leaf: "fa-dot-circle-o",
plusLtr: "fa-lg fa-caret-right",
plusRtl: "fa-lg fa-caret-left"
},
checkbox: {
checkedClasses: "fa-check-square-o",
checked: "fa-check-square-o fa-lg",
unchecked: "fa-square-o fa-lg"
}
},
fontAwesome5: {
//common: "fas", //"fa"
pager: {
common: "fa-fw",
first: "fa-step-backward",
prev: "fa-backward",
next: "fa-forward",
last: "fa-step-forward"
},
sort: {
common: "fa-lg", // common: "",
asc: "fa-sort-up", //"fa-sort-asc", // asc: "fa-sort-amount-asc",
desc: "fa-sort-down" //"fa-sort-desc" // desc: "fa-sort-amount-desc"
},
gridMinimize: {
visible: "fa-chevron-circle-up",
hidden: "fa-chevron-circle-down"
},
nav: {
common: "fa-lg fa-fw",
edit: "fa-pencil-alt",
add: "fa-plus",
del: "fa-trash-alt",
search: "fa-search",
refresh: "fa-sync", //"fa-refresh",
view: "fa-file",
save: "fa-save",
cancel: "fa-ban",
newbutton: "fa-external-link-alt"
},
actions: {
common: "fa-fw",
edit: "fa-pencil-alt",
del: "fa-trash-alt",
save: "fa-save",
cancel: "fa-ban"
},
form: {
close: "fa-times",
prev: "fa-caret-left",
next: "fa-caret-right",
save: "fa-save",
undo: "fa-undo",
del: "fa-trash-alt",
cancel: "fa-ban",
resizableLtr: "fa-rss fa-lg fa-rotate-270"
},
search: {
search: "fa-search",
reset: "fa-undo",
query: "fa-comments"
},
subgrid: {
common: "fa-fw",
plus: "fa-plus",
minus: "fa-minus",
openLtr: "fa-reply fa-rotate-180",
openRtl: "fa-share fa-rotate-180"
},
grouping: {
common: "fa-fw",
plus: "fa-plus-square",
minus: "fa-minus-square"
},
treeGrid: {
common: "fa-fw",
minus: "fa-lg fa-sort-down", //"fa-lg fa-sort-desc",
leaf: "fa-dot-circle",
plusLtr: "fa-lg fa-caret-right",
plusRtl: "fa-lg fa-caret-left"
},
checkbox: {
ignoreParents: true,
checkedClasses: "fa-check-square",
checked: "far fa-check-square fa-lg",
unchecked: "far fa-square fa-lg"
}
},
fontAwesomeBrands: {
baseIconSet: "fontAwesome5",
common: "fab"
},
fontAwesomeLight: {
baseIconSet: "fontAwesome5",
common: "fal"
},
fontAwesomeRegular: {
baseIconSet: "fontAwesome5",
common: "far"
},
fontAwesomeSolid: {
baseIconSet: "fontAwesome5",
common: "fas"
},
fontAwesomeSVG: {
baseIconSet: "fontAwesome5",
common: "fas"
},
glyph: {
common: "glyphicon",
pager: {
common: "",
first: "glyphicon-step-backward",
prev: "glyphicon-backward",
next: "glyphicon-forward",
last: "glyphicon-step-forward"
},
sort: {
common: "",
asc: "glyphicon-triangle-top",
desc: "glyphicon-triangle-bottom"
},
gridMinimize: {
visible: "glyphicon-circle-arrow-up",
hidden: "glyphicon-circle-arrow-down"
},
nav: {
common: "",
edit: "glyphicon-edit",
add: "glyphicon-plus",
del: "glyphicon-trash",
search: "glyphicon-search",
refresh: "glyphicon-refresh",
view: "glyphicon-file", // glyphicon glyphicon-th-list
save: "glyphicon-save",
cancel: "glyphicon-ban-circle",
newbutton: "glyphicon-new-window"
},
actions: {
common: "",
edit: "glyphicon-edit",
del: "glyphicon-trash",
save: "glyphicon-save",
cancel: "glyphicon-ban-circle"
},
form: {
close: "glyphicon-remove-circle",
prev: "glyphicon-step-backward",
next: "glyphicon-step-forward",
save: "glyphicon-save",
undo: "glyphicon-repeat",
del: "glyphicon-trash",
cancel: "glyphicon-ban-circle",
resizableLtr: "glyphicon-import"
},
search: {
search: "glyphicon-search",
reset: "glyphicon-repeat",
query: "glyphicon-cog" //"glyphicon-comment"
},
subgrid: {
common: "",
plus: "glyphicon-zoom-in", //"glyphicon-plus", "glyphicon-th-list",
minus: "glyphicon-zoom-out", // "glyphicon-minus",
openLtr: "glyphicon-indent-left",
openRtl: "glyphicon-indent-left"
},
grouping: {
common: "",
plus: "glyphicon-expand",
minus: "glyphicon-collapse-down"
},
treeGrid: {
common: "",
minus: "glyphicon-triangle-bottom",
leaf: "glyphicon-record", // glyphicon-unchecked
plusLtr: "glyphicon-triangle-right",
plusRtl: "glyphicon-triangle-left"
},
checkbox: {
checkedClasses: "glyphicon-check",
checked: "glyphicon-check",
unchecked: "glyphicon-unchecked"
}
}
},
guiStyles: {
jQueryUI: {
gBox: "ui-jqgrid-jquery-ui ui-widget ui-widget-content ui-corner-all", // ui-widget-content??? for the children of gbox
gView: "",
overlay: "ui-widget-overlay",
loading: "ui-state-default ui-state-active",
hDiv: "ui-state-default ui-corner-top",
hTable: "",
colHeaders: "ui-state-default",
states: {
select: "ui-state-highlight",
disabled: "ui-state-disabled ui-jqgrid-disablePointerEvents",
hover: "ui-state-hover", // can be table-hover on
only and style like .table-hover tbody tr:hover td
error: "ui-state-error",
active: "ui-state-active",
textOfClickable: "ui-state-default"
},
dialog: {
header: "ui-widget-header ui-dialog-titlebar ui-corner-all ui-helper-clearfix",
window: "ui-jqgrid-jquery-ui ui-widget ui-widget-content ui-corner-all ui-front",
document: "",
subdocument: "",
body: "",
footer: "",
content: "ui-widget-content",
hr: "ui-widget-content",
closeButton: "ui-corner-all",
fmButton: "ui-state-default",
dataField: "ui-widget-content ui-corner-all",
viewCellLabel: "ui-widget-content",
viewLabel: "",
viewCellData: "ui-widget-content",
viewData: "",
leftCorner: "ui-corner-left",
rightCorner: "ui-corner-right",
defaultCorner: "ui-corner-all"
},
filterToolbar: {
dataField: "ui-widget-content"
},
subgrid: {
thSubgrid: "ui-state-default", // used only with subGridModel
rowSubTable: "ui-widget-content", // used only with subGridModel additionally to ui-subtblcell
row: "ui-widget-content", // class of the subgrid row, additional to ui-subgrid
tdStart: "", // it can be with span over rownumber and multiselect columns
tdWithIcon: "ui-widget-content", // class of cell with +- icon, additional to subgrid-cell
buttonDiv: "",
button: "",
tdData: "ui-widget-content", // class of main td with span over the grid, additional subgrid-data
legacyTable: ""
},
grid: "",
gridRow: "ui-widget-content",
rowNum: "ui-state-default",
gridFooter: "",
rowFooter: "ui-widget-content",
gridTitle: "ui-widget-header ui-corner-top",
gridError: "ui-state-error",
gridErrorText: "",
titleButton: "ui-corner-all",
toolbarUpper: "ui-state-default",
toolbarBottom: "ui-state-default",
actionsDiv: "ui-widget-content",
actionsButton: "ui-corner-all",
pager: {
pager: "ui-state-default",
pagerButton: "ui-corner-all",
pagerInput: "ui-widget-content",
pagerSelect: "ui-widget-content"
},
navButton: "ui-corner-all",
searchDialog: {
operator: "ui-corner-all",
label: "ui-corner-all",
elem: "ui-corner-all",
operationGroup: "",
addRuleButton: "ui-corner-all",
deleteRuleButton: "ui-corner-all",
operationSelect: "ui-corner-all",
addGroupButton: "ui-corner-all",
deleteGroupButton: "ui-corner-all"
},
searchToolbar: {
menu: "ui-menu-jqueryui ui-menu ui-widget ui-widget-content ui-corner-all",
menuItem: "ui-menu-item",
menuItemButton: "ui-corner-all",
operButton: "ui-corner-all",
clearButton: "ui-corner-all"
},
top: "ui-corner-top",
bottom: "ui-corner-bottom",
resizer: "ui-widget-header"
},
bootstrap: {
gBox: "ui-jqgrid-bootstrap",
gView: "panel-info",
overlay: "modal-backdrop",
loading: "alert alert-info",
hDiv: "",
hTable: "table table-hover table-condensed table-bordered",
colHeaders: "",
states: {
select: "success",
disabled: "disabled ui-jqgrid-disablePointerEvents",
hover: "active",
error: "danger",
active: "active",
textOfClickable: ""
},
dialog: {
header: "modal-header",
window: "modal ui-jqgrid-bootstrap",
document: "modal-dialog",
subdocument: "modal-content",
body: "modal-body",
footer: "modal-footer",
content: "modal-content",
hr: "hidden",
closeButton: "btn btn-xs btn-default",
fmButton: "btn btn-default",
dataField: "form-control",
viewCellLabel: "",
viewLabel: "control-label",
viewCellData: "",
viewData: "form-control",
leftCorner: "",
rightCorner: "",
defaultCorner: ""
},
filterToolbar: {
dataField: "form-control"
},
subgrid: {
thSubgrid: "",
rowSubTable: "",
row: "",
tdStart: "",
tdWithIcon: "",
buttonDiv: "",
button: "btn btn-xs",
tdData: "",
legacyTable: "table table-condensed table-hover table-bordered"
},
grid: "table table-condensed table-hover table-bordered",
gridRow: "",
rowNum: "",
gridFooter: "table table-hover table-condensed table-bordered",
rowFooter: "",
gridTitle: "",
gridError: "alert alert-danger",
gridErrorText: "sr-only",
titleButton: "btn btn-xs btn-default",
actionsDiv: "",
actionsButton: "btn btn-xs btn-default",
toolbarUpper: "",
toolbarBottom: "",
pager: {
pager: "panel-footer",
pagerButton: "btn btn-xs",
pagerInput: "form-control",
pagerSelect: "form-control"
},
navButton: "btn btn-xs",
searchDialog: {
operator: "form-control",
label: "form-control",
elem: "form-control",
operationGroup: "form-inline",
addRuleButton: "btn btn-xs btn-default",
deleteRuleButton: "btn btn-xs btn-default",
operationSelect: "form-control",
addGroupButton: "btn btn-xs btn-default",
deleteGroupButton: "btn btn-xs btn-default"
},
searchToolbar: {
menu: "dropdown-menu",
menuItem: "",
menuItemButton: "ui-corner-all",
operButton: "btn btn-xs btn-default",
clearButton: "btn btn-xs btn-default"
},
top: "ui-jqgrid-bootstrap-corner-top",
bottom: "ui-jqgrid-bootstrap-corner-bottom",
resizer: "ui-jqgrid-bootstrap"
},
bootstrapPrimary: {
baseGuiStyle: "bootstrap",
dialog: {
closeButton: "btn btn-xs close",
fmButton: "btn btn-primary"
},
searchDialog: {
addRuleButton: "btn btn-xs btn-primary",
deleteRuleButton: "btn btn-xs btn-primary",
addGroupButton: "btn btn-xs btn-primary",
deleteGroupButton: "btn btn-xs btn-primary"
}
},
bootstrap4: {
gBox: "ui-jqgrid-bootstrap",
gView: "card",
overlay: "modal-backdrop",
loading: "alert alert-info",
hDiv: "",
hTable: "table table-hover table-sm table-bordered",
colHeaders: "",
states: {
select: "table-success",
disabled: "disabled ui-jqgrid-disablePointerEvents",
hover: "active",
hoverTh: "table-active",
error: "danger",
active: "active",
textOfClickable: ""
},
dialog: {
header: "modal-header",
window: "modal ui-jqgrid-bootstrap",
document: "modal-dialog",
subdocument: "modal-content",
body: "modal-body",
footer: "modal-footer",
content: "modal-content",
hr: "d-none",
closeButton: "btn btn-xs btn-outline-primary",
fmButton: "btn btn-outline-secondary",
dataField: "form-control",
viewCellLabel: "",
viewLabel: "control-label",
viewCellData: "",
viewData: "form-control",
leftCorner: "",
rightCorner: "",
defaultCorner: ""
},
filterToolbar: {
dataField: "form-control"
},
subgrid: {
thSubgrid: "",
rowSubTable: "",
row: "",
tdStart: "",
tdWithIcon: "",
buttonDiv: "",
button: "btn btn-xs",
tdData: "",
legacyTable: "table table-condensed table-hover table-bordered"
},
grid: "table table-condensed table-hover table-bordered",
gridRow: "",
rowNum: "",
gridFooter: "table table-hover table-condensed table-bordered",
rowFooter: "",
gridTitle: "",
gridError: "alert alert-danger",
gridErrorText: "sr-only",
titleButton: "btn btn-xs btn-outline-primary",
actionsDiv: "",
actionsButton: "btn btn-xs btn-outline-secondary",
toolbarUpper: "",
toolbarBottom: "",
pager: {
pager: "card-footer",
pagerButton: "btn btn-xs",
pagerInput: "form-control",
pagerSelect: "form-control"
},
navButton: "btn btn-xs",
searchDialog: {
operator: "form-control",
label: "form-control",
elem: "form-control",
operationGroup: "form-inline",
addRuleButton: "btn btn-xs btn-default",
deleteRuleButton: "btn btn-xs btn-default",
operationSelect: "form-control",
addGroupButton: "btn btn-xs btn-default",
deleteGroupButton: "btn btn-xs btn-default"
},
searchToolbar: {
menu: "dropdown-menu",
menuItem: "",
menuItemButton: "dropdown-item",
operButton: "btn btn-xs btn-outline-secondary",
clearButton: "btn btn-xs btn-outline-secondary"
},
top: "ui-jqgrid-bootstrap-corner-top",
bottom: "ui-jqgrid-bootstrap-corner-bottom",
resizer: "ui-jqgrid-bootstrap"
}
},
htmlDecode: function (value) {
if (value && (value === " " ||
value === " " ||
(value.length === 1 && value.charCodeAt(0) === 160))) {
return "";
}
return !value ?
value :
String(value)
.replace(/>/g, ">")
.replace(/</g, "<")
.replace(/'/g, "'")
.replace(///g, "\/")
.replace(/'/g, "'")
.replace(///g, "\/")
.replace(/"/g, "\"")
.replace(/&/g, "&");
},
htmlEncode: function (value) {
// see https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet#RULE_.231_-_HTML_Escape_Before_Inserting_Untrusted_Data_into_HTML_Element_Content
return !value ?
value :
String(value)
.replace(/&/g, "&")
.replace(/"/g, """)
.replace(/'/g, "'")
.replace(/\//g, "/")
.replace(//g, ">");
},
oldEncodePostedData: function (value) {
return !value ?
value :
String(value)
.replace(/&/g, "&")
.replace(/"/g, """)
.replace(//g, ">");
},
oldDecodePostedData: function (value) {
if (value && (value === " " ||
value === " " ||
(value.length === 1 && value.charCodeAt(0) === 160))) {
return "";
}
return !value ?
value :
String(value)
.replace(/>/g, ">")
.replace(/</g, "<")
.replace(/"/g, "\"")
.replace(/&/g, "&");
},
clearArray: function (ar) {
// see http://jsperf.com/empty-javascript-array
while (ar.length > 0) {
ar.pop();
}
},
format: function (format) { //jqgformat
var args = $.makeArray(arguments).slice(1);
if (format == null) { format = ""; }
return format.replace(/\{(\d+)\}/g, function (m, i) {
return args[i];
});
},
template: function (format) { //jqgformat
var args = $.makeArray(arguments).slice(1), j, al = args.length;
if (format == null) {
format = "";
}
return format.replace(/\{([\w\-]+)(?:\:([\w\.]*)(?:\((\.*?)?\))?)?\}/g, function (m, i) {
var nmarr, k;
if (!isNaN(parseInt(i, 10))) {
return args[parseInt(i, 10)];
}
for (j = 0; j < al; j++) {
if ($.isArray(args[j])) {
nmarr = args[j];
k = nmarr.length;
while (k--) {
if (i === nmarr[k].nm) {
return nmarr[k].v;
}
}
}
}
});
},
msie: navigator.appName === "Microsoft Internet Explorer",
msiever: function () {
// Trident/4.0 - Internet Explorer 8,
// Trident/5.0 - Internet Explorer 9,
// Trident/6.0 - Internet Explorer 10
// Trident/7.0 - IE11
// Version tokens MSIE might not reflect the actual version of the browser
// If Compatibility View is enabled for a webpage or the browser mode is set to an earlier version
var rv = -1, match;
if (navigator.appName === "Microsoft Internet Explorer") {
match = /(MSIE) ([0-9]{1,}[.0-9]{0,})/.exec(navigator.userAgent);
if (match != null && match.length === 3) {
rv = parseFloat(match[2] || -1);
}
} else if (navigator.appName === "Netscape") {
match = /rv:([0-9]{1,}[.0-9]{0,})/.exec(navigator.userAgent);
if (match != null && match.length === 2) {
rv = parseFloat(match[1] || -1);
}
}
return rv;
},
fixMaxHeightOfDiv: function (height) {
// we place the fixing of maximal height in the method to allow easy
// to overwrite the method and to change the behaviour of jqGrid
// in case of usage virtual scrolling
if (navigator.appName === "Microsoft Internet Explorer") {
return Math.min(height, 1533917); // ??? 1022611
}
if (/(Firefox)/.exec(navigator.userAgent) != null) {
return Math.min(height, 17895696);
}
return height;
},
getRelativeRect: function (elem) {
var relativeTo = elem instanceof $ && elem.length > 0 ? elem[0] : elem,
relativeToOuterHeight = $(relativeTo).outerHeight(),
gbox = $(this).closest(".ui-jqgrid")[0],
rectRelativeTo, rectGbox;
if (!gbox) {
return { top: 0, left: 0 };
}
rectRelativeTo = relativeTo.getBoundingClientRect != null ?
relativeTo.getBoundingClientRect() :
$(relativeTo).offset();
rectGbox = gbox.getBoundingClientRect != null ?
gbox.getBoundingClientRect() :
$(gbox).offset();
return {
top: rectRelativeTo.top + relativeToOuterHeight - rectGbox.top,
//right: rectGbox.right - rectRelativeTo.right,
left: rectRelativeTo.left - rectGbox.left
};
},
getCellIndex: function (cell) {
var c = $(cell);
if (c.is("tr")) { return -1; }
c = (!c.is("td") && !c.is("th") ? c.closest("td,th") : c)[0];
if (c == null) { return -1; }
if (jgrid.msie) { return $.inArray(c, c.parentNode.cells); }
return c.cellIndex;
},
stripHtml: function (v) {
v = String(v);
if (v) {
v = v.replace(/<("[^"]*"|'[^']*'|[^'">])*>/gi, "");
return (v && v !== " " && v !== " ") ? v.replace(/"/g, "'") : "";
}
return v;
},
stripPref: function (pref, id) {
var obj = $.type(pref);
if (obj === "string" || obj === "number") {
pref = String(pref);
id = pref !== "" ? String(id).replace(String(pref), "") : id;
}
return id;
},
getRes: function (basePath, path) {
var pathParts = path.split("."), n = pathParts.length, i;
if (basePath == null) {
return undefined;
}
for (i = 0; i < n; i++) {
if (!pathParts[i]) {
return null;
}
basePath = basePath[pathParts[i]];
if (basePath === undefined) {
break;
}
if (typeof basePath === "string") {
return basePath;
}
}
return basePath;
},
parseDate: function (format, date, newformat, opts) {
// It seems that the code was "imported" by Tony from http://blog.stevenlevithan.com/archives/date-time-format
// Thus I include the reference to original
// Date Format 1.2.3 (c) 2007-2009 Steven Levithan MIT license
// The code can be found on https://github.com/felixge/node-dateformat/blob/master/lib/dateformat.js
// It would be probabbly good idea to support original date format additionally to the
// PHP data format used below.
var token = /\\.|[dDjlNSwzWFmMntLoYyaABgGhHisueIOPTZcrU]/g, dM, k, hl, timestamp = 0, offset = 0,
timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[\-+]\d{4})?)\b/g,
timezoneClip = /[^\-+\dA-Z]/g,
msMatch = ((typeof date === "string") ? date.match(/^\/Date\((([\-+])?[0-9]+)(([\-+])([0-9]{2})([0-9]{2}))?\)\/$/) : null),
pad = function (value, length) {
value = String(value);
length = parseInt(length, 10) || 2;
while (value.length < length) { value = "0" + value; }
return value;
},
ts = { m: 1, d: 1, y: 1970, h: 0, i: 0, s: 0, u: 0 },
h12To24 = function (ampm, h) {
if (ampm === 0) {
if (h === 12) { h = 0; }
} else {
if (h !== 12) { h += 12; }
}
return h;
},
getDefOptions = function (p, options) {
// It could be multiple sources for date properties used below.
// Let us we need to use srcformat. The highest priority have
// opts.srcformat if it is specified. If the srcformat is not
// specified of if opts is undefined then one should use
// $.jgrid.locales.de.formatter.date.srcformat, for example,
// where "de" part is an example of the locale of the grid
// ($t.p.locale). There as the third important case existing
// because of compatibility only. The old place for formatter.date.srcformat
// was $.jgrid.formatter.date.srcformat (without "locales.de" part
// in the middle). Now such option should be not used, but
// because of some code where the old code of jqGrid was customized
// using $.jgrid.formatter instead of $.jgrid.locales[locale].formatter,
// one have to take in consideration the case. If such setting exist
// then one should use it (should use $.jgrid.formatter.date.srcformat)
// BEFORE the new default $.jgrid.locales.de.formatter.date.srcformat.
// As the result sue should search for all below properties in 3 sources:
// first in opts || {}, second in
// ($.jgrid.formatter || {}).date || {}
// and finally, if $t.p != null && $t.p.locale != null, under
// $.jgrid.locales[$t.p.locale].formatter.date
// oder (it's the same, just rewritten) under
// ((locales[$t.p.locale] || {}).formatter || {}).date
var props = ["AmPm", "dayNames", "masks", "monthNames", "userLocalTime", "parseRe", "S", "srcformat"],
root1 = options || {},
root2 = (jgrid.formatter || {}).date || {},
root3 = ((locales[(p || $.jgrid.defaults).locale] || {}).formatter || {}).date,
iProp, nProps = props.length, result = {}, prop;
for (iProp = 0; iProp < nProps; iProp++) {
prop = props[iProp];
if (root1[prop] !== undefined) { // root1.hasOwnProperty(prop)
result[prop] = root1[prop];
} else if (root2[prop] !== undefined) {// root2.hasOwnProperty(prop)
result[prop] = root2[prop];
} else if (root3[prop] !== undefined) {// root3.hasOwnProperty(prop)
result[prop] = root3[prop];
}
}
return result;
};
//opts = $.extend({}, (jgrid.formatter || {}).date,
// $t.p != null ?
// jgrid.getRes(locales[$t.p.locale], "formatter.date") || {} :
// {},
// opts || {});
opts = getDefOptions(this.p, opts);
// old lang files
if (opts.parseRe === undefined) {
opts.parseRe = /[#%\\\/:_;.,\t\s\-]/;
}
if (opts.masks.hasOwnProperty(format)) { format = opts.masks[format]; }
if (date && date != null) {
if (!isNaN(date) && String(format).toLowerCase() === "u") {
//Unix timestamp
timestamp = new Date(parseFloat(date) * 1000);
} else if (!isNaN(date) && String(format).toLowerCase() === "u1000") {
// Milliseconds since the Unix Epoch (January 1 1970 00:00:00 GMT)
timestamp = new Date(parseFloat(date));
} else if (date.constructor === Date) {
timestamp = date;
// Microsoft date format support
} else if (msMatch !== null) {
timestamp = new Date(parseInt(msMatch[1], 10));
if (msMatch[3]) {
offset = Number(msMatch[5]) * 60 + Number(msMatch[6]);
offset *= ((msMatch[4] === "-") ? 1 : -1);
offset -= timestamp.getTimezoneOffset();
timestamp.setTime(Number(Number(timestamp) + (offset * 60 * 1000)));
}
} else {
//Support ISO8601Long that have Z at the end to indicate UTC timezone
if (opts.srcformat === "ISO8601Long" && date.charAt(date.length - 1) === "Z") {
offset -= (new Date()).getTimezoneOffset();
}
date = String(date).replace(/\T/g, "#").replace(/\t/, "%").split(opts.parseRe);
format = format.replace(/\T/g, "#").replace(/\t/, "%").split(opts.parseRe);
// parsing for month names and time
for (k = 0, hl = Math.min(format.length, date.length); k < hl; k++) {
switch (format[k]) {
case "M":
// A short textual representation of a month, three letters Jan through Dec
dM = $.inArray(date[k], opts.monthNames);
if (dM !== -1 && dM < 12) {
date[k] = dM + 1;
ts.m = date[k];
}
break;
case "F":
// A full textual representation of a month, such as January or March
dM = $.inArray(date[k], opts.monthNames, 12);
if (dM !== -1 && dM > 11) {
date[k] = dM + 1 - 12;
ts.m = date[k];
}
break;
case "n":
// Numeric representation of a month, without leading zeros 1 through 12
ts.m = parseInt(date[k], 10);
break;
case "j":
// Day of the month without leading zeros 1 to 31
ts.d = parseInt(date[k], 10);
break;
case "g":
// 12-hour format of an hour without leading zeros 1 through 12
ts.h = parseInt(date[k], 10);
break;
case "a":
// Lowercase Ante meridiem and Post meridiem am or pm
dM = $.inArray(date[k], opts.AmPm);
if (dM !== -1 && dM < 2 && date[k] === opts.AmPm[dM]) {
date[k] = dM;
ts.h = h12To24(date[k], ts.h);
}
break;
case "A":
// Uppercase Ante meridiem and Post meridiem AM or PM
dM = $.inArray(date[k], opts.AmPm);
if (dM !== -1 && dM > 1 && date[k] === opts.AmPm[dM]) {
date[k] = dM - 2;
ts.h = h12To24(date[k], ts.h);
}
break;
}
if (date[k] !== undefined && date[k] !== "" && !isNaN(date[k])) {
ts[format[k].toLowerCase()] = parseInt(date[k], 10);
}
}
if (ts.f) { ts.m = ts.f; }
if (ts.m === 0 && ts.y === 0 && ts.d === 0) {
return " ";
}
ts.m = parseInt(ts.m, 10) - 1;
var ty = ts.y;
if (ty >= 70 && ty <= 99) {
ts.y = 1900 + ts.y;
} else if (ty >= 0 && ty <= 69) {
ts.y = 2000 + ts.y;
}
timestamp = new Date(ts.y, ts.m, ts.d, ts.h, ts.i, ts.s, ts.u);
//Apply offset to show date as local time.
if (offset !== 0) {
timestamp.setTime(Number(Number(timestamp) + (offset * 60 * 1000)));
}
}
} else {
timestamp = new Date(ts.y, ts.m, ts.d, ts.h, ts.i, ts.s, ts.u);
}
if (opts.userLocalTime && offset === 0) {
offset -= (new Date()).getTimezoneOffset();
if (offset !== 0) {
timestamp.setTime(Number(Number(timestamp) + (offset * 60 * 1000)));
}
}
if (newformat === undefined) {
return timestamp;
}
if (opts.masks.hasOwnProperty(newformat)) {
newformat = opts.masks[newformat];
} else if (!newformat) {
newformat = "Y-m-d";
}
if (newformat.toLowerCase() === "u1000") {
return timestamp.getTime();
}
var hours = timestamp.getHours(), // a Number, from 0 to 23, representing the hour
i = timestamp.getMinutes(),
j = timestamp.getDate(),
n = timestamp.getMonth() + 1,
o = timestamp.getTimezoneOffset(),
s = timestamp.getSeconds(),
u = timestamp.getMilliseconds(),
w = timestamp.getDay(),
year = timestamp.getFullYear(), // a Number, representing four digits, representing the year. Examples: 1999 or 2003
dayOfWeek = (w + 6) % 7 + 1, // numeric representation of the day of the week. 1 (for Monday) through 7 (for Sunday)
z = (new Date(year, n - 1, j) - new Date(year, 0, 1)) / 86400000,
weekNumberOfYear = dayOfWeek < 5 ?
Math.floor((z + dayOfWeek - 1) / 7) + 1 :
Math.floor((z + dayOfWeek - 1) / 7) || ((new Date(year - 1, 0, 1).getDay() + 6) % 7 < 4 ? 53 : 52),
flags = {
// Day
d: pad(j), // Day of the month, 2 digits with leading zeros 01 to 31
D: opts.dayNames[w], // A textual representation of a day, three letters. Mon through Sun
j: j, // Day of the month without leading zeros 1 to 31
l: opts.dayNames[w + 7], // A full textual representation of the day of the week. Sunday through Saturday
N: dayOfWeek, // ISO-8601 numeric representation of the day of the week. 1 (for Monday) through 7 (for Sunday)
S: opts.S(j), // English ordinal suffix for the day of the month, 2 characters. st, nd, rd or th. Works well with j
w: w, // Numeric representation of the day of the week. 0 (for Sunday) through 6 (for Saturday)
z: z, // The day of the year (starting from 0). 0 through 365
// Week.
W: weekNumberOfYear, // ISO-8601 week number of year, weeks starting on Monday. Example: 42 (the 42nd week in the year)
// Month
F: opts.monthNames[n - 1 + 12], // A full textual representation of a month, such as January or March. January through December
m: pad(n), // Numeric representation of a month, with leading zeros. 01 through 12
M: opts.monthNames[n - 1], // A short textual representation of a month, three letters. Jan through Dec
n: n, // Numeric representation of a month, without leading zeros. 1 through 12
t: "?", // Number of days in the given month. 28 through 31
// Year
L: "?", // Whether it's a leap year. 1 if it is a leap year, 0 otherwise.
o: "?", // SO-8601 year number. This has the same value as Y, except that if the ISO week number (W) belongs to the previous or next year, that year is used instead. Examples: 1999 or 2003
Y: year, // A full numeric representation of a year, 4 digits. Examples: 1999 or 2003
y: String(year).substring(2), // A two digit representation of a year. Examples: 99 or 03
// Time
a: hours < 12 ? opts.AmPm[0] : opts.AmPm[1], // Lowercase Ante meridiem and Post meridiem: am or pm
A: hours < 12 ? opts.AmPm[2] : opts.AmPm[3], // Uppercase Ante meridiem and Post meridiem: AM or PM
B: "?", // Swatch Internet time 000 through 999
g: hours % 12 || 12, // 12-hour format of an hour without leading zeros 1 through 12
G: hours, // 24-hour format of an hour without leading zeros. 0 through 23
h: pad(hours % 12 || 12), // 12-hour format of an hour with leading zeros: 01 through 12
H: pad(hours), // 24-hour format of an hour with leading zeros: 00 through 23
i: pad(i), // Minutes with leading zeros: 00 to 59
s: pad(s), // Seconds, with leading zeros: 00 through 59
u: u, // Microseconds. Example: 654321
// Timezone
e: "?", // Timezone identifier. Examples: UTC, GMT, Atlantic/Azores
I: "?", // Whether or not the date is in daylight saving time. 1 if Daylight Saving Time, 0 otherwise.
O: (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4), // Difference to Greenwich time (GMT) in hours. Example: +0200
P: "?", // Difference to Greenwich time (GMT) with colon between hours and minutes. Example: +02:00
T: (String(timestamp).match(timezone) || [""]).pop().replace(timezoneClip, ""), // Timezone abbreviation. Examples: EST, MDT
Z: "?", // Timezone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive. -43200 through 50400
// Full Date/Time
c: "?", // ISO 8601 date. Example: 2004-02-12T15:19:21+00:00
r: "?", // RFC 2822 formatted date. Example: Thu, 21 Dec 2000 16:01:07 +0200
U: Math.floor(timestamp / 1000) // Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)
};
return newformat.replace(token, function ($0) {
return flags.hasOwnProperty($0) ? flags[$0] : $0.substring(1);
});
},
parseDateToNumber: function (format, date) {
var datetime = jgrid.parseDate.call(this, format, date);
// datetime could be the string " "
return datetime instanceof Date ? datetime.getTime() : 0;
},
jqID: function (sid) {
return String(sid).replace(/[!"#$%&'()*+,.\/:; <=>?@\[\\\]\^`{|}~]/g, "\\$&");
},
/**
* @param {COMPONENT_NAMES} componentName
*/
getGridComponentId: function (componentName) {
var self = this;
if (self.p == null || !self.p.id) {
return ""; // return empty string
}
var id = self.p.id;
switch (componentName) {
case COMPONENT_NAMES.GRID:
return id;
case COMPONENT_NAMES.GRID_BOX_DIV:
return "gbox_" + id;
case COMPONENT_NAMES.GRID_VIEW_DIV:
return "gview_" + id;
case COMPONENT_NAMES.DIALOG_ALERT_DIV: // footer/summary table
return "alertmod_" + id;
case COMPONENT_NAMES.COLUMN_RESIZER_DIV:
return "rs_m" + id;
case COMPONENT_NAMES.HEADER_SELECT_ALL_ROWS_CHECKBOX:
return "cb_" + id;
case COMPONENT_NAMES.SEARCH_OPERATION_MENU_UL:
return "sopt_menu";
default:
return ""; // return empty string
}
},
/**
* @param {COMPONENT_NAMES} componentName
*/
getGridComponentIdSelector: function (componentName) {
var id = jgrid.getGridComponentId.call(this, componentName);
return id ? "#" + jgrid.jqID(id) : "";
},
isHTMLElement: function (elem) {
// see http://stackoverflow.com/a/384380/315935
return (typeof HTMLElement === "object" || typeof HTMLElement === "function") ?
elem instanceof HTMLElement : //DOM2
elem != null && typeof elem === "object" && elem.nodeType === 1 && typeof elem.nodeName === "string";
},
/**
* @param {COMPONENT_NAMES} componentName
*/
getGridComponent: function (componentName, $p) {// , p1
var p;
if ($p instanceof $ || $p.length > 0) {
p = $p[0];
} else if (jgrid.isHTMLElement($p)) {
p = $p;
$p = $(p);
} else {
return $(); // return empty jQuery object
}
switch (componentName) {
case COMPONENT_NAMES.BODY_TABLE: // get body table from bDiv
return $p.hasClass("ui-jqgrid-bdiv") ? $p.children("div").children(".ui-jqgrid-btable") : $();
case COMPONENT_NAMES.HEADER_TABLE: // header table from bDiv
return $p.hasClass("ui-jqgrid-hdiv") ? $p.children("div").children(".ui-jqgrid-htable") : $();
case COMPONENT_NAMES.FOOTER_TABLE: // footer/summary table from sDiv
return $p.hasClass("ui-jqgrid-sdiv") ? $p.children("div").children(".ui-jqgrid-ftable") : $();
case COMPONENT_NAMES.FROZEN_HEADER_TABLE: // header table from bDiv
return $p.hasClass("ui-jqgrid-hdiv") ? $p.children(".ui-jqgrid-htable") : $();
case COMPONENT_NAMES.FROZEN_FOOTER_TABLE: // footer/summary table from sDiv
return $p.hasClass("ui-jqgrid-sdiv") ? $p.children(".ui-jqgrid-ftable") : $();
case COMPONENT_NAMES.BODY_DIV: // get bDiv of grid (bTable)
return $p.hasClass("ui-jqgrid-btable") && p.grid != null ? $(p.grid.bDiv) : $();
case COMPONENT_NAMES.HEADER_DIV: // get hDiv of grid (bTable)
return $p.hasClass("ui-jqgrid-btable") && p.grid != null ? $(p.grid.hDiv) : $();
case COMPONENT_NAMES.FOOTER_DIV: // get sDiv of grid (bTable)
return $p.hasClass("ui-jqgrid-btable") && p.grid != null ? $(p.grid.sDiv) : $();
//case "colHeader": // p should be iCol
// return !isNaN(p1) && p.grid != null && p.grid.headers != null && p.grid.headers[p1] != null ?
// $(p.grid.headers[p1].el) : $();
default:
return $(); // return empty jQuery object
}
},
fixScrollOffsetAndhBoxPadding: function () {
var self = this, grid = self.grid;
if (!grid) {
return;
}
var p = self.p, bDiv = grid.bDiv,
fixhBox = function (hDiv) {
var $hDivhBox = $(hDiv).children("div").first();
$hDivhBox.css($hDivhBox.hasClass("ui-jqgrid-hbox-rtl") ? "padding-left" : "padding-right", p.scrollOffset);
hDiv.scrollLeft = bDiv.scrollLeft;
};
if ($(bDiv).width() > 0) {
p.scrollOffset = (bDiv.offsetWidth - bDiv.clientWidth); // can be 0 if no scrollbar exist
// TODO: add detection of the width of vertical scroll bar if the grid is hidden
// at the moment of executing fixScrollOffsetAndhBoxPadding (for example inside of inactive jQuery UI Tab)
// one need just create close construction with visible:hidden style, add to body and get its width
fixhBox(grid.hDiv);
if (grid.sDiv) {
fixhBox(grid.sDiv);
}
}
},
mergeCssClasses: function () {
var args = $.makeArray(arguments), map = {}, i, j, ar, cssClass, classes = [];
for (i = 0; i < args.length; i++) {
ar = String(args[i]).replace(/[\t\r\n\f]/g, " ").split(" ");
for (j = 0; j < ar.length; j++) {
cssClass = ar[j];
if (cssClass !== "" && !map.hasOwnProperty(cssClass)) {
map[cssClass] = true;
classes.push(cssClass);
}
}
}
return classes.join(" ");
},
hasOneFromClasses: function (elem, classes) {
var $elem = $(elem),
arClasses = String(classes).replace(/[\t\r\n\f]/g, " ").split(" "),
n = arClasses.length,
i;
for (i = 0; i < n; i++) {
if ($elem.hasClass(arClasses[i])) {
return true;
}
}
return false;
},
hasAllClasses: function (elem, classes) {
// the current implementation of jQuery.hasClass can work with multiple classes,
// but the classes HAVE TO BE in exact the same order. jQuery.hasClass just
// search for classes using indexOf.
// (see https://github.com/jquery/jquery/blob/1.11.3/src/attributes/classes.js#L143-L154)
// Thus we cant's use it to test whether an element has the list of all the classes
// and we introduces the helper method hasAllClasses
var $elem = $(elem),
arClasses = String(classes).replace(/[\t\r\n\f]/g, " ").split(" "),
n = arClasses.length,
i;
for (i = 0; i < n; i++) {
if (!$elem.hasClass(arClasses[i])) {
return false;
}
}
return true;
},
detectRowEditing: function (rowid) {
//var i, savedRowInfo, tr, self = this, rows = self.rows, p = self.p, isFunction = $.isFunction;
if (!this.grid || this.p == null || this.p.editingInfo == null || this.p.editingInfo[rowid] == null) {
return null; // this is not a grid or the row is not editing now
}
return this.p.editingInfo[rowid];
},
// The method returns jQuery wrapper with the cell (
) of the row.
// It can return jQuery wrapper with two cells in case of usage frozen data:
// one cell of the main grid and another cell with the corresponding cell from the frozen body table
getCell: function (tr, iCol) {
var grid = this.grid, p = this.p, frozenRows, $td;
if (!grid || !p) { return $(); } // not a grid
if (tr instanceof $ || tr.length > 0) {
tr = tr[0]; // unwrap jQuery object to DOM element
}
if (!((typeof HTMLTableRowElement === "object" || typeof HTMLTableRowElement === "function") && tr instanceof HTMLTableRowElement) || tr.cells == null) { // the line will be failed in IE7
return $(); // return empty jQuery object
}
$td = $(tr.cells[iCol]);
frozenRows = grid.fbRows;
return frozenRows != null && iCol < frozenRows[0].cells.length ?
$td.add(frozenRows[tr.rowIndex].cells[iCol]) :
$td;
},
getDataFieldOfCell: function (tr, iCol) {
var p = this.p, $td = jgrid.getCell.call(this, tr, iCol), $dataElement;
if (p.treeGrid && $td.children("div.tree-wrap").length > 0) {
$td = $td.children("span.cell-wrapperleaf,span.cell-wrapper");
}
if (p.colModel[iCol].autoResizable) {
$dataElement = $td.children("span." + p.autoResizing.wrapperClassName);
if ($dataElement.length === 0) { // for example, td is in editing mode
$dataElement = $td;
}
} else {
$dataElement = $td;
}
return $dataElement;
},
enumEditableCells: function (tr, mode, callback) {
var self = this, grid = self.grid, rows = self.rows, p = self.p;
if (grid == null || rows == null || p == null || tr == null || tr.rowIndex == null || !tr.id || !$.isFunction(callback)) {
return null; // this is not a grid or tr is not tr
}
var iCol, colModel = p.colModel, nCol = colModel.length, cm, nm, options, id, pos, item,
isEditable, iRow = tr.rowIndex, td, $dataElement, dataWidth,
frozenRows = grid.fbRows, frozen = frozenRows != null,
trFrozen = frozen ? frozenRows[iRow] : null;
// normalize tr if required
if (frozen/* && !$.contains(self, tr)*/) {
// The event could be inside of frozen div.
// Thus tr could be the same as trFrozen
// We normalize it based on the rowIndex.
tr = self.rows[iRow];
}
for (iCol = 0; iCol < nCol; iCol++) {
cm = colModel[iCol];
nm = cm.name;
if (nm !== "cb" && nm !== "subgrid" && nm !== "rn") {
if (frozen && !cm.frozen) {
frozen = false;
}
td = (frozen ? trFrozen : tr).cells[iCol];
$dataElement = $(td);
if (!$dataElement.hasClass("not-editable-cell")) {
dataWidth = $dataElement.width();
if (p.treeGrid === true && nm === p.ExpandColumn) {
dataWidth -= $dataElement.children("div.tree-wrap").outerWidth();
$dataElement = $dataElement.children("span.cell-wrapperleaf,span.cell-wrapper").first();
} else {
dataWidth = 0; // we can test it in the callback and use width:auto in the case
}
id = stripPref(p.idPrefix, tr.id);
options = {
rowid: tr.id,
id: id,
iCol: iCol,
iRow: iRow,
cmName: nm,
cm: cm,
mode: mode,
td: td,
tr: tr,
trFrozen: trFrozen,
dataElement: $dataElement[0],
dataWidth: dataWidth
};
if (p.datatype === "local") {
pos = p._index[id];
item = pos != null ? p.data[pos] : undefined;
if (item) {
options.item = item;
}
}
if (!cm.edittype) { cm.edittype = "text"; }
if (((p.editingInfo[tr.id] || {}).editable || {}).hasOwnProperty(nm)) {
// if the cell in already editing
isEditable = p.editingInfo[tr.id].editable[nm];
} else {
isEditable = cm.editable;
isEditable = $.isFunction(isEditable) ?
isEditable.call(self, options) :
isEditable;
}
if (isEditable === true || isEditable === "hidden") {
options.editable = isEditable;
if (callback.call(self, options) === false) { break; }
}
}
}
}
},
getEditedValue: function ($dataFiled, cm, valueText, editable) {
var result, checkBoxValues, newformat, $field, values, texts,
formatoptions = cm.formatoptions || {}, editoptions = cm.editoptions || {},
customValue = editoptions.custom_value,
nameSelector = "[name=" + jgrid.jqID(cm.name) + "]", $t = this, $self = $($t);
if (editable === "hidden" || editable === "readonly") {
// the implementation from the next line can be improved
return $($t).jqGrid("getCell", $dataFiled.closest("tr.jqgrow").attr("id"), cm.name);
}
switch (cm.edittype) {
case "checkbox":
checkBoxValues = ["Yes", "No"];
if (typeof editoptions.value === "string") {
checkBoxValues = editoptions.value.split(":");
}
result = $dataFiled.find("input[type=checkbox]").is(":checked") ? checkBoxValues[0] : checkBoxValues[1];
break;
case "text":
case "password":
case "textarea":
case "button":
$field = $dataFiled.find("input" + nameSelector + ",textarea" + nameSelector);
result = $field.val();
if ($field.prop("type") === "date" && String(result).split("-").length === 3) {
newformat = formatoptions.newformat || $self.jqGrid("getGridRes", "formatter.date.newformat");
result = jgrid.parseDate.call($t, "Y-m-d", result, newformat);
}
break;
case "select":
$field = $dataFiled.find("select option:selected");
if (editoptions.multiple) {
values = [];
texts = [];
$field.each(function () {
values.push($(this).val());
texts.push($(this).text());
});
result = values.join(",");
valueText.text = texts.join(",");
} else {
result = $field.val();
valueText.text = $field.text();
}
valueText.value = result;
break;
case "custom":
try {
if ($.isFunction(customValue)) {
result = customValue.call($t, $dataFiled.find(".customelement"), "get");
if (result === undefined) {
throw "e2";
}
} else {
throw "e1";
}
} catch (e) {
var errorText, infoDialog = jgrid.info_dialog,
getRes = function (path) { $self.jqGrid("getGridRes", path); };
switch (String(e)) {
case "e1":
errorText = "function 'custom_value' " + getRes("edit.msg.nodefined");
break;
case "e2":
break;
default:
errorText = e.message;
break;
}
if (infoDialog && $.isFunction(infoDialog)) {
infoDialog.call($t, getRes("errors.errcap"), errorText, getRes("edit.bClose"));
} else {
($.isFunction(defaults.fatalError) ? defaults.fatalError : alert)(errorText);
}
}
break;
default:
result = $dataFiled.find("*" + nameSelector).text();
break;
}
return result;
},
guid: 1,
uidPref: "jqg",
randId: function (prefix) {
return (prefix || jgrid.uidPref) + (jgrid.guid++);
},
getAccessor: function (obj, expr) {
var ret, p, prm = [], i;
if ($.isFunction(expr)) { return expr(obj); }
if (obj != null && obj.hasOwnProperty(expr)) {
return obj[expr];
}
try {
if (typeof expr === "string") {
prm = expr.split(".");
}
i = prm.length;
if (i) {
ret = obj;
while (ret != null && i--) {
p = prm.shift();
if (ret.hasOwnProperty(p)) {
ret = ret[p];
} else {
ret = undefined;
}
}
}
} catch (ignore) { }
return ret;
},
getXmlData: function (obj, expr, returnObj) {
var m = typeof expr === "string" ? expr.match(/^(.*)\[(\w+)\]$/) : null;
if ($.isFunction(expr)) { return expr(obj); }
if (m && m[2]) {
// m[2] is the attribute selector
// m[1] is an optional element selector
// examples: "[id]", "rows[page]"
return m[1] ? $(m[1], obj).attr(m[2]) : $(obj).attr(m[2]);
}
if (obj === undefined) {
//alert("expr");
return undefined;
}
// !!! one should never use another form $(expr, obj) if obj could be undefined
// In the case the $(expr, obj) could be $("someString") and jQuery can
// parse it as array of characters ($("someString").length will be "someString".length) !!!
// The problem take place if expr is not string object, but object new String("someString").
// The problem can exist if one use $.each with array of strings.
// The "this" inside of $.each is the string converted to object.
var ret = $(obj).find(expr);
if (returnObj) { return ret; }
//$(expr, obj).filter(":last"); // we use ":last" to be more compatible with old version of jqGrid
return ret.length > 0 ? $(ret).text() : undefined;
},
cellWidth: function () {
// TODO: use all other classes in grid. Probably one should set the visibility explicitly to show (display:block)
var $testDiv = $("
";
},
addRowNum = function (pos, irow, pG, rN) {
var v = (parseInt(pG, 10) - 1) * parseInt(rN, 10) + 1 + irow;
return "
" + v + "
";
};
if (rowIndex <= 1) { p.rowIndexes = {}; }
if ((p.datatype === "local" && !p.deselectAfterSort) || p.multiPageSelection) { selected = true; }
if (adjust) { rn *= adjust + 1; }
for (i = 0; i < Math.min(len, rn); i++) {
idr = ids[i];
rd = items[i];
cells = cellsToDisplay != null ? cellsToDisplay[i] : rd;
altr = rcnt === 1 ? 0 : rcnt; // probably rowIndex should be used instead
cn1 = (altr + i) % 2 === 1 ? cn : "";
if (selected) {
if (p.multiselect) {
selr = ($.inArray(idr, p.selarrrow) !== -1);
if (selr && p.selrow === null) { p.selrow = idr; }
} else {
selr = (idr === p.selrow);
}
} else {
selr = false;
}
iStartTrTag = rowData.length;
rowData.push(""); // it will be replaced. See rowData[iStartTrTag] below
for (j = 0; j < p.colModel.length; j++) {
cmName = p.colModel[j].name;
switch (cmName) {
case "rn":
rowData.push(addRowNum(j, i, p.page, p.rowNum));
break;
case "cb":
rowData.push(addMulti(idr, j, i, selr, rd));
break;
case "subgrid":
rowData.push($j.addSubGridCell.call($self, j, i + rcnt, idr, rd));
break;
default:
rowData.push(addCell(idr, rd[cmName], j, i + rcnt, cells, rd));
}
}
if (p.grouping) {
if ($j.groupingPrepare && !grp._locgr) {
$j.groupingPrepare.call($self, rd, i);
}
hiderow = $.isFunction(grp.groupCollapse) ?
grp.groupCollapse.call(self, {
group: grp.groups[grp.groups.length - 1],
rowid: idr,
data: rd
}) :
grp.groupCollapse;
}
rowData[iStartTrTag] = self.constructTr(idr, hiderow, cn1, rd, cells, selr);
rowData.push("");
p.rowIndexes[idr] = rowIndex;
rowIndex++;
//TODO: fix p.rowIndexes in case of usage grouping.
if (p.grouping) {
// we save the rowData in the array grpdata first.
// grpdata will collect HTML fragments of all rows of data
// of the current group. Later we call groupingRender, which
// will insert additional grouping row and concatinate all
// the HTML fragments of all rows of the group.
grpdata.push(rowData);
rowData = []; // the data for rendering are moved in grpdata
}
if (rowData.length > p.maxItemsToJoin) {
rowData = [rowData.join("")];
}
}
if (p.grouping && $j.groupingRender) {
if (readAllInputData) {
grp._locgr = true;
}
rowData = [$j.groupingRender.call($self, grpdata, rn)];
jgrid.clearArray(grpdata); //grpdata = null;
}
return rowData;
},
fillSelectOptions: function (elem, value, sep, delim, isMultiple, valuesToSelect) {
var i, so, sv, ov, optionInfo, optionInfos = [], isSelected, key, ovm,
isNoFilterValueExist = false,
mapFunc = function (n, ii) { if (ii > 0) { return n; } };
if (!value) { return; }
if (typeof value === "function") {
value = value();
}
if (typeof value === "string") {
so = value.split(delim);
for (i = 0; i < so.length; i++) {
sv = so[i].split(sep);
if (sv.length > 2) {
sv[1] = $.map(sv, mapFunc).join(sep);
}
optionInfos.push({
value: sv[0],
innerHtml: sv[1],
selectValue: $.trim(sv[0]),
selectText: $.trim(sv[1]),
selected: false
});
if (sv[0] === "") {
isNoFilterValueExist = true;
}
}
} else if (typeof value === "object") {
for (key in value) {
if (value.hasOwnProperty(key)) {
optionInfos.push({
value: key,
innerHtml: value[key],
selectValue: $.trim(key),
selectText: $.trim(value[key]),
selected: false
});
}
if (key === "") {
isNoFilterValueExist = true;
}
}
}
if (typeof valuesToSelect === "string") {
ovm = isMultiple ?
$.map(valuesToSelect.split(","), function (n) { return $.trim(n); }) :
[$.trim(valuesToSelect)];
valuesToSelect = $.trim(valuesToSelect);
// mark selection
// 1) first by value
for (i = 0; i < optionInfos.length; i++) {
optionInfo = optionInfos[i];
if (!isMultiple && optionInfo.selectValue === valuesToSelect) {
optionInfo.selected = true;
isSelected = true;
}
if (isMultiple && $.inArray(optionInfo.selectValue, ovm) > -1) {
optionInfo.selected = true;
isSelected = true;
}
}
// 2) when no selection by value, then by text
if (!isSelected) {
for (i = 0; i < optionInfos.length; i++) {
optionInfo = optionInfos[i];
if (!isMultiple && optionInfo.selectText === valuesToSelect) {
optionInfo.selected = true;
}
if (isMultiple && $.inArray(optionInfo.selectText, ovm) > -1) {
optionInfo.selected = true;
}
}
}
}
for (i = 0; i < optionInfos.length; i++) {
optionInfo = optionInfos[i];
ov = document.createElement("option");
ov.value = optionInfo.value;
ov.innerHTML = optionInfo.innerHtml;
if (optionInfo.selected) {
ov.selected = true;
}
elem.appendChild(ov);
}
return isNoFilterValueExist;
},
getMethod: function (name) {
// this should be $.jgrid object
return this.getAccessor($.fn.jqGrid, name);
},
extend: function (methods) {
$.extend($.fn.jqGrid, methods);
if (!this.no_legacy_api) {
$.fn.extend(methods);
}
}
});
var clearArray = jgrid.clearArray, jqID = jgrid.jqID,
getGridComponentIdSelector = jgrid.getGridComponentIdSelector, getGridComponentId = jgrid.getGridComponentId,
getGridComponent = jgrid.getGridComponent, stripPref = jgrid.stripPref, randId = jgrid.randId,
getAccessor = jgrid.getAccessor, convertOnSaveLocally = jgrid.convertOnSaveLocally,
stripHtml = jgrid.stripHtml, htmlEncode = jgrid.htmlEncode, htmlDecode = jgrid.htmlDecode,
mergeCssClasses = jgrid.mergeCssClasses, hasOneFromClasses = jgrid.hasOneFromClasses,
feedback = function () {
// short form of $.jgrid.feedback to save usage this.p as the first parameter
var args = $.makeArray(arguments);
args.unshift("");
args.unshift("");
args.unshift(this.p);
return jgrid.feedback.apply(this, args);
};
/**
* @param {(string|Object)} pin
*/
$.fn.jqGrid = function (pin) {
var $j = $.fn.jqGrid, fn;
if (typeof pin === "string") {
fn = $j[pin];
if (!fn) {
throw ("jqGrid - No such method: " + pin);
}
return fn.apply(this, $.makeArray(arguments).slice(1));
}
return this.each(function () {
if (this.grid) { return; }
// TODO: verify that pin.locale exists in locales. If it's not exist then change it to
// en-US or some other which exist
var ts = this, localData, localDataStr, $self0 = $(ts),
isFunction = $.isFunction, isArray = $.isArray, extend = $.extend, inArray = $.inArray,
trim = $.trim, each = $.each, setSelection = $j.setSelection, getGridRes = $j.getGridRes,
fatalErrorFunction = isFunction(defaults.fatalError) ? defaults.fatalError : alert,
locale = pin.locale || defaults.locale || "en-US",
direction = locales[locale] != null && typeof locales[locale].isRTL === "boolean" ? (locales[locale].isRTL ? "rtl" : "ltr") : "ltr",
iconSet = pin.iconSet || defaults.iconSet || ((pin.guiStyle || defaults.guiStyle) === "bootstrap" || (pin.guiStyle || defaults.guiStyle) === "bootstrapPrimary" ? "glyph" : "jQueryUI"),
guiStyle = pin.guiStyle || defaults.guiStyle || "jQueryUI",
getIcon = function (path) {
//return jgrid.getIconRes(iconSet, path);
return $j.getIconRes.call(ts, path);
},
getGuiStyles = function (path, jqClasses) {
return $self0.jqGrid("getGuiStyles", path, jqClasses);
},
stdLoadError = function (jqXHR, textStatus, errorThrown) {
if (textStatus !== "abort" && errorThrown !== "abort") {
var contentType = jqXHR.getResponseHeader ("Content-Type"),
message = jqXHR.responseText || "",
processHtmlError = function (msg) {
var div = document.createElement("div"), scripts, i, bodyMatch;
// get body only and strip all scripts
bodyMatch = /]*>([\s\S]*)<\/body\s*>/gim.exec(msg);
div.innerHTML = bodyMatch != null && bodyMatch.length === 2 ?
bodyMatch[1] : msg;
scripts = div.getElementsByTagName("script");
i = scripts.length;
while (i--) {
scripts[i].parentNode.removeChild(scripts[i]);
}
// strip html headers and get the body only
msg = div.innerHTML;
try {
// remove HTML, if it has no text
if ($.trim($(msg).text()) === "") {
msg = "";
}
}
catch (ignore) {}
return msg;
},
processJsonError = function (msg) {
try {
var errorInfo = $.parseJSON(msg), errorMessages = [], errorProp;
for (errorProp in errorInfo) {
if (errorInfo.hasOwnProperty(errorProp) && errorProp !== "StackTrace") {
errorMessages.push(errorProp + ": " + errorInfo[errorProp]);
}
}
msg = errorMessages.join(" ");
}
catch (ignore) {}
return msg;
};
if (contentType === "text/html") {
message = processHtmlError(message);
} else if (contentType === "application/json") {
message = processJsonError(message);
} else if (contentType === "text/plain") {
// try to process as JSON
message = processJsonError(message);
}
if (jqXHR.status !== 500 && jqXHR.status !== 0) {
// add the header
message = (textStatus || errorThrown) +
(errorThrown && (errorThrown !== textStatus) ? ": " + errorThrown : "") +
" " + jqXHR.status + " " + jqXHR.statusText +
(message !== "" ? "" : "") +
message;
}
$self0.jqGrid("displayErrorMessage", message || textStatus || errorThrown);
}
};
if (pin == null) {
pin = { datatype: "local" };
}
if (pin.datastr !== undefined && isArray(pin.datastr)) {
localDataStr = pin.datastr;
pin.datastr = []; // don't clear the array, just change the value of datastr property
}
if (pin.data !== undefined) {
localData = pin.data;
pin.data = []; // don't clear the array, just change the value of data property
}
if (jgrid.formatter == null || jgrid.formatter.unused == null) {
// detect old locale file grid.locale-XX.js are included (without DEEP extend).
fatalErrorFunction("CRITICAL ERROR!!!\n\n\nOne uses probably\n\n\t$.extend($.jgrid.defaults, {...});\n\nto set default settings of jqGrid instead of the usage the DEEP version of jQuery.extend (with true as the first parameter):\n\n\t$.extend(true, $.jgrid.defaults, {...});\n\nOne other possible reason:\n\nyou included some OLD version of language file (grid.locale-en.js for example) AFTER jquery.jqGrid.min.js. For example all language files of jqGrid 4.7.0 uses non-deep call of jQuery.extend.\n\n\nSome options of jqGrid could still work, but another one will be broken.");
}
if (pin.datatype === undefined && pin.dataType !== undefined) {
// fix the bug in the usage of dataType instead of datatype
pin.datatype = pin.dataType;
delete pin.dataType;
}
if (pin.mtype === undefined && pin.type !== undefined) {
// fix the bug in the usage of type instead of mtype
pin.mtype = pin.type;
delete pin.type;
}
ts.p = { iconSet: iconSet }; // minimal initializing to get icons with respect of getIconRes method
var p = extend(true,
{
//url: "",
height: "auto",
page: 1,
rowNum: 20,
maxRowNum: 10000,
pagingDuringEditing: "prevent", // "prevent", "cancel" or "save"
sortingDuringEditing: "prevent", // "prevent", "cancel" or "save"
reloadingDuringEditing: "prevent", // "prevent", "cancel" or "save"
autoresizeOnLoad: false,
columnsToReResizing: [],
autoResizing: {
wrapperClassName: "ui-jqgrid-cell-wrapper",
//widthOfVisiblePartOfSortIcon: pin.iconSet === "fontAwesome" ? 13 : 12,
minColWidth: 33,
maxColWidth: 300,
adjustGridWidth: true, // shrinkToFit and widthOrg (no width option or width:"auto" during jqGrid creation will be detected) will be used additionally with adjustGridWidth
compact: false,
fixWidthOnShrink: false
},
doubleClickSensitivity: 250,
minResizingWidth: 10,
rowTotal: null,
records: 0,
pager: "",
pgbuttons: true,
pginput: true,
colModel: [],
additionalProperties: [],
arrayReader: [],
rowList: [],
colNames: [],
sortorder: "asc",
threeStateSort: false,
//showOneSortIcon: pin.showOneSortIcon !== undefined ? pin.showOneSortIcon :
// pin.iconSet === "fontAwesome" ? true : false, // hide or set ui-state-disabled class on the other icon
sortname: "",
//datatype: pin.datatype !== undefined ? pin.datatype : // datatype parameter are specified - use it
// localData !== undefined || pin.url == null ? "local" : // data parameter specified or no url are specified
// pin.jsonReader != null && typeof pin.jsonReader === "object" ? "json" : "xml", // if jsonReader are specified - use "json". In all other cases - use "xml"
mtype: "GET",
altRows: false,
selarrrow: [],
savedRow: [],
editingInfo: {},
shrinkToFit: true,
xmlReader: {},
//jsonReader: {},
subGrid: false,
subGridModel: [],
reccount: 0,
lastpage: 0,
lastsort: 0,
selrow: null,
singleSelectClickMode: "toggle",
selectOnContextMenu: true,
beforeSelectRow: null,
onSelectRow: null,
onSortCol: null,
ondblClickRow: null,
onRightClickRow: null,
onPaging: null,
onSelectAll: null,
onInitGrid: null,
loadComplete: null,
gridComplete: null,
loadError: stdLoadError,
loadBeforeSend: null,
afterInsertRow: null,
beforeRequest: null,
beforeProcessing: null,
onHeaderClick: null,
viewrecords: false,
loadonce: false,
forceClientSorting: false,
multiselect: false,
multikey: false,
editurl: "clientArray",
search: false,
caption: "",
hidegrid: true,
hiddengrid: false,
useUnformattedDataForCellAttr: true,
postData: {},
userData: {},
treeGrid: false,
treeGridModel: "nested",
treeReader: {},
treeANode: -1,
ExpandColumn: null,
tree_root_level: 0,
prmNames: {
page: "page",
rows: "rows",
sort: "sidx",
order: "sord",
search: "_search",
filters: "filters",
nd: "nd",
id: "id",
idold: "idOld",
oper: "oper",
editoper: "edit",
addoper: "add",
deloper: "del",
subgridid: "id",
npage: null,
totalrows: "totalrows"
},
forceFit: false,
gridstate: "visible",
cellEdit: false,
iCol: -1,
iRow: -1,
//cellsubmit: pin.cellurl === undefined ? "clientArray" : "remote",
nv: 0,
loadui: "enable",
toolbar: [false, ""],
scroll: false,
multiboxonly: false,
deselectAfterSort: true,
resetPageAfterSort: true,
multiPageSelection: false,
selectAllMode: "filtered",
scrollrows: false,
autowidth: false,
scrollOffset: 18,
cellLayout: 5,
subGridWidth: 16,
multiselectWidth: 16,
multiselectPosition: "left",
gridview: true,
rownumWidth: 25,
rownumbers: false,
pagerpos: "center",
footerrow: false,
userDataOnFooter: false,
hoverrows: true,
altclass: "ui-priority-secondary",
viewsortcols: [false, "vertical", true],
resizeclass: "",
autoencode: true, // one can use false to have better backwards compatibility, but one have to prevent Cross Site Scripting (XSS) manually
autoEncodeOnEdit: false,
remapColumns: [],
cmNamesInputOrder: [],
ajaxGridOptions: {},
direction: direction,
toppager: false,
headertitles: false,
scrollTimeout: 40,
maxItemsToJoin: 32768,
data: [],
lastSelectedData: [],
quickEmpty: "quickest", // false, true or "quickest"
/** @dict */
_index: {},
indexByColumnData: {},
dataIndexById: {},
iColByName: {},
iPropByName: {},
reservedColumnNames: ["rn", "cb", "subgrid"],
grouping: false,
groupingView: {
groupField: [],
groupOrder: [],
groupText: [],
groupColumnShow: [],
groupSummary: [],
showSummaryOnHide: false,
useDefaultValuesOnGrouping: true,
summary: [],
displayField: [],
groupSummaryPos: [],
formatDisplayField: [],
_locgr: false,
commonIconClass: getIcon("grouping.common"),
plusicon: getIcon("grouping.plus"),
minusicon: getIcon("grouping.minus")
},
ignoreCase: true,
cmTemplate: {},
idPrefix: "",
iconSet: iconSet, // "fontAwesome" or "jQueryUI" or some custom value
guiStyle: guiStyle,
locale: locale,
multiSort: false,
showSortOrder: true,
sortOrderPosition: "afterSortIcons", // "afterSortIcons", "beforeSortIcons"
multiSortOrder: "lastClickedFirstSorted", // "lastClickedLastSorted", "lastClickedFirstSorted" or callback reodering function
maxSortColumns: 3,
treeIcons: {
commonIconClass: getIcon("treeGrid.common"),
plusLtr: getIcon("treeGrid.plusLtr"),
plusRtl: getIcon("treeGrid.plusRtl"),
minus: getIcon("treeGrid.minus"),
leaf: getIcon("treeGrid.leaf")
}
},
//locales[locale].defaults,
defaults,
{
navOptions: extend(true, {
commonIconClass: getIcon("nav.common"),
editicon: getIcon("nav.edit"),
addicon: getIcon("nav.add"),
delicon: getIcon("nav.del"),
searchicon: getIcon("nav.search"),
refreshicon: getIcon("nav.refresh"),
viewicon: getIcon("nav.view"),
saveicon: getIcon("nav.save"),
cancelicon: getIcon("nav.cancel"),
buttonicon: getIcon("nav.newbutton")
}, jgrid.nav || {}),
actionsNavOptions: extend(true, {
commonIconClass: getIcon("actions.common"),
editicon: getIcon("actions.edit"),
delicon: getIcon("actions.del"),
saveicon: getIcon("actions.save"),
cancelicon: getIcon("actions.cancel")
}, jgrid.actionsNav || {}),
formEditing: extend(true, {
commonIconClass: getIcon("form.common"),
prevIcon: getIcon("form.prev"),
nextIcon: getIcon("form.next"),
saveicon: [true, "left", getIcon("form.save")],
closeicon: [true, "left", getIcon("form.undo")]
}, jgrid.edit || {}),
searching: extend(true, {
commonIconClass: getIcon("search.common"),
findDialogIcon: getIcon("search.search"),
resetDialogIcon: getIcon("search.reset"),
queryDialogIcon: getIcon("search.query")
}, jgrid.search || {}),
formViewing: extend(true, {
commonIconClass: getIcon("form.common"),
prevIcon: getIcon("form.prev"),
nextIcon: getIcon("form.next"),
closeicon: [true, "left", getIcon("form.cancel")]
}, jgrid.view || {}),
formDeleting: extend(true, {
commonIconClass: getIcon("form.common"),
delicon: [true, "left", getIcon("form.del")],
cancelicon: [true, "left", getIcon("form.cancel")]
}, jgrid.del || {})
},
pin || {}),
getRes = function (path) {
return getGridRes.call($self0, path);
},
getDef = function (path) {
var gridParam = jgrid.getRes(p, path);
return gridParam !== undefined ? gridParam : getGridRes.call($self0, "defaults." + path);
};
// set dynamic options
p.recordpos = p.recordpos || (p.direction === "rtl" ? "left" : "right");
p.autoResizing.widthOfVisiblePartOfSortIcon =
p.autoResizing.widthOfVisiblePartOfSortIcon !== undefined ?
p.autoResizing.widthOfVisiblePartOfSortIcon :
(p.iconSet === "fontAwesome" ? 13 : 12);
//p.showOneSortIcon = p.showOneSortIcon !== undefined ? p.showOneSortIcon :
// (p.iconSet === "fontAwesome" ? true : false);
p.datatype = p.datatype !== undefined ? p.datatype : // datatype parameter are specified - use it
localData !== undefined || p.url == null ? "local" : // data parameter specified or no url are specified
p.jsonReader != null && typeof p.jsonReader === "object" ? "json" : "xml"; // if jsonReader are specified - use "json". In all other cases - use "xml"
p.jsonReader = p.jsonReader || {};
p.url = p.url || "";
p.cellsubmit = p.cellsubmit !== undefined ? p.cellsubmit :
p.cellurl === undefined ? "clientArray" : "remote";
p.gridview = p.gridview !== undefined ? p.gridview : (p.afterInsertRow == null);
if (localData !== undefined) {
p.data = localData;
pin.data = localData;
}
if (localDataStr !== undefined) {
p.datastr = localDataStr;
pin.datastr = localDataStr;
}
if (ts.tagName.toUpperCase() !== "TABLE") {
fatalErrorFunction("Element is not a table!");
return;
}
if (ts.id === "") {
$self0.attr("id", randId());
}
if (document.documentMode !== undefined) { // IE only
if (document.documentMode <= 5) {
fatalErrorFunction("Grid can not be used in this ('quirks') mode!");
return;
}
}
$self0.empty().attr("tabindex", "0");
ts.p = p;
p.id = ts.id;
p.idSel = "#" + jqID(ts.id);
p.gBoxId = getGridComponentId.call(ts, COMPONENT_NAMES.GRID_BOX_DIV); // gbox id like "gbox_list" or "gbox_my.list"
p.gBox = getGridComponentIdSelector.call(ts, COMPONENT_NAMES.GRID_BOX_DIV); // gbox selector like "#gbox_list" or "#gbox_my\\.list"
p.gViewId = getGridComponentId.call(ts, COMPONENT_NAMES.GRID_VIEW_DIV); // gview id like "gview_list" or "gview_my.list"
p.gView = getGridComponentIdSelector.call(ts, COMPONENT_NAMES.GRID_VIEW_DIV); // gview selector like "#gview_list" or "#gview_my\\.list"
p.rsId = getGridComponentId.call(ts, COMPONENT_NAMES.COLUMN_RESIZER_DIV); // vertical div inside of gbox which will be seen on resizing of columns
p.rs = getGridComponentIdSelector.call(ts, COMPONENT_NAMES.COLUMN_RESIZER_DIV); // vertical div inside of gbox which will be seen on resizing of columns
p.cbId = getGridComponentId.call(ts, COMPONENT_NAMES.HEADER_SELECT_ALL_ROWS_CHECKBOX); // "cb_" +id
p.cb = getGridComponentIdSelector.call(ts, COMPONENT_NAMES.HEADER_SELECT_ALL_ROWS_CHECKBOX); // "cb_" +id
var fixScrollOffsetAndhBoxPadding = jgrid.fixScrollOffsetAndhBoxPadding,
buildColNameMap = function (colModel) {
var m = {}, i, n = colModel.length;
for (i = 0; i < n; i++) {
m[colModel[i].name] = i;
}
return m;
},
buildEmptyIndexedColumnMap = function () {
var m = {}, i, colModel = p.colModel, n = colModel.length, cm;
for (i = 0; i < n; i++) {
cm = colModel[i];
if (cm.createColumnIndex ||
(p.createColumnIndex && cm.createColumnIndex !== false) ||
(cm.stype === "select" && (cm.searchoptions || {}).generateValue) ||
(cm.edittype === "select" && (cm.editoptions || {}).generateValue)) {
m[colModel[i].name] = {};
}
}
return m;
},
buildAddPropMap = function (additionalProperties) {
var m = {}, i, n = additionalProperties.length, addPropInfo;
for (i = 0; i < n; i++) {
addPropInfo = additionalProperties[i];
m[typeof addPropInfo === "string" ? addPropInfo : addPropInfo.name] = i;
}
return m;
},
rebuildRowIndexes = function () {
var rowIndexes = {}, row, i;
this.p.rowIndexes = rowIndexes;
for (i = 0; i < this.rows.length; i++) {
row = this.rows[i];
if ($(row).hasClass("jqgrow")) {
rowIndexes[row.id] = row.rowIndex;
}
}
},
buildArrayReader = function () {
var i, colModel = p.colModel, cmNamesInputOrder = p.cmNamesInputOrder,
additionalProperties = p.additionalProperties, n = cmNamesInputOrder.length, arrayReaderInfos,
name, index, order;
p.arrayReaderInfos = {};
arrayReaderInfos = p.arrayReaderInfos;
for (order = 0; order < n; order++) {
name = cmNamesInputOrder[order];
if (inArray(name, p.reservedColumnNames) < 0 && !arrayReaderInfos.hasOwnProperty(name)) {
index = p.iColByName[name];
if (index !== undefined) {
arrayReaderInfos[name] = { name: name, index: index, order: order, type: 0 }; // INPUT_NAME_TYPE.COL_NAME
} else {
index = p.iPropByName[name];
if (index !== undefined) {
arrayReaderInfos[name] = { name: name, index: index, order: order, type: 1 };// INPUT_NAME_TYPE.ADDITIONAL_PROPERTY
} else if (name === (p.prmNames.rowidName || "rowid")) {
arrayReaderInfos[name] = { index: index, type: 2 };// INPUT_NAME_TYPE.ROWID
}
}
}
}
n = colModel.length;
for (i = 0; i < n; i++) {
name = colModel[i].name;
if (inArray(name, p.reservedColumnNames) < 0 && !arrayReaderInfos.hasOwnProperty(name)) {
arrayReaderInfos[name] = { name: name, index: i, order: order, type: 0 };// INPUT_NAME_TYPE.COL_NAME
order++;
}
}
n = additionalProperties.length;
for (i = 0; i < n; i++) {
name = additionalProperties[i];
if (name != null && !arrayReaderInfos.hasOwnProperty(name)) {
if (typeof name === "object" && $.type(name.name) === "string") {
name = name.name;
}
arrayReaderInfos[name] = { name: name, index: i, order: order, type: 1 };
order++;
}
}
},
myResizerClickHandler = function (e) {
var pageX = $(this).data("pageX");
if (pageX) {
pageX = String(pageX).split(";");
pageX = pageX[pageX.length - 1];
$(this).data("pageX", pageX + ";" + e.pageX);
} else {
$(this).data("pageX", e.pageX);
}
},
intNum = function (val, defval) {
val = parseInt(val, 10);
if (isNaN(val)) { return defval || 0; }
return val;
},
grid = {
headers: [],
cols: [],
footers: [],
// Some properties will be created dynamically on demand
// cDiv
// uDiv
// topDiv
// hDiv
// bDiv
// sDiv
// ubDiv
// fhDiv
// fbDiv
// fsDiv
// width
// newWidth
// resizing
// scrollTop
// timer
// prevRowHeight
dragStart: function (i, x, y, $th) {
var self = this, $bDiv = $(self.bDiv), gridOffset = $bDiv.closest(p.gBox).offset(),
// it's better to use exact position of the border on the right of the current header
startX = $th.offset().left + (p.direction === "rtl" ? 0 : self.headers[i].width + (jgrid.cell_width ? 0 : intNum(p.cellLayout, 0)) - 2);
self.resizing = { idx: i, startX: startX, sOL: startX, moved: false, delta: startX - x.pageX };
self.curGbox = $(p.rs);
self.curGbox.prependTo("body"); // change the parent to be able to move over the ranges of the gBox
self.curGbox.css({ display: "block", left: startX, top: y[1] + gridOffset.top + 1, height: y[2] });
self.curGbox.css("height", (y[2] - (self.curGbox.outerHeight() - self.curGbox.height())) + "px");
self.curGbox.data("idx", i);
self.curGbox.data("delta", startX - x.pageX);
myResizerClickHandler.call(this.curGbox, x);
feedback.call(getGridComponent(COMPONENT_NAMES.BODY_TABLE, $bDiv)[0], "resizeStart", x, i);
document.onselectstart = function () { return false; };
$(document)
.on("mousemove.jqGrid", function (e) {
if (grid.resizing) {
grid.dragMove(e);
return false;
}
})
.on("mouseup.jqGrid" + p.id, function () {
if (grid.resizing) {
grid.dragEnd();
return false;
}
});
},
dragMove: function (x) {
var self = this, resizing = self.resizing;
if (resizing) {
var diff = x.pageX + resizing.delta - resizing.startX, headers = self.headers, h = headers[resizing.idx],
newWidth = p.direction === "ltr" ? h.width + diff : h.width - diff, hn, nWn,
minResizingWidth = ((p.colModel[resizing.idx] || {}).autoResizing || {}).minColWidth || p.minResizingWidth;
resizing.moved = true;
if (newWidth > minResizingWidth) {
if (self.curGbox == null) {
self.curGbox = $(p.rs);
}
self.curGbox.css({ left: resizing.sOL + diff });
if (p.forceFit === true) {
hn = headers[resizing.idx + p.nv];
nWn = p.direction === "ltr" ? hn.width - diff : hn.width + diff;
if (nWn > p.autoResizing.minColWidth) {
h.newWidth = newWidth;
hn.newWidth = nWn;
}
} else {
self.newWidth = p.direction === "ltr" ? p.tblwidth + diff : p.tblwidth - diff;
h.newWidth = newWidth;
}
}
}
},
resizeColumn: function (idx, skipCallbacks, skipGridAdjustments) {
var self = this, headers = self.headers, footers = self.footers, h = headers[idx], hn, nw = h.newWidth || h.width,
$bTable = getGridComponent(COMPONENT_NAMES.BODY_TABLE, self.bDiv), $hTable = getGridComponent(COMPONENT_NAMES.HEADER_TABLE, self.hDiv),
hCols = $hTable.children("thead").children("tr").first()[0].cells;
nw = parseInt(nw, 10);
p.colModel[idx].width = nw;
h.width = nw;
hCols[idx].style.width = nw + "px";
self.cols[idx].style.width = nw + "px";
if (self.fbRows) {
$(self.fbRows[0].cells[idx]).css("width", nw);
$(getGridComponent(COMPONENT_NAMES.FROZEN_HEADER_TABLE, self.fhDiv)[0].rows[0].cells[idx]).css("width", nw);
if (p.footerrow) {
$(getGridComponent(COMPONENT_NAMES.FROZEN_FOOTER_TABLE, self.fsDiv)[0].rows[0].cells[idx]).css("width", nw);
}
}
if (footers.length > 0) { footers[idx].style.width = nw + "px"; }
if (skipGridAdjustments !== true) {
fixScrollOffsetAndhBoxPadding.call($bTable[0]);
}
if (p.forceFit === true) {
hn = headers[idx + p.nv]; // next visible th
nw = hn.newWidth || hn.width;
hn.width = nw;
hCols[idx + p.nv].style.width = nw + "px";
self.cols[idx + p.nv].style.width = nw + "px";
if (footers.length > 0) { footers[idx + p.nv].style.width = nw + "px"; }
p.colModel[idx + p.nv].width = nw;
} else {
p.tblwidth = self.newWidth || p.tblwidth;
//$bTable.css("width", p.tblwidth + "px");
//getGridComponent(COMPONENT_NAMES.HEADER_TABLE, self.hDiv).css("width", p.tblwidth + "px");
if (skipGridAdjustments !== true) {
self.hDiv.scrollLeft = self.bDiv.scrollLeft;
if (p.footerrow) {
//getGridComponent(COMPONENT_NAMES.FOOTER_TABLE, self.sDiv).css("width", p.tblwidth + "px");
self.sDiv.scrollLeft = self.bDiv.scrollLeft;
}
}
}
if (!p.autowidth && (p.widthOrg === undefined || p.widthOrg === "auto" || p.widthOrg === "100%") && skipGridAdjustments !== true) {
$j.setGridWidth.call($bTable, self.newWidth + p.scrollOffset, false);
}
if (!skipCallbacks) {
feedback.call($bTable[0], "resizeStop", nw, idx);
}
},
dragEnd: function () {
var self = this;
self.hDiv.style.cursor = "default";
if (self.resizing) {
if (self.resizing !== null && self.resizing.moved === true) {
$(self.headers[self.resizing.idx].el).removeData("autoResized");
self.resizeColumn(self.resizing.idx, false);
}
$(p.rs).removeData("pageX");
self.resizing = false;
setTimeout(function () {
$(p.rs).css("display", "none")
.prependTo(p.gBox); // restore the parent
}, p.doubleClickSensitivity);
}
self.curGbox = null;
document.onselectstart = function () { return true; };
$(document).off("mousemove.jqGrid mouseup.jqGrid" + p.id);
},
populateVisible: function () {
var self = this, $self = $(self), gridSelf = self.grid, bDiv = gridSelf.bDiv, $bDiv = $(bDiv);
if (gridSelf.timer) { clearTimeout(gridSelf.timer); }
gridSelf.timer = null;
var dh = $bDiv.height();
if (!dh) { return; }
var firstDataRow, rh;
if (self.rows.length) {
try {
firstDataRow = self.rows[1]; // self.rows[0] is cols row (the first row (.jqgfirstrow)) used only to set column width
rh = firstDataRow ? $(firstDataRow).outerHeight() || gridSelf.prevRowHeight : gridSelf.prevRowHeight;
} catch (pv) {
rh = gridSelf.prevRowHeight;
}
}
if (!rh) { return; }
gridSelf.prevRowHeight = rh;
var rn = p.rowNum;
gridSelf.scrollTop = bDiv.scrollTop;
var scrollTop = gridSelf.scrollTop;
var ttop = Math.round($self.position().top) - scrollTop;
var tbot = ttop + $self.height();
var div = rh * rn;
var page, npage, empty;
if (tbot < dh && ttop <= 0 &&
(p.lastpage === undefined || (parseInt((tbot + scrollTop + div - 1) / div, 10) || 0) <= p.lastpage)) {
npage = parseInt((dh - tbot + div - 1) / div, 10) || 1;
if (tbot >= 0 || npage < 2 || p.scroll === true) {
page = (Math.round((tbot + scrollTop) / div) || 0) + 1;
ttop = -1;
} else {
ttop = 1;
}
}
if (ttop > 0) {
page = (parseInt(scrollTop / div, 10) || 0) + 1;
npage = (parseInt((scrollTop + dh) / div, 10) || 0) + 2 - page;
empty = true;
}
if (npage) {
if (p.lastpage && (page > p.lastpage || p.lastpage === 1 || (page === p.page && page === p.lastpage))) {
return;
}
if (gridSelf.hDiv.loading) {
gridSelf.timer = setTimeout(function () { gridSelf.populateVisible.call(self); }, p.scrollTimeout);
} else {
p.page = page;
if (empty) {
gridSelf.selectionPreserver.call(self);
gridSelf.emptyRows.call(self, false, false);
}
gridSelf.populate.call(self, npage);
}
}
},
scrollGrid: function () { // this must be bDiv
if (p.scroll) {
var scrollTop = this.scrollTop;
// save last scrollTop of bDiv as property of grid object
if (grid.scrollTop === undefined) { grid.scrollTop = 0; }
if (scrollTop !== grid.scrollTop) {
grid.scrollTop = scrollTop;
if (grid.timer) { clearTimeout(grid.timer); }
grid.timer = setTimeout(function () { grid.populateVisible.call(ts); }, p.scrollTimeout);
}
}
grid.hDiv.scrollLeft = this.scrollLeft;
if (p.footerrow) {
grid.sDiv.scrollLeft = this.scrollLeft;
}
return false;
},
selectionPreserver: function () {
var self = this, $self = $(self), sr = p.selrow, sra = p.selarrrow ? $.makeArray(p.selarrrow) : null,
bDiv = self.grid.bDiv, left = bDiv.scrollLeft,
restoreSelection = function () {
var i;
p.selrow = null;
if (!p.multiPageSelection) {
clearArray(p.selarrrow); // p.selarrrow = [];
if (p.multiselect && sra && sra.length > 0) {
for (i = 0; i < sra.length; i++) {
if (sra[i] !== sr) {
setSelection.call($self, sra[i], false, null);
}
}
}
if (sr) {
setSelection.call($self, sr, false, null);
}
}
bDiv.scrollLeft = left;
$self.off(".selectionPreserver", restoreSelection);
};
$self.on("jqGridGridComplete.selectionPreserver", restoreSelection);
}
};
ts.grid = grid;
feedback.call(ts, "beforeInitGrid");
p.iColByName = buildColNameMap(p.colModel);
p.iPropByName = buildAddPropMap(p.additionalProperties);
// TODO: replace altclass : "ui-priority-secondary",
// set default buttonicon : "ui-icon-newwin" of navButtonAdd: fa-external-link, fa-desktop or other
// change the order in $.extend to allows to set icons using $.jgrid (for example $.jgrid.nav). It will be ovewritten currently by p.navOptions which we set above.
jgrid.msie = jgrid.msiever() > 0;
var gv = $(""),
isMSIE = jgrid.msie, dir;
p.direction = trim(p.direction.toLowerCase());
if (inArray(p.direction, ["ltr", "rtl"]) === -1) { p.direction = "ltr"; }
dir = p.direction;
$(gv).insertBefore(ts);
$self0.removeClass("scroll").appendTo(gv);
var eg = $("");
$(eg).attr({ "id": p.gBoxId, "dir": dir }).insertBefore(gv);
$(gv).attr("id", p.gViewId).appendTo(eg);
$("").insertBefore(gv);
$("
" + getDef("loadtext") + "
").insertBefore(gv);
$self0.attr({ "role": "presentation", "aria-labelledby": "gbox_" + ts.id });
var sortkeys = ["shiftKey", "altKey", "ctrlKey"],
// for reading of array of items from the input data it's required to know the
// mapping of input items to the column names (colModel[iCol].name items).
// The function normalizeRemapColumns converts p.remapColumns to p.cmNamesInputOrder and fills
// p.cmNamesInputOrder with the names colModel items.
// The function should be called only if no p.cmNamesInputOrder is specified
normalizeRemapColumns = function () {
// offset is the number of columns in colModel which should be skipped in calculation of the mapping
// offset is the number of columns from the list "rn", "cb", "subgrid".
// The index 0 in the p.remapColumns means the first column after the "rn", "cb", "subgrid"
var remapColumns = p.remapColumns, colModel = p.colModel, nCol = colModel.length, cmNames = [], i, remappedCmNames,
name;
for (i = 0; i < nCol; i++) {
name = colModel[i].name;
if (inArray(name, p.reservedColumnNames) < 0) {
cmNames.push(name);
}
}
// it's important to remark that the numbers in remapColumns or in
// jsonReder, localReader, xmlReader are based on the position of column
// in colModel BEFORE adding columns "rn", "cb", "subgrid"
if (remapColumns != null) {
// now we should remap items in cmNames corresponds to the indexes from p.remapColumns array
remappedCmNames = cmNames.slice(); // make copy of cmNames array
for (i = 0; i < remapColumns.length; i++) {
cmNames[i] = remappedCmNames[remapColumns[i]];
}
}
p.cmNamesInputOrder = cmNames;
},
stripGridPrefix = function (rowId) {
return stripPref(p.idPrefix, rowId);
},
formatCol = function (pos, rowInd, tv, rawObject, rowId, rdata) {
var cm = p.colModel[pos], cellAttrFunc,
rPrefix = cm.autoResizable ? "" : "",
// see https://github.com/free-jqgrid/jqGrid/issues/74#issuecomment-107675796
// we will cut formatted string like "193,81"
// to substring "193,81". The formatting (comma, point, dollar and so on) still stay.
unwrappedCellValue = cm.autoResizable ? tv.substring(rPrefix.length, tv.length - "".length) : tv,
cellValue = p.useUnformattedDataForCellAttr && rdata != null ?
rdata[cm.name] :
(cm.autoResizable ? unwrappedCellValue : tv),
result, classes = cm.classes,
styleValue = cm.align ? "text-align:" + cm.align + ";" : "",
attrStr, matches, value, tilteValue,
encodeAttr = function (v) {
return typeof v === "string" ? v.replace(/'/g, "'") : v;
},
rest = " aria-describedby='" + p.id + "_" + cm.name + "'";
if (cm.hidden === true) { styleValue += "display:none;"; }
if (rowInd === 0) {
styleValue += "width: " + grid.headers[pos].width + "px;";
} else if (isFunction(cm.cellattr) || (typeof cm.cellattr === "string" && jgrid.cellattr != null && isFunction(jgrid.cellattr[cm.cellattr]))) {
cellAttrFunc = isFunction(cm.cellattr) ? cm.cellattr : jgrid.cellattr[cm.cellattr];
attrStr = cellAttrFunc.call(ts, rowId, cellValue, rawObject, cm, rdata, unwrappedCellValue);
if (typeof attrStr === "string") {
// ??? probably one can create object with properties from the attrStr
// and then to use one common function with constructTr to combine the default
// properties with the properties used in cellattr and rowattr.
// Probably one could use $.extend with the most attributes. The exception are
// only class and style attributes which hold multi-values with " " or ";" as separator
attrStr = attrStr.replace(/\n/g, "
");
while (true) {
// we have to use ? in the construction ([^\2]*?) to have non-greedy (lazy, minimal) matching
// so that we will find the FIRST closing quote instead of default the LAST matching.
// TODO: more common regex for the attribute name.
// See http://www.w3.org/TR/html-markup/syntax.html#syntax-attributes:
// Attribute names must consist of one or more characters other than the space
// characters, U+0000 NULL, """, "'", ">", "/", "=", the control characters,
// and any characters that are not defined by Unicode.
// An important example is attribute name with "-" in the middle: "data-sometext"
matches = /^\s*(\w+[\w|\-]*)\s*=\s*([\"|\'])(.*?)\2(.*)/.exec(attrStr);
if (matches === null || matches.length < 5) {
if (!tilteValue && cm.title) {
tilteValue = cellValue;
}
return rest + " style='" + encodeAttr(styleValue) + "'" +
(classes ? " class='" + encodeAttr(classes) + "'" : "") +
(tilteValue ? " title='" + encodeAttr(tilteValue) + "'" : "");
}
value = matches[3];
attrStr = matches[4];
switch (matches[1].toLowerCase()) { // attribute name
case "class":
// if some special characters are inside of class value there MUST be escaped
// so we can use any quote characters (' or ") around the call value.
// So we don't need to save quote used in class attribute
if (classes) {
classes += " " + value;
} else {
classes = value;
}
break;
case "title":
//quotedTilteValue = quote + value + quote;
tilteValue = value;
break;
case "style":
styleValue += value;
break;
default:
// matches[2] is quote
rest += " " + matches[1] + "=" + matches[2] + value + matches[2];
break;
}
}
}
}
result = styleValue !== "" ? "style='" + styleValue + "'" : "";
result += (classes !== undefined ? (" class='" + classes + "'") : "") + ((cm.title && cellValue) ? (" title='" + stripHtml(tv).replace(/'/g, "'") + "'") : "");
result += rest;
return result;
},
cellVal = function (val) {
return val == null || val === "" ? " " : (p.autoencode ? htmlEncode(val) : String(val));
},
normalizeTreeGridProperties = function (ldat) {
var treeReader = p.treeReader,
loaded = treeReader.loaded,
isLeaf = treeReader.leaf_field,
expanded = treeReader.expanded_field,
getBool = function (val) {
return val === true || val === "true" || val === "1";
};
if (p.treeGridModel === "nested" && !ldat[isLeaf]) {
var lft = parseInt(ldat[treeReader.left_field], 10),
rgt = parseInt(ldat[treeReader.right_field], 10);
ldat[isLeaf] = (rgt === lft + 1) ? true : false;
}
if (ldat[loaded] !== undefined) {
ldat[loaded] = getBool(ldat[loaded]);
}
ldat[isLeaf] = getBool(ldat[isLeaf]);
ldat[expanded] = getBool(ldat[expanded]);
// the next line is suspected. The local data which missing loaded property
// can be be changed to have expanded=false
// we comment it.
//ldat[expanded] = ldat[expanded] && (ldat[loaded] || ldat[loaded] === undefined);
},
formatter = function (rowId, cellval, colpos, rwdat, act, rdata) {
var cm = p.colModel[colpos], v;
if (cm.formatter !== undefined) {
rowId = String(p.idPrefix) !== "" ? stripGridPrefix(rowId) : rowId;
var opts = { rowId: rowId, colModel: cm, gid: p.id, pos: colpos, rowData: rdata || rwdat };
if (isFunction(cm.cellBuilder)) {
v = cm.cellBuilder.call(ts, cellval, opts, rwdat, act);
} else if (isFunction(cm.formatter)) {
v = cm.formatter.call(ts, cellval, opts, rwdat, act);
} else if ($.fmatter) {
v = $.fn.fmatter.call(ts, cm.formatter, cellval, opts, rwdat, act);
} else {
v = cellVal(cellval);
}
} else {
v = cellVal(cellval);
}
v = cm.autoResizable && cm.formatter !== "actions" ? "" + v + "" : v;
if (p.treeGrid && act !== "edit" && ((p.ExpandColumn == null && colpos === 0) || (p.ExpandColumn === cm.name))) {
if (rdata == null) { rdata = p.data[p._index[rowId]]; }
var curLevel = parseInt(rdata[p.treeReader.level_field] || 0, 10), levelOffset = 18,
rootLevel = parseInt(p.tree_root_level, 10),
lftpos = rootLevel === 0 ? curLevel : curLevel - 1,
isLeaf = rdata[p.treeReader.leaf_field],
isExpanded = rdata[p.treeReader.expanded_field],
icon = rdata[p.treeReader.icon_field],
iconClass = isLeaf ?
((icon != null && icon !== "") ? icon : p.treeIcons.leaf) + " tree-leaf" :
(isExpanded ? p.treeIcons.minus + " tree-minus" : p.treeIcons.plus + " tree-plus");
//normalizeTreeGridProperties(rdata); // ??? don't needed more probably
if (!isLeaf && icon && typeof icon === "string") {
var icons = icon.split(",");
if (icons.length === 2) {
iconClass = isExpanded ? icons[0] : icons [1];
}
}
v = "
" +
"" +
v + "";
}
return v;
},
emptyRows = function (scroll, locdata) {
var self = this, bDiv = grid.bDiv,
frozenTable = grid.fbDiv != null ?
grid.fbDiv.children(".ui-jqgrid-btable")[0] : null,
removeRows = function (table) {
if (!table) { return; }
var tableRows = table.rows, firstrow = tableRows[0];
if (p.deepempty) {
if (tableRows) { $(tableRows).slice(1).remove(); }
} else if (p.quickEmpty) {
if (p.quickEmpty === "quickest") {
table.replaceChild(document.createElement("tbody"), table.tBodies[0]);
table.firstChild.appendChild(firstrow);
} else {
while (tableRows.length > 1) { // skip deliting of the first row
table.deleteRow(tableRows.length - 1);
}
}
} else {
$(table.firstChild).empty().append(firstrow);
}
};
$(self).off(".jqGridFormatter");
removeRows(self);
removeRows(frozenTable);
if (scroll && p.scroll) {
$(bDiv.firstChild).css({ height: "auto" });
$(bDiv.firstChild.firstChild).css({ height: 0, display: "none" });
if (bDiv.scrollTop !== 0) {
bDiv.scrollTop = 0;
}
}
if (locdata === true && p.treeGrid) {
clearArray(p.data); //p.data = [];
clearArray(p.lastSelectedData); //p.lastSelectedData = [];
p._index = {};
p.dataIndexById = {};
p.indexByColumnData = {};
}
p.rowIndexes = {};
p.iRow = -1;
p.iCol = -1;
//$(self.grid.headers).each(function () { $(this.el).removeData("autoResized"); });
},
addItemDataToColumnIndex = function (rd, id) {
var cmName, v;
for (cmName in p.indexByColumnData) {
if (p.indexByColumnData.hasOwnProperty(cmName)) {
v = rd[cmName];
if (rd.hasOwnProperty(cmName) && v !== undefined && v !== "") {
// rd[cmName] is the value, which need be saved in p.indexByColumnData[cmName]
if (p.ignoreCase) {
v = String(v).toLowerCase();
}
if (p.indexByColumnData[cmName][v] === undefined) {
p.indexByColumnData[cmName][v] = {};
}
p.indexByColumnData[cmName][v][id] = rd[cmName];
if (p.dataIndexById[id] === undefined) {
p.dataIndexById[id] = {};
}
if (p.dataIndexById[id][cmName] === undefined) {
p.dataIndexById[id][cmName] = {};
}
p.dataIndexById[id][cmName][v] = p.indexByColumnData[cmName][v];
}
}
}
},
removeItemDataFromColumnIndex = function (id) {
var cmName, columnIndex, v, index = p.dataIndexById[id];
if (index == null) {
return;
}
for (cmName in index) {
if (index.hasOwnProperty(cmName)) {
columnIndex = index[cmName];
for (v in columnIndex) {
if (columnIndex.hasOwnProperty(v)) {
delete p.indexByColumnData[cmName][v][id];
if ($.isEmptyObject(p.indexByColumnData[cmName][v])) {
delete p.indexByColumnData[cmName][v];
}
}
}
}
}
delete p.dataIndexById[id];
},
normalizeData = function () {
var data = p.data, dataLength = data.length, i, cur, cells, idName, idIndex, v, rd, id,
localReader = p.localReader, additionalProperties = p.additionalProperties,
cellName = localReader.cell, cmName, isArrayCells, addProp, info,
arrayReaderInfos = p.arrayReaderInfos;
if (p.datatype !== "local" || localReader.repeatitems !== true) {
if (p.treeGrid) {
for (i = 0; i < dataLength; i++) {
normalizeTreeGridProperties(data[i]);
}
}
return; // nothing to do
}
idName = p.keyName === false ?
(isFunction(localReader.id) ? localReader.id.call(ts, data) : localReader.id) :
p.keyName;
if (!isNaN(idName)) {
idIndex = Number(idName);
/*for (cmName in arrayReaderInfos) {
if (arrayReaderInfos.hasOwnProperty(cmName)) {
info = arrayReaderInfos[cmName];
if (info.order === idIndex) {
idName = info.name;
break;
}
}
}*/
} else if (!isFunction(idName)) {
if (p.arrayReaderInfos[idName] != null) {
idIndex = p.arrayReaderInfos[idName].order;
}
}
for (i = 0; i < dataLength; i++) {
cur = data[i];
cells = cellName ? getAccessor(cur, cellName) || cur : cur;
isArrayCells = isArray(cells);
rd = {};
for (cmName in arrayReaderInfos) {
if (arrayReaderInfos.hasOwnProperty(cmName)) {
info = arrayReaderInfos[cmName];
v = getAccessor(cells, isArrayCells ? info.order : info.name);
if (info.type === 1) { // additional property
addProp = additionalProperties[info.index];
if (addProp != null && isFunction(addProp.convert)) {
v = addProp.convert(v, cells);
}
}
if (v !== undefined) {
rd[cmName] = v;
}
}
}
// read id.
if (rd[idName] !== undefined) {
// in case of p.keyName or if there exist column with the same id name
// probably one should test only for rd[p.keyName] !== undefined
// and get rd[p.keyName] below, but the probability that the user
// wanted to use the column rd[idName] as the rowid seemd me
// higher as the opposite case.
// the id should be already read in p.keyName column.
// One need generate id only if the input data had no id
id = rd[idName] !== undefined ? rd[idName] : randId(); //id = br + i;
} else {
id = getAccessor(cur, isArray(cur) ? idIndex : idName);
if (id === undefined) {
id = getAccessor(cells, isArray(cells) ? idIndex : idName);
}
if (id === undefined) {
id = randId(); //id = br + i;
}
}
id = String(id);
rd[localReader.id] = id; //p.idPrefix + id;
// the next two line are the most important!
// one should consider to remove true parameter to improve the performance !!!
if (p.treeGrid) { normalizeTreeGridProperties(rd); }
extend(data[i], rd); // extend(true, data[i], rd);
}
},
refreshIndex = function () {
var datalen = p.data.length, idname, i, val, item;
if (p.keyName === false || (p.loadonce && p.dataTypeOrg)) {
idname = p.localReader.id;
} else {
idname = p.keyName;
}
p._index = {};
p.dataIndexById = {};
p.indexByColumnData = buildEmptyIndexedColumnMap();
for (i = 0; i < datalen; i++) {
item = p.data[i];
val = getAccessor(item, idname);
if (val === undefined) {
val = String(randId()); //String(i + 1);
if (item[idname] === undefined) {
item[idname] = val;
}
}
p._index[val] = i;
addItemDataToColumnIndex.call(this, item, val);
}
},
constructTr = function (id, hide, altClass, rd, cur, selected) {
var tabindex = "-1", restAttr = "", attrName, style = hide ? "display:none;" : "", self = this,
classes = getGuiStyles("gridRow", "jqgrow ui-row-" + p.direction) + (altClass ? " " + altClass : "") + (selected ? " " + getGuiStyles("states.select") : ""),
rowAttrObj = $(self).triggerHandler("jqGridRowAttr", [rd, cur, id]);
if (typeof rowAttrObj !== "object") {
rowAttrObj = isFunction(p.rowattr) ? p.rowattr.call(self, rd, cur, id) :
(typeof p.rowattr === "string" && jgrid.rowattr != null && isFunction(jgrid.rowattr[p.rowattr]) ?
jgrid.rowattr[p.rowattr].call(self, rd, cur, id) : {});
}
if (rowAttrObj != null && !$.isEmptyObject(rowAttrObj)) {
if (rowAttrObj.hasOwnProperty("id")) {
id = rowAttrObj.id;
delete rowAttrObj.id;
}
if (rowAttrObj.hasOwnProperty("tabindex")) {
tabindex = rowAttrObj.tabindex;
delete rowAttrObj.tabindex;
}
if (rowAttrObj.hasOwnProperty("style")) {
style += rowAttrObj.style;
delete rowAttrObj.style;
}
if (rowAttrObj.hasOwnProperty("class")) {
classes += " " + rowAttrObj["class"];
delete rowAttrObj["class"];
}
// don't allow to change role attribute
try { delete rowAttrObj.role; } catch (ignore) { }
for (attrName in rowAttrObj) {
if (rowAttrObj.hasOwnProperty(attrName)) {
restAttr += " " + attrName + "=" + rowAttrObj[attrName];
}
}
}
if (p.treeGrid) {
if (parseInt(rd[p.treeReader.level_field], 10) !== parseInt(p.tree_root_level, 10)) {
var pn = $j.getNodeParent.call($(this), rd),
expan = pn && pn.hasOwnProperty(p.treeReader.expanded_field) ?
pn[p.treeReader.expanded_field] : true;
if (!expan && !hide) {
// TODO: append ";" to style if required
style += "display:none;";
}
}
}
return "
";
},
finalizationFormatters = function () {
var i, formatName, fmatter = $.fn.fmatter;
for (i = 0; i < p.colModel.length; i++) {
formatName = p.colModel[i].formatter;
if (typeof formatName === "string" && fmatter != null &&
isFunction(fmatter[formatName]) && isFunction(fmatter[formatName].pageFinalization)) {
fmatter[formatName].pageFinalization.call(this, i);
}
}
},
fillOrClearCellBuilder = function (clear, act) {
var i, cm, colModel = p.colModel, n = colModel.length, opt,
autoencodeCellBuilder = function (v) {
return v == null || v === "" ? " " : htmlEncode(v);
},
simpleCellBuilder = function (v) {
return v == null || v === "" ? " " : String(v);
};
for (i = 0; i < n; i++) {
cm = colModel[i];
cm.cellBuilder = null;
if (!clear) {
opt = { colModel: cm, gid: p.id, pos: i };
if (cm.formatter === undefined) {
cm.cellBuilder = p.autoencode ? autoencodeCellBuilder : simpleCellBuilder;
} else if (typeof cm.formatter === "string" && $.fn.fmatter != null && isFunction($.fn.fmatter.getCellBuilder)) {
cm.cellBuilder = $.fn.fmatter.getCellBuilder.call(ts, cm.formatter, opt, act || "add");
} else if (isFunction(cm.getCellBuilder)) {
cm.cellBuilder = cm.getCellBuilder.call(ts, opt, act || "add");
}
}
}
},
readInput = function (data, rcnt, more, adjust) {
var self = this, $self = $(self), startReq = new Date(), datatype = p.datatype,
// readAllInputData shows that one should read ALL input items, not only the current page of data
readAllInputData = (datatype !== "local" && p.loadonce) || datatype === "xmlstring" || datatype === "jsonstring",
isXML = (datatype === "xmlstring" || datatype === "xml") && $.isXMLDoc(data),
locid = "_id_", dataReader = p.localReader, fieldReader = getAccessor;
if (data) {
if (datatype === "xml" && !isXML) {
return;
}
if (p.treeANode === -1 && !p.scroll) {
grid.emptyRows.call(self, false, true);
rcnt = 1;
} else {
rcnt = rcnt > 1 ? rcnt : 1;
}
} else {
// in case of usage TreeGrid for example
return;
}
if (readAllInputData) {
clearArray(p.data); //p.data = [];
clearArray(p.lastSelectedData); //p.lastSelectedData = [];
p._index = {};
if (p.grouping && p.groupingView != null) {
p.groupingView.groups = [];
p.groupingView._locgr = false;
}
p.localReader.id = locid; // consider to place the statement in if (p.treeGrid) {...}
}
p.reccount = 0;
switch (datatype) {
case "xml":
case "xmlstring":
dataReader = p.xmlReader;
fieldReader = jgrid.getXmlData;
break;
case "json":
case "jsonp":
case "jsonstring":
dataReader = p.jsonReader;
break;
default:
break;
}
var i, cells, len, drows, idName, idIndex, rd = {}, idr,
colModel = p.colModel, nCol = colModel.length, cmName,
iChild, children, nChildren, child,
// TODO: consider to introduce preloadedAttributes in the same way
// like we use to preloadedNodes below and to cache .attributes[i]
// in the same way like one cache .childNodes[i].
// One should measure the performance, to find out whether
// such caching will improve the performance.
arrayReaderInfos = p.arrayReaderInfos, info, preloadedNodes = {},
attrReader = function (nodeName) {
return function (obj) {
var attrValue = obj != null && isFunction(obj.getAttribute) ? obj.getAttribute(nodeName) : null;
return attrValue !== null ? attrValue : undefined;
};
},
nodeReader = function (nodeName) {
return function () {
// commented code which used getElementsByTagName works
// good in new web browsers (Chrome, Firefox, Safari),
// but it is slowly in IE10 and especially in IE8.
// So we use the code which is very good for all web browsers
/*var elem = obj.getElementsByTagName(nodeName)[0], childNodes;
if (elem != null) {
childNodes = elem.childNodes;
return childNodes.length > 0 ? childNodes[0].nodeValue : undefined;
}
return undefined;*/
var elem = preloadedNodes[nodeName], childNodes;
if (elem == null) { return undefined; }
childNodes = elem.childNodes;
return childNodes.length > 0 ? childNodes[0].nodeValue : undefined;
};
};
p.page = intNum(fieldReader(data, dataReader.page), p.page);
p.lastpage = intNum(fieldReader(data, dataReader.total), 1);
p.records = intNum(fieldReader(data, dataReader.records));
if (isFunction(dataReader.userdata)) {
p.userData = dataReader.userdata.call(self, data) || {};
} else if (isXML) {
fieldReader(data, dataReader.userdata, true)
.each(function () {
p.userData[this.getAttribute("name")] = $(this).text();
});
} else {
p.userData = fieldReader(data, dataReader.userdata) || {};
}
// fill colReader and
fillOrClearCellBuilder();
var colReader = {}, isArrayCells, v, addProp, items,
additionalProperties = p.additionalProperties,
setSimpleColReaderIfPossible = function (propName, nameReaderOrAddProp) {
if (isXML && typeof nameReaderOrAddProp === "string") {
if (/^\w+$/.test(nameReaderOrAddProp)) {
colReader[propName] = nodeReader(nameReaderOrAddProp);
} else if (/^\[\w+\]$/.test(nameReaderOrAddProp)) {
colReader[propName] = attrReader(nameReaderOrAddProp.substring(1, nameReaderOrAddProp.length - 1));
}
}
},
colReaderFilling = function (colOrAddProp) {
var colOrAddPropName = colOrAddProp.name,
nameReader = isXML ?
colOrAddProp.xmlmap || colOrAddPropName :
(datatype === "local" && !p.dataTypeOrg) || datatype === "jsonstring" || datatype === "json" || datatype === "jsonp" ? colOrAddProp.jsonmap || colOrAddPropName : colOrAddPropName;
if (p.keyName !== false && colOrAddProp.key === true) {
p.keyName = colOrAddPropName; // TODO: replace nameReader to colOrAddPropName if we don't will read it at the second time
}
if (typeof nameReader === "string" || isFunction(nameReader)) {
colReader[colOrAddPropName] = nameReader;
}
if (!isFunction(nameReader)) {
setSimpleColReaderIfPossible(colOrAddPropName, nameReader);
}
};
for (i = 0; i < nCol; i++) {
colReaderFilling(colModel[i]);
}
nCol = additionalProperties.length;
for (i = 0; i < nCol; i++) {
addProp = additionalProperties[i];
if (typeof addProp === "object" && addProp != null) {
colReaderFilling(addProp);
} else {
setSimpleColReaderIfPossible(addProp, addProp);
}
}
// TODO: Consider to allow to specify key:true property in additionalProperties
// in the case the item of additionalProperties should looks not like
// "myProp" and not like {name: "myProp", convert: function (data) {...}} used in TreeGrid,
// but in more common form {name: "myProp", key:true, convert: function (data) {...}}
// prepare to read id of data items
// if p.keyName !== false it contains the name of the column or the nameReader functoin (jsonmap or xmlmap)
// in the case the reading of id is simple and one DON'T NEED TO READ IT AT ALL
// because it will be already read during reading of the columns
idName = p.keyName === false ?
(isFunction(dataReader.id) ? dataReader.id.call(self, data) : dataReader.id) :
p.keyName;
if (!isNaN(idName)) {
idIndex = Number(idName);
} else if (!isFunction(idName)) {
if (arrayReaderInfos[idName]) {
idIndex = arrayReaderInfos[idName].order;
}
if (isXML && p.keyName === false) {
if (typeof idName === "string" && /^\[\w+\]$/.test(idName)) {
idName = attrReader(idName.substring(1, idName.length - 1));
} else if (typeof idName === "string" && /^\w+$/.test(idName)) {
idName = nodeReader(idName);
}
}
}
// get array of items from the input data
drows = fieldReader(data, dataReader.root, true);
if (dataReader.row) {
if (drows.length === 1 && typeof dataReader.row === "string" && /^\w+$/.test(dataReader.row)) {
items = [];
children = drows[0].childNodes;
nChildren = children.length;
for (iChild = 0; iChild < nChildren; iChild++) {
child = children[iChild];
if (child.nodeType === 1 && child.nodeName === dataReader.row) {
items.push(child);
}
}
drows = items;
} else {
drows = fieldReader(drows, dataReader.row, true); // || [];
}
}
if (drows == null && isArray(data)) { drows = data; }
if (!drows) { drows = []; }
len = drows.length;
if (len > 0 && p.page <= 0) { p.page = 1; }
var rn = parseInt(p.rowNum, 10); // br = p.scroll ? randId() : 1
if (adjust) { rn *= adjust + 1; }
// The first loop (from 0 till len) read ALL data and saves it in array
var cellsToDisplay = [], ids = [], id, cur;
items = [];
for (i = 0; i < len; i++) {
cur = drows[i];
cells = dataReader.repeatitems && dataReader.cell ? fieldReader(cur, dataReader.cell, true) || cur : cur;
isArrayCells = dataReader.repeatitems && (isXML || isArray(cells));
// the first step: reading the input data from the current item
rd = {}; // require to prevent modification of items previously placed in p.data
preloadedNodes = {};
if (isXML && !isArrayCells && cells != null) {
// reading of simple children nodes by name can be relatively slow
// because one enumerates all children nodes to find the node with
// specified name
children = cells.childNodes;
nChildren = children.length;
for (iChild = 0; iChild < nChildren; iChild++) {
child = children[iChild];
if (child.nodeType === 1) {
preloadedNodes[child.nodeName] = child;
}
}
// TODO: one can consider to examine cells.attributes and
// to save all values in preloadedAttributes map.
}
for (cmName in arrayReaderInfos) {
if (arrayReaderInfos.hasOwnProperty(cmName)) {
info = arrayReaderInfos[cmName];
if (isArrayCells) {
v = cells[info.order];
if (isXML && v != null) {
v = v.textContent || v.text;
}
} else if (colReader[cmName] != null && typeof colReader[cmName] !== "string") { // isFunction(colReader[cmName])
v = colReader[cmName].call(self, cells, { cmName: cmName, iItem: i });
} else {
v = fieldReader(cells, typeof colReader[cmName] === "string" ? colReader[cmName] : info.name);
}
if (info.type === 1) { // additional property
addProp = additionalProperties[info.index];
if (addProp != null && isFunction(addProp.convert)) {
v = addProp.convert(v, cells);
}
}
if (v !== undefined) {
rd[cmName] = v;
}
}
}
// read id.
if (rd[idName] !== undefined) {
// the id should be already read in p.keyName column.
// One need generate id only if the input data had no id
id = rd[idName] !== undefined ? rd[idName] : randId(); //id = br + i;
} else {
id = fieldReader(cur, isArray(cur) ? idIndex : idName);
if (id === undefined) {
id = fieldReader(cells, isArray(cells) ? idIndex : idName);
}
if (id === undefined) {
id = randId(); //id = br + i;
}
}
if (rd[idName] === undefined) {
rd[idName] = id;
}
id = String(id);
idr = p.idPrefix + id;
if (p.treeGrid) { normalizeTreeGridProperties(rd); }
// final steps of reading the row
if (i < rn) {
ids.push(idr);
cellsToDisplay.push(cells);
items.push(rd);
} else if (!readAllInputData) {
break;
}
if (readAllInputData || p.treeGrid === true) {
rd[locid] = id; //stripGridPrefix(idr);
p.data.push(rd);
addItemDataToColumnIndex(rd, id);
p._index[rd[locid]] = p.data.length - 1;
}
}
if (readAllInputData && p.treeGrid !== true) {
if (p.forceClientSorting) {
// don't display the data, just read it.
return;
}
// initialize lastSelectedData to simplify the usage of lastSelectedData
p.lastSelectedData = p.data.slice();
}
// of rd items plus array cells items (almost the same as drows).
// The second loop (from 0 till min(len,rn)) will build rowData from the both arrays
// Then one place rowData AT ONCE to the body any calls afterInsertRow in the loop
// for every inserted row.
// Finally one clean up the both arrays
var rowData = jgrid.parseDataToHtml.call(self, len, ids, items, cellsToDisplay, rcnt, adjust, readAllInputData);
fillOrClearCellBuilder(true); // clear cellBuilders
// place the HTML string fragments collected in rowData in the body of grid
var fpos = p.treeANode > -1 ? p.treeANode : 0;
var $tbody = $(self.tBodies[0]);
if (p.treeGrid === true && fpos > 0) {
$(self.rows[fpos]).after(rowData.join(""));
} else if (p.scroll) {
$tbody.append(rowData.join(""));
} else if (self.firstElementChild == null || (document.documentMode !== undefined && document.documentMode <= 9)) {
// for IE8 for example
$tbody.html($tbody.html() + rowData.join("")); // append to innerHTML of tbody which contains the first row (.jqgfirstrow)
self.grid.cols = self.rows[0].cells; // update cached first row
} else {
self.firstElementChild.innerHTML += rowData.join(""); // append to innerHTML of tbody which contains the first row (.jqgfirstrow)
self.grid.cols = self.rows[0].cells; // update cached first row
}
// refresh rowIndexes cash in case of usage grouping
if (p.grouping) {
rebuildRowIndexes.call(self);
// bind onclick on +/- icon of grouping header to the call of groupingToggle
var expandOrCollapseGroup = function (e) {
var groupHeaderId = $(this).closest("tr.jqgroup").attr("id");
$self.jqGrid("groupingToggle", groupHeaderId, this, e);
return false;
},
$tr;
for (i = 0; i < self.rows.length; i++) {
$tr = $(self.rows[i]);
if ($tr.hasClass("jqgroup")) {
$tr.children("td")
.children("span.tree-wrap")
.click(expandOrCollapseGroup);
}
}
}
//
if (p.subGrid === true) {
// make subgrid specific actions: bind click event handler to "+"
try { $j.addSubGrid.call($self, p.iColByName.subgrid); } catch (ignore) { }
}
if (p.gridview === false || isFunction(p.afterInsertRow)) {
for (i = 0; i < Math.min(len, rn); i++) {
feedback.call(self, "afterInsertRow", ids[i], items[i], cellsToDisplay[i]);
}
}
p.totaltime = new Date() - startReq;
if (i > 0) {
if (p.records === 0) { p.records = len; }
}
clearArray(rowData);
if (p.treeGrid === true) {
try { $j.setTreeNode.call($self, fpos + 1, i + fpos + 1); } catch (ignore) { }
}
p.reccount = Math.min(len, rn);
p.treeANode = -1;
if (p.userDataOnFooter) { $j.footerData.call($self, "set", p.userData, true); }
if (readAllInputData) {
p.records = len;
p.lastpage = Math.ceil(len / rn);
}
if (!more) { self.updatepager(false, true); }
finalizationFormatters.call(self);
},
addLocalData = function () {
var $self = $(this), st = p.multiSort ? [] : "", sto = {}, fndsort = false, cmtypes = {}, grtypes = [], grindexes = [],
defSrcFormat = getRes("formatter.date.srcformat"),
defNewFormat = getRes("formatter.date.newformat");
if (!isArray(p.data)) {
return {};
}
if (p.multiSort) {
getSortNames(st, sto);
}
var grpview = p.grouping ? p.groupingView : false, lengrp, gin,
processColModel = function (cm, iCol1, isAddProp) {
var srcformat, newformat,
grindex = cm.index || cm.name,
sorttype = cm.sorttype || "text";
cmtypes[cm.name] = {
reader: !p.dataTypeOrg ? cm.jsonmap || cm.name : cm.name,
iCol: iCol1,
stype: sorttype,
srcfmt: "",
newfmt: "",
sfunc: cm.sortfunc || null,
isAddProp: isAddProp === true ? true : false
};
if (sorttype === "date" || sorttype === "datetime") {
if (cm.formatter && typeof cm.formatter === "string" && cm.formatter === "date") {
if (cm.formatoptions && cm.formatoptions.srcformat) {
srcformat = cm.formatoptions.srcformat;
} else {
srcformat = defSrcFormat;
}
if (cm.formatoptions && cm.formatoptions.newformat) {
newformat = cm.formatoptions.newformat;
} else {
newformat = defNewFormat;
}
} else {
srcformat = newformat = cm.datefmt || "Y-m-d";
}
cmtypes[cm.name].srcfmt = srcformat;
cmtypes[cm.name].newfmt = newformat;
}
if (p.grouping) {
for (gin = 0, lengrp = grpview.groupField.length; gin < lengrp; gin++) {
if (cm.name === grpview.groupField[gin]) {
grtypes[gin] = cmtypes[grindex];
grindexes[gin] = grindex;
}
}
}
if (!p.multiSort) {
if (!fndsort && (cm.index === p.sortname || cm.name === p.sortname)) {
st = cm.name; // ???
fndsort = true;
}
}
};
each(p.colModel, function (iCol1) {
processColModel(this, iCol1);
});
each(p.additionalProperties, function (iCol1) {
processColModel(
typeof this === "string" ? { name: this } : this,
iCol1,
true
);
});
if (p.treeGrid) {
$j.SortTree.call($self, st, p.sortorder,
cmtypes[st] != null && cmtypes[st].stype ? cmtypes[st].stype : "text",
cmtypes[st] != null && cmtypes[st].srcfmt ? cmtypes[st].srcfmt : "");
return false;
}
var compareFnMap = {
"eq": function (queryObj) { return queryObj.equals; },
"ne": function (queryObj) { return queryObj.notEquals; },
"lt": function (queryObj) { return queryObj.less; },
"le": function (queryObj) { return queryObj.lessOrEquals; },
"gt": function (queryObj) { return queryObj.greater; },
"ge": function (queryObj) { return queryObj.greaterOrEquals; },
"cn": function (queryObj) { return queryObj.contains; },
"nc": function (queryObj, op) { return op === "OR" ? queryObj.orNot().contains : queryObj.andNot().contains; },
"bw": function (queryObj) { return queryObj.startsWith; },
"bn": function (queryObj, op) { return op === "OR" ? queryObj.orNot().startsWith : queryObj.andNot().startsWith; },
"en": function (queryObj, op) { return op === "OR" ? queryObj.orNot().endsWith : queryObj.andNot().endsWith; },
"ew": function (queryObj) { return queryObj.endsWith; },
"ni": function (queryObj, op) { return op === "OR" ? queryObj.orNot().inSet : queryObj.andNot().inSet; },
"in": function (queryObj) { return queryObj.inSet; },
"nu": function (queryObj) { return queryObj.isNull; },
"nn": function (queryObj, op) { return op === "OR" ? queryObj.orNot().isNull : queryObj.andNot().isNull; }
},
query = jgrid.from.call(this, p.data);
if (p.ignoreCase) { query = query.ignoreCase(); }
function tojLinq(group) {
var s = 0, index, gor, ror, opr, rule, r, cmi1;
if (group.groups != null) {
gor = group.groups.length && group.groupOp.toString().toUpperCase() === "OR";
if (gor) {
query.orBegin();
}
for (index = 0; index < group.groups.length; index++) {
if (s > 0 && gor) {
query.or();
}
try {
tojLinq(group.groups[index]);
} catch (e) { fatalErrorFunction(e); }
s++;
}
if (gor) {
query.orEnd();
}
}
if (group.rules != null) {
try {
ror = group.rules.length && group.groupOp.toString().toUpperCase() === "OR";
if (ror) {
query.orBegin();
}
for (index = 0; index < group.rules.length; index++) {
rule = group.rules[index];
opr = group.groupOp.toString().toUpperCase();
if (compareFnMap[rule.op] && rule.field) {
if (s > 0 && opr && opr === "OR") {
query = query.or();
}
cmi1 = cmtypes[rule.field];
if (cmi1 != null) {
r = cmi1.reader;
query = compareFnMap[rule.op](query, opr)(
isFunction(r) ?
"jQuery.jgrid.getAccessor(this,jQuery(\"" + p.idSel + "\")[0].p.colModel[" + cmi1.iCol + "].jsonmap)" :
"jQuery.jgrid.getAccessor(this,'" + r + "')",
rule.data,
cmtypes[rule.field]
);
}
} else if (p.customSortOperations != null && p.customSortOperations[rule.op] != null && isFunction(p.customSortOperations[rule.op].filter)) {
query = query.custom(rule.op, rule.field, rule.data);
}
s++;
}
if (ror) {
query.orEnd();
}
} catch (g) { fatalErrorFunction(g); }
}
}
if (p.search === true) {
var srules = p.postData[(p.searching || {}).sFilter || p.prmNames.filters];
if (srules) {
if (typeof srules === "string") { srules = $.parseJSON(srules); }
tojLinq(srules);
} else {
try {
var cmtypes1 = cmtypes[p.postData.searchField];
query = compareFnMap[p.postData.searchOper](query)(
//p.postData.searchField,
isFunction(cmtypes1.reader) ?
"jQuery.jgrid.getAccessor(this,jQuery(\"" + p.idSel + "\")[0].p.colModel[" + cmtypes1.iCol + "].jsonmap)" :
"jQuery.jgrid.getAccessor(this,'" + cmtypes1.reader + "')",
p.postData.searchString,
cmtypes[p.postData.searchField]
);
} catch (ignore) { }
}
}
if (p.grouping) {
for (gin = 0; gin < lengrp && gin < grindexes.length && gin < grtypes.length; gin++) {
query.orderBy(grindexes[gin], grpview.groupOrder[gin], grtypes[gin].stype, grtypes[gin].srcfmt);
}
}
if (p.multiSort) {
each(st, function () {
query.orderBy(this, sto[this], cmtypes[this].stype, cmtypes[this].srcfmt, cmtypes[this].sfunc);
});
} else if (st && p.sortorder && fndsort) {
query.orderBy(p.sortname, p.sortorder.toUpperCase() === "DESC" ? "d" : "a", cmtypes[st].stype, cmtypes[st].srcfmt, cmtypes[st].sfunc);
}
p.lastSelectedData = query.select();
var recordsperpage = parseInt(p.rowNum, 10),
total = p.lastSelectedData.length,
page = parseInt(p.page, 10),
totalpages = Math.ceil(total / recordsperpage),
retresult = {};
if (p.grouping && p.groupingView._locgr) {
p.groupingView.groups = [];
var j, key, udc;
if (p.footerrow && p.userDataOnFooter) {
for (key in p.userData) {
if (p.userData.hasOwnProperty(key)) {
p.userData[key] = 0;
}
}
udc = true;
}
for (j = 0; j < total; j++) {
if (udc) {
for (key in p.userData) {
if (p.userData.hasOwnProperty(key)) {
p.userData[key] += parseFloat(p.lastSelectedData[j][key] || 0);
}
}
}
$j.groupingPrepare.call($self, p.lastSelectedData[j], j, recordsperpage);
}
}
query = null;
cmtypes = null;
var localReader = p.localReader;
retresult[localReader.total] = totalpages;
retresult[localReader.page] = page;
retresult[localReader.records] = total;
retresult[localReader.root] = p.lastSelectedData.slice((page - 1) * recordsperpage, page * recordsperpage);
retresult[localReader.userdata] = p.userData;
return retresult;
},
setWidthOfPagerTdWithPager = function ($pgTable) {
var self = this, width = $pgTable.outerWidth(), fontSize;
if (width <= 0) { // not visible
fontSize = $(self).closest(".ui-jqgrid>.ui-jqgrid-view").css("font-size") || "11px";
$(document.body).append("");
$($pgTable).clone().appendTo("#testpg");
width = $("#testpg>.ui-pg-table").width();
$("#testpg").remove();
}
if (width > 0) {
$pgTable.parent().width(width);
}
return width;
},
updatepager = function (rn, dnd) {
var self = this, $self = $(self), gridSelf = self.grid, cp, last, base1, from, to, tot, fmt, pgboxes = p.pager || "", sppg,
tspg = p.pager ? "_" + p.pager.substr(1) : "", bDiv = gridSelf.bDiv, numberFormat = $.fmatter ? $.fmatter.NumberFormat : null,
tspgTop = p.toppager ? "_" + p.toppager.substr(1) : "",
hoverClasses = getGuiStyles("states.hover"), disabledClasses = getGuiStyles("states.disabled");
base1 = parseInt(p.page, 10) - 1;
if (base1 < 0) { base1 = 0; }
base1 = base1 * parseInt(p.rowNum, 10);
to = base1 + p.reccount;
if (p.scroll) {
var rows = $(getGridComponent(COMPONENT_NAMES.BODY_TABLE, bDiv)[0].rows).slice(1);//$("tbody:first > tr:gt(0)", bDiv);
base1 = to - rows.length;
p.reccount = rows.length;
var rh = rows.outerHeight() || gridSelf.prevRowHeight;
if (rh) {
var top = base1 * rh;
var height = jgrid.fixMaxHeightOfDiv.call(self, parseInt(p.records, 10) * rh);
$(bDiv).children("div").first().css({ height: height + "px" })
.children("div").first().css({ height: top + "px", display: top + "px" ? "" : "none" });
if (bDiv.scrollTop === 0 && p.page > 1) {
bDiv.scrollTop = p.rowNum * (p.page - 1) * rh;
}
}
bDiv.scrollLeft = gridSelf.hDiv.scrollLeft;
}
pgboxes += p.toppager ? (pgboxes ? "," : "") + p.toppager : "";
if (pgboxes) {
fmt = getRes("formatter.integer") || {};
cp = intNum(p.page);
last = intNum(p.lastpage);
$(".selbox", pgboxes).prop("disabled", false);
if (p.pginput === true) {
var $pagerInputs = $(".ui-pg-input", pgboxes),
numberOfDigitsInPageNumber = String(p.page).length;
$pagerInputs.val(p.page);
// verify the value of size attribute of "input.ui-pg-input"
// and increase it if it's required.
$pagerInputs.each(function () {
var size = parseInt($(this).attr("size"), 10);
if (size > 0 && size < numberOfDigitsInPageNumber) {
$(this).attr("size", numberOfDigitsInPageNumber);
}
});
sppg = p.toppager ? "#sp_1" + tspg + ",#sp_1" + tspgTop : "#sp_1" + tspg;
$(sppg).html($.fmatter ? numberFormat(p.lastpage, fmt) : p.lastpage)
.closest(".ui-pg-table").each(function () {
setWidthOfPagerTdWithPager.call(self, $(this));
});
}
if (p.viewrecords) {
if (p.reccount === 0) {
$(".ui-paging-info", pgboxes).html(getDef("emptyrecords"));
} else {
from = base1 + 1;
tot = p.records;
if ($.fmatter) {
from = numberFormat(from, fmt);
to = numberFormat(to, fmt);
tot = numberFormat(tot, fmt);
}
$(".ui-paging-info", pgboxes).html(jgrid.format(getDef("recordtext"), from, to, tot));
}
}
if (p.pgbuttons === true) {
if (last <= 0) { cp = 0;}
if (cp <= 0) { cp = last = 0; }
if (cp === 1 || cp === 0) {
$("#first" + tspg + ", #prev" + tspg).addClass(disabledClasses).removeClass(hoverClasses);
if (p.toppager) { $("#first_t" + tspgTop + ", #prev_t" + tspgTop).addClass(disabledClasses).removeClass(hoverClasses); }
} else {
$("#first" + tspg + ", #prev" + tspg).removeClass(disabledClasses);
if (p.toppager) { $("#first_t" + tspgTop + ", #prev_t" + tspgTop).removeClass(disabledClasses); }
}
if (cp === last || cp === 0) {
$("#next" + tspg + ", #last" + tspg).addClass(disabledClasses).removeClass(hoverClasses);
if (p.toppager) { $("#next_t" + tspgTop + ", #last_t" + tspgTop).addClass(disabledClasses).removeClass(hoverClasses); }
} else {
$("#next" + tspg + ", #last" + tspg).removeClass(disabledClasses);
if (p.toppager) { $("#next_t" + tspgTop + ", #last_t" + tspgTop).removeClass(disabledClasses); }
}
}
}
if (rn === true && p.rownumbers === true) {
$(">td.jqgrid-rownum", self.rows).each(function (i) {
$(this).html(base1 + 1 + i);
});
}
if (dnd && p.jqgdnd) { $self.jqGrid("gridDnD", "updateDnD"); }
feedback.call(self, "gridComplete");
$self.triggerHandler("jqGridAfterGridComplete");
},
beginReq = function () {
var self = this;
self.grid.hDiv.loading = true;
if (p.hiddengrid) { return; }
$j.progressBar.call($(self), { method: "show", loadtype: p.loadui, htmlcontent: getDef("loadtext") });
},
endReq = function () {
var self = this;
self.grid.hDiv.loading = false;
$j.progressBar.call($(self), { method: "hide", loadtype: p.loadui });
},
populate = function (npage) {
var self = this, $self = $(self), gridSelf = self.grid;
if (!gridSelf.hDiv.loading) {
var pvis = p.scroll && npage === false, prm = {}, dt, dstr, pN = p.prmNames;
if (p.page <= 0) { p.page = Math.min(1, p.lastpage); }
if (pN.search !== null) { prm[pN.search] = p.search; }
if (pN.nd !== null) { prm[pN.nd] = new Date().getTime(); }
if (isNaN(parseInt(p.rowNum, 10)) || parseInt(p.rowNum, 10) <= 0) { p.rowNum = p.maxRowNum; }
if (pN.rows !== null) { prm[pN.rows] = p.rowNum; }
if (pN.page !== null) { prm[pN.page] = p.page; }
if (pN.sort !== null) { prm[pN.sort] = p.sortname; }
if (pN.order !== null) { prm[pN.order] = p.sortorder; }
if (p.rowTotal !== null && pN.totalrows !== null) { prm[pN.totalrows] = p.rowTotal; }
var lcf = isFunction(p.loadComplete), lc = lcf ? p.loadComplete : null;
var adjust = 0;
npage = npage || 1;
if (npage > 1) {
if (pN.npage !== null) {
prm[pN.npage] = npage;
adjust = npage - 1;
npage = 1;
} else {
lc = function (data) {
p.page++;
gridSelf.hDiv.loading = false;
if (lcf) {
p.loadComplete.call(self, data);
}
populate.call(self, npage - 1);
};
}
} else if (pN.npage !== null) {
delete p.postData[pN.npage];
}
if (p.grouping && $j.groupingSetup) {
$j.groupingSetup.call($self);
var grp = p.groupingView, gi, gs = "", index, iColumn, cmValue;
for (gi = 0; gi < grp.groupField.length; gi++) {
index = grp.groupField[gi];
for (iColumn = 0; iColumn < p.colModel.length; iColumn++) {
cmValue = p.colModel[iColumn];
if (cmValue.name === index && cmValue.index) {
index = cmValue.index;
}
}
gs += index + " " + grp.groupOrder[gi] + ", ";
}
prm[pN.sort] = gs + prm[pN.sort];
}
extend(p.postData, prm);
var rcnt = !p.scroll ? 1 : self.rows.length - 1,
fixDisplayingHorizontalScrollbar = function () {
fixScrollOffsetAndhBoxPadding.call(self);
// if no items are displayed in the btable, but the column header is too wide
// the horizontal scrollbar of bDiv will be disabled.
if (!p.autowidth && (p.widthOrg === undefined || p.widthOrg === "auto" || p.widthOrg === "100%")) {
$j.setGridWidth.call($self, p.tblwidth + p.scrollOffset, false);
}
},
resort = function () {
var iRes;
if (p.autoresizeOnLoad) {
$j.autoResizeAllColumns.call($self);
clearArray(p.columnsToReResizing);
if (p.autowidth) {
$j.setGridWidth.call($self,
$self.closest(".ui-jqgrid").parent().width(),
true);
}
} else {
for (iRes = 0; iRes < p.columnsToReResizing.length; iRes++) {
$j.autoResizeColumn.call($self, p.columnsToReResizing[iRes]);
}
clearArray(p.columnsToReResizing);
}
},
finalReportSteps = function () {
feedback.call(self, "loadComplete", dstr);
resort();
$self.triggerHandler("jqGridAfterLoadComplete", [dstr]);
endReq.call(self);
p.datatype = "local";
p.datastr = null;
fixDisplayingHorizontalScrollbar();
},
finalReportVirtual = function (data) {
$self.triggerHandler("jqGridLoadComplete", [data]);
if (lc) { lc.call(self, data); }
resort();
$self.triggerHandler("jqGridAfterLoadComplete", [data]);
if (pvis) { gridSelf.populateVisible.call(self); }
if (npage === 1) { endReq.call(self); }
fixDisplayingHorizontalScrollbar();
},
readLocal = function () {
var req = addLocalData.call(self);
readInput.call(self, req, rcnt, npage > 1, adjust);
finalReportVirtual(req);
};
if (!feedback.call(self, "beforeRequest")) { return; }
if (isFunction(p.datatype)) { p.datatype.call(self, p.postData, "load_" + p.id, rcnt, npage, adjust); return; }
dt = p.datatype.toLowerCase();
$(grid.eDiv).hide();
switch (dt) {
case "json":
case "jsonp":
case "xml":
case "script":
$.ajax(extend({
url: p.url,
type: p.mtype,
dataType: dt,
//data: $.isFunction(p.serializeGridData)? p.serializeGridData.call(self,p.postData) : p.postData,
data: jgrid.serializeFeedback.call(ts, p.serializeGridData, "jqGridSerializeGridData", p.postData),
success: function (data, textStatus, jqXHR) {
p.jqXhr = null;
$(grid.eDiv).hide();
if (isFunction(p.beforeProcessing)) {
if (p.beforeProcessing.call(self, data, textStatus, jqXHR) === false) {
endReq.call(self);
return;
}
}
readInput.call(self, data, rcnt, npage > 1, adjust);
finalReportVirtual(data);
if (p.loadonce || p.treeGrid) {
p.dataTypeOrg = p.datatype;
p.datatype = "local";
if (p.forceClientSorting) { readLocal(); }
}
},
error: function (jqXHR, textStatus, errorThrown) {
p.jqXhr = null;
if (isFunction(p.loadError)) { p.loadError.call(self, jqXHR, textStatus, errorThrown); }
if (npage === 1) { endReq.call(self); }
},
beforeSend: function (jqXHR, settings) {
var gotoreq = true;
if (isFunction(p.loadBeforeSend)) {
gotoreq = p.loadBeforeSend.call(self, jqXHR, settings);
}
if (gotoreq === undefined) { gotoreq = true; }
if (gotoreq === false) {
return false;
}
p.jqXhr = jqXHR;
beginReq.call(self);
}
}, jgrid.ajaxOptions, p.ajaxGridOptions));
break;
case "xmlstring":
beginReq.call(self);
dstr = typeof p.datastr === "string" ? $.parseXML(p.datastr) : p.datastr;
readInput.call(self, dstr);
finalReportSteps();
if (p.forceClientSorting) { readLocal(); }
break;
case "jsonstring":
beginReq.call(self);
dstr = p.datastr && typeof p.datastr === "string" ? $.parseJSON(p.datastr) : p.datastr;
readInput.call(self, dstr);
finalReportSteps();
if (p.forceClientSorting) { readLocal(); }
break;
case "local":
case "clientside":
beginReq.call(self);
p.datatype = "local";
readLocal();
break;
}
}
},
setHeadCheckBox = function (checked) {
var self = this, gridSelf = self.grid;
$(p.cb, gridSelf.hDiv).prop("checked", checked);
if (p.frozenColumns) {
$(p.cb, gridSelf.fhDiv).prop("checked", checked);
}
},
cancelOrSaveEditing = function (mode) {
// The current code don't take in the consideration errors during
// remote saving/canceling. The standard behavior in case of
// remote saving/canceling is wating till the server response and
// holding inline/cell editing if saving/canceling failed by some
// server reason. The current code of cancelOrSaveEditing
// don't wait for the server response
var iEditing, savedRowInfo;
for (iEditing = 0; iEditing < p.savedRow.length; iEditing++) {
savedRowInfo = p.savedRow[iEditing];
if (mode === "save") {
if (savedRowInfo.hasOwnProperty("ic")) {
$self0.jqGrid("saveCell", savedRowInfo.id, savedRowInfo.ic);
} else {
$self0.jqGrid("saveRow", savedRowInfo.id);
}
} else {
// mode === "cancel"
if (savedRowInfo.hasOwnProperty("ic")) {
$self0.jqGrid("restoreCell", savedRowInfo.id, savedRowInfo.ic);
} else {
$self0.jqGrid("restoreRow", savedRowInfo.id);
}
}
}
//clearArray(p.savedRow); // p.savedRow = [];
//p.editingInfo = {};
},
setPager = function (pgid, tp) {
var hoverClasses = getGuiStyles("states.hover"), disabledClasses = getGuiStyles("states.disabled"),
sep = "
", { role: "row", "aria-hidden": "true" }).addClass("jqg-first-row-header").css("height", "auto");
} else {
$firstHeaderRow.empty();
}
var inColumnHeader = function (cmName, columnHeaders) {
var j;
for (j = 0; j < columnHeaders.length; j++) {
if (columnHeaders[j].startColumnName === cmName) {
return columnHeaders[j];
}
}
return 0; // falsy value
};
$(ts).prepend($thead);
$tr = $("
", { role: "row" }).addClass("ui-jqgrid-labels jqg-third-row-header");
for (i = 0; i < cml; i++) {
th = ths[i].el;
$th = $(th);
cmi = colModel[i];
// build the next cell for the first header row
// ??? cmi.hidden || isCellClassHidden(cmi.classes) || $th.is(":hidden")
thStyle = { height: "0", width: ths[i].width + "px", display: (cmi.hidden ? "none" : "") };
$("
", { role: "gridcell" }).css(thStyle).addClass("ui-first-th-" + p.direction + (o.applyLabelClasses ? " " + (cmi.labelClasses || "") : "")).appendTo($firstHeaderRow);
th.style.width = ""; // remove unneeded style
thClasses = getGuiStyles.call(ts, "colHeaders", "ui-th-column-header ui-th-" + p.direction + " " + (o.applyLabelClasses ? cmi.labelClasses || "" : ""));
cghi = inColumnHeader(cmi.name, o.groupHeaders);
if (cghi) {
numberOfColumns = cghi.numberOfColumns;
titleText = cghi.titleText;
// caclulate the number of visible columns from the next numberOfColumns columns
for (cVisibleColumns = 0, iCol = 0; iCol < numberOfColumns && (i + iCol < cml); iCol++) {
if (!colModel[i + iCol].hidden && !isCellClassHidden(colModel[i + iCol].classes)) {
cVisibleColumns++;
}
}
// The next numberOfColumns headers will be moved in the next row
// in the current row will be placed the new column header with the titleText.
// The text will be over the cVisibleColumns columns
$colHeader = $("
")
.addClass(thClasses)
.html(titleText || " ");
if (cVisibleColumns > 0) {
$colHeader.attr("colspan", String(cVisibleColumns));
}
if (p.headertitles) {
$colHeader.attr("title", $colHeader.text());
}
// hide if not a visible cols
if (cVisibleColumns === 0) {
$colHeader.hide();
}
$th.before($colHeader); // insert new column header before the current
$tr.append(th); // move the current header in the next row
// set the counter of headers which will be moved in the next row
skip = numberOfColumns - 1;
} else {
if (skip === 0) {
if (o.useColSpanStyle) {
// expand the header height to two rows
$th.attr("rowspan", $trLabels.length + 1); // consider to use ($th.attr("rowspan") || 1) instead of $trLabels.length
} else {
$("
")
.addClass(thClasses)
.css({ "display": cmi.hidden ? "none" : "", "border-top": "0 none" })
.insertBefore($th);
$tr.append(th);
}
} else {
// move the header to the next row
$tr.append(th);
skip--;
}
}
}
$theadInTable = $(ts).children("thead");
$theadInTable.prepend($firstHeaderRow);
$tr.insertAfter($trLastWithLabels);
$htable.prepend($theadInTable);
$(ts).triggerHandler("jqGridAfterSetGroupHeaders");
});
},
getNumberOfFrozenColumns: function () {
var $t = this;
if ($t.length === 0) {
return 0;
}
$t = $t[0];
var colModel = $t.p.colModel, len = colModel.length, maxfrozen = -1, i;
// get the max index of frozen col
for (i = 0; i < len; i++) {
// from left, no breaking frozen
if (colModel[i].frozen !== true) {
break;
}
maxfrozen = i;
}
return maxfrozen + 1;
},
setFrozenColumns: function (o) {
o = o || {};
return this.each(function () {
var $t = this, $self = $($t), p = $t.p, grid = $t.grid;
if (!grid || p == null || p.frozenColumns === true) { return; }
var cm = p.colModel, i, len = cm.length, maxfrozen = -1, frozen = false, frozenIds = [], $colHeaderRow,// nonFrozenIds = [],
tid = jqID(p.id), // one can use p.idSel and remove "#"
hoverClasses = getGuiStyles.call($t, "states.hover");
// TODO treeGrid and grouping Support
// TODO: allow to edit columns AFTER frozen columns
if (p.subGrid === true || p.treeGrid === true || p.scroll) {
return;
}
// get the max index of frozen col
for (i = 0; i < len; i++) {
// from left, no breaking frozen
if (cm[i].frozen !== true) {
break;
//nonFrozenIds.push("#jqgh_" + tid + "_" + jqID(cm[i].name));
}
frozen = true;
maxfrozen = i;
frozenIds.push("#jqgh_" + tid + "_" + jqID(cm[i].name));
}
if (p.sortable) {
$colHeaderRow = $(grid.hDiv).find(".ui-jqgrid-htable .ui-jqgrid-labels");
try {
$colHeaderRow.sortable("destroy");
} catch (ignore) { }
$self.jqGrid("setGridParam", {
sortable: {
options: {
items: frozenIds.length > 0 ?
">th:not(:has(" + frozenIds.join(",") + "),:hidden)" :
">th:not(:hidden)"
}
}
});
$self.jqGrid("sortableColumns", $colHeaderRow);
}
if (maxfrozen >= 0 && frozen) {
var top = p.caption ? $(grid.cDiv).outerHeight() : 0,
hth = $(".ui-jqgrid-htable", p.gView).height();
//headers
if (p.toppager) {
top = top + $(grid.topDiv).outerHeight();
}
if (p.toolbar[0] === true) {
if (p.toolbar[1] !== "bottom") {
top = top + $(grid.uDiv).outerHeight();
}
}
grid.fhDiv = $("");
grid.fbDiv = $("");
$(p.gView).append(grid.fhDiv);
var htbl = $(".ui-jqgrid-htable", p.gView).clone(true),
tHeadRows = htbl[0].tHead.rows;
// groupheader support - only if useColSpanstyle is false
if (p.groupHeader) {
// TODO: remove all th which corresponds non-frozen columns. One can identify there by id
// for example. Consider to use name attribute of th on column headers. It simplifies
// identifying of the columns.
$(tHeadRows[0].cells).filter(":gt(" + maxfrozen + ")").remove();
$(tHeadRows).filter(".jqg-third-row-header").each(function () {
$(this).children("th[id]")
.each(function () {
var id = $(this).attr("id"), colName;
if (id && id.substr(0, $t.id.length + 1) === $t.id + "_") {
colName = id.substr($t.id.length + 1);
if (p.iColByName[colName] > maxfrozen) {
$(this).remove();
}
}
});
});
var swapfroz = -1, fdel = -1, cs, rs;
// TODO: test carefully processing of hidden columns
$(tHeadRows).filter(".jqg-second-row-header").children("th").each(function () {
cs = parseInt($(this).attr("colspan") || 1, 10);
rs = parseInt($(this).attr("rowspan") || 1, 10);
if (rs > 1) {
swapfroz++;
fdel++;
} else if (cs) {
swapfroz = swapfroz + cs;
fdel++;
}
if (swapfroz === maxfrozen) {
return false;
}
});
if (swapfroz !== maxfrozen) {
fdel = maxfrozen;
}
$(tHeadRows).filter(".jqg-second-row-header,.ui-search-toolbar").each(function () {
$(this).children(":gt(" + fdel + ")").remove();
});
} else {
$(tHeadRows).each(function () {
$(this).children(":gt(" + maxfrozen + ")").remove();
});
}
// htable, bdiv and ftable uses table-layout:fixed; style
// to make it working one have to set ANY width value on table.
// The value of the width will be ignored, the sum of widths
// of the first column will be used as the width of tables
// and all columns will have the same width like the first row.
// We set below just width=1 of the tables.
$(htbl).width(1);
// resizing stuff
$(grid.fhDiv).append(htbl)
.scroll(function () {
// the fhDiv can be scrolled because of tab keyboard navigation
// we prevent horizontal scrolling of fhDiv
this.scrollLeft = 0;
});
if (p.footerrow) {
var hbd = $(".ui-jqgrid-bdiv", p.gView).height();
grid.fsDiv = $("");
$(p.gView).append(grid.fsDiv);
var ftbl = $(".ui-jqgrid-ftable", p.gView).clone(true);
$("tr", ftbl).each(function () {
$("td:gt(" + maxfrozen + ")", this).remove();
});
$(ftbl).width(1);
$(grid.fsDiv).append(ftbl);
}
// data stuff
//TODO support for setRowData
$(p.gView).append(grid.fbDiv);
$(grid.bDiv).scroll(function () {
$(grid.fbDiv).scrollTop($(this).scrollTop());
});
$(grid.fbDiv).on("mousewheel.setFrozenColumns DOMMouseScroll.setFrozenColumns", function (e) {
grid.bDiv.scrollTop += $.isFunction(o.mouseWheel) ?
o.mouseWheel.call($t, e) :
e.type === "mousewheel" ?
-e.originalEvent.wheelDelta / 10 :
e.originalEvent.detail * 6;
});
if (p.hoverrows === true) {
$(p.idSel).off("mouseover.jqGrid mouseout.jqGrid");
}
var safeHeightSet = function ($elem, newHeight) {
var height = $elem.height();
if (Math.abs(height - newHeight) >= 1 && newHeight > 0) {
$elem.height(newHeight);
height = $elem.height();
if (Math.abs(newHeight - height) >= 1) {
$elem.height(newHeight + Math.round((newHeight - height)));
}
}
},
safeWidthSet = function ($elem, newWidth) {
var width = $elem.width();
if (Math.abs(width - newWidth) >= 1) {
$elem.width(newWidth);
width = $elem.width();
if (Math.abs(newWidth - width) >= 1) {
$elem.width(newWidth + Math.round((newWidth - width)));
}
}
},
fixDiv = function ($hDiv, hDivBase, iRowStart, iRowEnd) {
var iRow, n, $frozenRows, $rows, $row, $frozenRow, posFrozenTop, height, newHeightFrozen, td,
posTop = $(hDivBase).position().top, frozenTableTop, tableTop, cells;
if ($hDiv != null && $hDiv.length > 0) {
$hDiv[0].scrollTop = hDivBase.scrollTop;
$hDiv.css(p.direction === "rtl" ?
{ top: posTop, right: 0 } :
{ top: posTop, left: 0 }
);
// first try with thead for the hdiv
$frozenRows = $hDiv.children("table").children("thead").children("tr");
$rows = $(hDivBase).children("div").children("table").children("thead").children("tr");
if ($rows.length === 0 && $hDiv.children("table").length > 0) {
// then use tbody for bdiv
$frozenRows = $($hDiv.children("table")[0].rows);
$rows = $($(hDivBase).children("div").children("table")[0].rows);
}
n = Math.min($frozenRows.length, $rows.length);
frozenTableTop = n > 0 ? $($frozenRows[0]).position().top : 0;
tableTop = n > 0 ? $($rows[0]).position().top : 0; // typically 0
if (iRowStart >= 0) { // negative iRowStart means no changing of the height of individual rows
if (iRowEnd >= 0) { // negative iRowEnd means all rows
n = Math.min(iRowEnd + 1, n);
}
for (iRow = iRowStart; iRow < n; iRow++) {
// but after that one have to verify all scenarios
$row = $($rows[iRow]);
if ($row.css("display") !== "none" && $row.is(":visible")) {
posTop = $row.position().top;
$frozenRow = $($frozenRows[iRow]);
posFrozenTop = $frozenRow.position().top;
height = $row.height();
if (p.groupHeader != null && p.groupHeader.useColSpanStyle) {
cells = $row[0].cells;
for (i = 0; i < cells.length; i++) { // maxfrozen
td = cells[i];
if (td != null && td.nodeName.toUpperCase() === "TH") {
height = Math.max(height, $(td).height());
}
}
}
newHeightFrozen = height + (posTop - tableTop) + (frozenTableTop - posFrozenTop);
safeHeightSet($frozenRow, newHeightFrozen);
}
}
}
safeHeightSet($hDiv, hDivBase.clientHeight);
}
},
/** @const */
resizeAll = {
resizeDiv: true,
resizedRows: {
iRowStart: 0,
iRowEnd: -1 // -1 means "till the end"
}
},
/** @const */
fullResize = {
header: resizeAll,
resizeFooter: true,
body: resizeAll
};
$self.on("jqGridAfterGridComplete.setFrozenColumns", function () {
$(p.idSel + "_frozen").remove();
$(grid.fbDiv).height(grid.hDiv.clientHeight);
// clone with data and events !!!
var $frozenBTable = $(this).clone(true),
frozenRows = $frozenBTable[0].rows,
rows = $self[0].rows;
$(frozenRows).filter("tr[role=row]").each(function () {
$(this.cells).filter("td[role=gridcell]:gt(" + maxfrozen + ")").remove();
/*if (this.id) {
$(this).attr("id", this.id + "_frozen");
}*/
});
grid.fbRows = frozenRows;
$frozenBTable.width(1).attr("id", p.id + "_frozen");
$frozenBTable.appendTo(grid.fbDiv);
if (p.hoverrows === true) {
var hoverRows = function (tr, method, additionalRows) {
$(tr)[method](hoverClasses);
$(additionalRows[tr.rowIndex])[method](hoverClasses);
};
$(frozenRows).filter(".jqgrow").hover(
function () {
hoverRows(this, "addClass", rows);
},
function () {
hoverRows(this, "removeClass", rows);
}
);
$(rows).filter(".jqgrow").hover(
function () {
hoverRows(this, "addClass", frozenRows);
},
function () {
hoverRows(this, "removeClass", frozenRows);
}
);
}
fixDiv(grid.fhDiv, grid.hDiv, 0, -1);
fixDiv(grid.fbDiv, grid.bDiv, 0, -1);
if (grid.sDiv) { fixDiv(grid.fsDiv, grid.sDiv, 0, -1); }
});
var myResize = function (resizeOptions) {
$(grid.fbDiv).scrollTop($(grid.bDiv).scrollTop());
// TODO: the width of all column headers can be changed
// so one should recalculate frozenWidth in other way.
if (resizeOptions.header.resizeDiv) {
fixDiv(grid.fhDiv, grid.hDiv, resizeOptions.header.resizedRows.iRowStart, resizeOptions.header.resizedRows.iRowEnd);
}
if (resizeOptions.body.resizeDiv) {
fixDiv(grid.fbDiv, grid.bDiv, resizeOptions.body.resizedRows.iRowStart, resizeOptions.body.resizedRows.iRowEnd);
}
if (resizeOptions.resizeFooter && grid.sDiv && resizeOptions.resizeFooter) {
fixDiv(grid.fsDiv, grid.sDiv, 0, -1);
}
var frozenWidth = grid.fhDiv[0].clientWidth;
if (resizeOptions.header.resizeDiv && grid.fhDiv != null && grid.fhDiv.length >= 1) {
safeHeightSet($(grid.fhDiv), grid.hDiv.clientHeight);
}
if (resizeOptions.body.resizeDiv && grid.fbDiv != null && grid.fbDiv.length > 0) {
safeWidthSet($(grid.fbDiv), frozenWidth);
}
if (resizeOptions.resizeFooter && grid.fsDiv != null && grid.fsDiv.length >= 0) {
safeWidthSet($(grid.fsDiv), frozenWidth);
}
};
$(p.gBox).on("resizestop.setFrozenColumns", function () {
setTimeout(function () {
myResize(fullResize);
}, 50);
});
$self.on("jqGridInlineEditRow.setFrozenColumns jqGridInlineAfterRestoreRow.setFrozenColumns jqGridInlineAfterSaveRow.setFrozenColumns jqGridAfterEditCell.setFrozenColumns jqGridAfterRestoreCell.setFrozenColumns jqGridAfterSaveCell.setFrozenColumns jqGridResizeStop.setFrozenColumns", function (e, rowid) {
// TODO: probably one should handle additional events like afterSetRow
// and remove jqGridInlineAfterSaveRow and jqGridInlineAfterRestoreRow
var iRow = $self.jqGrid("getInd", rowid);
myResize({
header: {
resizeDiv: false, // don't recalculate the position and the height of hDiv
resizedRows: {
iRowStart: -1, // -1 means don't recalculate heights or rows
iRowEnd: -1
}
},
resizeFooter: true, // recalculate the position and the height of sDiv
body: {
resizeDiv: true, // recalculate the position and the height of bDiv
resizedRows: {
// recalculate the height of only one row inside of bDiv
iRowStart: iRow,
iRowEnd: iRow
}
}
});
});
$self.on("jqGridResizeStop.setFrozenColumns", function () {
myResize(fullResize);
});
$self.on("jqGridResetFrozenHeights.setFrozenColumns", function (e, o) {
myResize(o || fullResize);
});
if (!grid.hDiv.loading) {
setTimeout(function () {
$self.triggerHandler("jqGridAfterGridComplete");
}, 0);
}
p.frozenColumns = true;
}
});
},
destroyFrozenColumns: function () {
return this.each(function () {
var $t = this, $self = $($t), grid = $t.grid, p = $t.p, tid = jqID(p.id);
if (!grid) { return; }
if (p.frozenColumns === true) {
$(grid.fhDiv).remove();
$(grid.fbDiv).off(".setFrozenColumns");
$(grid.fbDiv).remove();
grid.fhDiv = null;
grid.fbDiv = null;
grid.fbRows = null;
if (p.footerrow) {
$(grid.fsDiv).remove();
grid.fsDiv = null;
}
$self.off(".setFrozenColumns");
if (p.hoverrows === true) {
var ptr, hoverClasses = getGuiStyles.call($t, "states.hover");
$self.on("mouseover.jqGrid", function (e) {
ptr = $(e.target).closest("tr.jqgrow");
if ($(ptr).attr("class") !== "ui-subgrid") {
$(ptr).addClass(hoverClasses);
}
}).on("mouseout.jqGrid", function (e) {
ptr = $(e.target).closest("tr.jqgrow");
$(ptr).removeClass(hoverClasses);
});
}
p.frozenColumns = false;
if (p.sortable) {
var $colHeaderRow = $(grid.hDiv).find(".ui-jqgrid-htable .ui-jqgrid-labels");
$colHeaderRow.sortable("destroy");
$self.jqGrid("setGridParam", {
sortable: {
options: {
items: ">th:not(:has(#jqgh_" + tid + "_cb" + ",#jqgh_" + tid + "_rn" + ",#jqgh_" + tid + "_subgrid),:hidden)"
}
}
});
$self.jqGrid("sortableColumns", $colHeaderRow);
}
}
});
}
});
// end module grid.custom
/**
* jqFilter jQuery jqGrid filter addon.
* Copyright (c) 2011-2014, Tony Tomov, [email protected]
* Copyright (c) 2014-2018, Oleg Kiriljuk, [email protected]
* Dual licensed under the MIT and GPL licenses
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl-2.0.html
*
* The work is inspired from this Stefan Pirvu
* http://www.codeproject.com/KB/scripting/json-filtering.aspx
*
* The filter uses JSON entities to hold filter rules and groups. Here is an example of a filter:
{ "groupOp": "AND",
"groups" : [
{ "groupOp": "OR",
"rules": [
{ "field": "name", "op": "eq", "data": "England" },
{ "field": "id", "op": "le", "data": "5"}
]
}
],
"rules": [
{ "field": "name", "op": "eq", "data": "Romania" },
{ "field": "id", "op": "le", "data": "1"}
]
}
*/
// begin module grid.filter
$.fn.jqFilter = function (arg) {
if (typeof arg === "string") {
var fn = $.fn.jqFilter[arg];
if (!fn) {
throw ("jqFilter - No such method: " + arg);
}
var args = $.makeArray(arguments).slice(1);
return fn.apply(this, args);
}
var p = $.extend(true, {
filter: null,
columns: [],
onChange: null,
afterRedraw: null,
error: false,
errmsg: "",
errorcheck: true,
showQuery: true,
sopt: null,
ops: [],
operands: null,
numopts: ["eq", "ne", "lt", "le", "gt", "ge", "nu", "nn", "in", "ni"],
stropts: ["eq", "ne", "bw", "bn", "ew", "en", "cn", "nc", "nu", "nn", "in", "ni"],
strarr: ["text", "string", "blob"],
groupOps: [{ op: "AND", text: "AND" }, { op: "OR", text: "OR" }],
groupButton: true,
ruleButtons: true,
direction: "ltr"
}, jgrid.filter, arg || {});
return this.each(function () {
if (this.filter) { return; }
this.p = p;
// setup filter in case if they is not defined
if (p.filter === null || p.filter === undefined) {
p.filter = {
groupOp: p.groupOps[0].op,
rules: [],
groups: []
};
}
var iColumn, len = p.columns.length, cl, isIE = /msie/i.test(navigator.userAgent) && !window.opera,
isFunction = $.isFunction,
fatalErrorFunction = jgrid.defaults != null && isFunction(jgrid.defaults.fatalError) ? jgrid.defaults.fatalError : alert,
getGrid = function () {
return $("#" + jgrid.jqID(p.id))[0] || null;
},
getGuiStyles = function (path, jqClasses) {
return $(getGrid()).jqGrid("getGuiStyles", path, jqClasses || "");
},
getRes = function (property) {
return $(getGrid()).jqGrid("getGridRes", "search." + property);
},
getCmInfo = function (cmName) {
// the function convert column name or advanced property name to
// object with properties { cm: , iCol: }
var $t = getGrid(), iCol = $t.p.iColByName[cmName]; //iPropByName
if (iCol !== undefined) {
return { cm: $t.p.colModel[iCol], iCol: iCol };
}
iCol = $t.p.iPropByName[cmName];
if (iCol !== undefined) {
return { cm: $t.p.additionalProperties[iCol], iCol: iCol, isAddProp: true };
}
return { cm: null, iCol: -1 };
},
errorClass = getGuiStyles("states.error"),
dialogContentClass = getGuiStyles("dialog.content");
// translating the options
p.initFilter = $.extend(true, {}, p.filter);
// set default values for the columns if they are not set
if (!len) { return; }
for (iColumn = 0; iColumn < len; iColumn++) {
cl = p.columns[iColumn];
if (cl.stype) {
// grid compatibility
cl.inputtype = cl.stype;
} else if (!cl.inputtype) {
cl.inputtype = "text";
}
if (cl.sorttype) {
// grid compatibility
cl.searchtype = cl.sorttype;
} else if (!cl.searchtype) {
cl.searchtype = "string";
}
if (cl.hidden === undefined) {
// jqGrid compatibility
cl.hidden = false;
}
if (!cl.label) {
cl.label = cl.name;
}
cl.cmName = cl.name;
if (cl.index) {
cl.name = cl.index;
}
if (!cl.hasOwnProperty("searchoptions")) {
cl.searchoptions = {};
}
if (!cl.hasOwnProperty("searchrules")) {
cl.searchrules = {};
}
}
if (p.showQuery) {
$(this).append("
");
}
/*
*Perform checking.
*
*/
var checkData = function (val, colModelItem) {
var ret = [true, ""], $t = getGrid();
if (isFunction(colModelItem.searchrules)) {
ret = colModelItem.searchrules.call($t, val, colModelItem);
} else if (jgrid && jgrid.checkValues) {
try {
ret = jgrid.checkValues.call($t, val, -1, colModelItem.searchrules, colModelItem.label);
} catch (ignore) { }
}
if (ret && ret.length && ret[0] === false) {
p.error = !ret[0];
p.errmsg = ret[1];
}
};
/* moving to common
randId = function() {
return Math.floor(Math.random()*10000).toString();
};
*/
this.onchange = function () {
// clear any error
p.error = false;
p.errmsg = "";
return isFunction(p.onChange) ? p.onChange.call(getGrid(), p, this) : false;
};
/*
* Redraw the filter every time when new field is added/deleted
* and field is changed
*/
this.reDraw = function () {
$("table.group:first", this).remove();
var t = this.createTableForGroup(p.filter, null);
$(this).append(t);
if (isFunction(p.afterRedraw)) {
p.afterRedraw.call(getGrid(), p, this);
}
};
/**
* Creates a grouping data for the filter
* @param group - object
* @param parentgroup - object
*/
this.createTableForGroup = function (group, parentgroup) {
var that = this, i;
// this table will hold all the group (tables) and rules (rows)
var table = $("
");
table.append(tr);
// this header will hold the group operator type and group action buttons for
// creating subgroup "+ {}", creating rule "+" or deleting the group "-"
var th = $("
");
tr.append(th);
if (p.ruleButtons === true) {
// dropdown for: choosing group operator type
var groupOpSelect = $("");
th.append(groupOpSelect);
// populate dropdown with all posible group operators: or, and
var str = "", selected;
for (i = 0; i < p.groupOps.length; i++) {
selected = group.groupOp === that.p.groupOps[i].op ? " selected='selected'" : "";
str += "";
}
groupOpSelect.append(str)
.on("change", function () {
group.groupOp = $(groupOpSelect).val();
that.onchange(); // signals that the filter has changed
});
}
// button for adding a new subgroup
var inputAddSubgroup = "";
if (p.groupButton) {
inputAddSubgroup = $("");
inputAddSubgroup.on("click", function () {
if (group.groups === undefined) {
group.groups = [];
}
group.groups.push({
groupOp: p.groupOps[0].op,
rules: [],
groups: []
}); // adding a new group
that.reDraw(); // the html has changed, force reDraw
that.onchange(); // signals that the filter has changed
return false;
});
}
th.append(inputAddSubgroup);
if (p.ruleButtons === true) {
// button for adding a new rule
var inputAddRule = $(""), cm;
inputAddRule.on("click", function () {
var searchable, hidden, ignoreHiding;
//if(!group) { group = {};}
if (group.rules === undefined) {
group.rules = [];
}
for (i = 0; i < that.p.columns.length; i++) {
// but show only serchable and serchhidden = true fields
searchable = (that.p.columns[i].search === undefined) ? true : that.p.columns[i].search;
hidden = (that.p.columns[i].hidden === true);
ignoreHiding = (that.p.columns[i].searchoptions.searchhidden === true);
if ((ignoreHiding && searchable) || (searchable && !hidden)) {
cm = that.p.columns[i];
break;
}
}
var opr;
if (cm.searchoptions.sopt) {
opr = cm.searchoptions.sopt;
} else if (that.p.sopt) {
opr = that.p.sopt;
} else if ($.inArray(cm.searchtype, that.p.strarr) !== -1) {
opr = that.p.stropts;
} else {
opr = that.p.numopts;
}
group.rules.push({
field: cm.name,
op: opr[0],
data: ""
}); // adding a new rule
that.reDraw(); // the html has changed, force reDraw
// for the moment no change have been made to the rule, so
// this will not trigger onchange event
return false;
});
th.append(inputAddRule);
}
// button for delete the group
if (parentgroup !== null) { // ignore the first group
var inputDeleteGroup = $("");
th.append(inputDeleteGroup);
inputDeleteGroup.on("click", function () {
// remove group from parent
for (i = 0; i < parentgroup.groups.length; i++) {
if (parentgroup.groups[i] === group) {
parentgroup.groups.splice(i, 1);
break;
}
}
that.reDraw(); // the html has changed, force reDraw
that.onchange(); // signals that the filter has changed
return false;
});
}
// append subgroup rows
if (group.groups !== undefined) {
var trHolderForSubgroup, tdFirstHolderForSubgroup, tdMainHolderForSubgroup;
for (i = 0; i < group.groups.length; i++) {
trHolderForSubgroup = $("
");
tdMainHolderForSubgroup.append(this.createTableForGroup(group.groups[i], group));
trHolderForSubgroup.append(tdMainHolderForSubgroup);
}
}
if (group.groupOp === undefined) {
group.groupOp = that.p.groupOps[0].op;
}
// append rules rows
if (group.rules !== undefined) {
for (i = 0; i < group.rules.length; i++) {
table.append(
this.createTableRowForRule(group.rules[i], group)
);
}
}
return table;
};
/*
* Create the rule data for the filter
*/
this.createTableRowForRule = function (rule, group) {
// save current entity in a variable so that it could
// be referenced in anonimous method calls
var that = this, $t = getGrid(), tr = $("
"),
i, op, cm, str = "", selected;
tr.append("
");
// create field container
var ruleFieldTd = $("
");
tr.append(ruleFieldTd);
// dropdown for: choosing field
var ruleFieldSelect = $(""), ina, aoprs = [];
ruleFieldTd.append(ruleFieldSelect);
ruleFieldSelect.on("change", function () {
rule.field = $(ruleFieldSelect).val();
var trpar = $(this).parents("tr:first"), columns, k; // define LOCAL variables
for (k = 0; k < that.p.columns.length; k++) {
if (that.p.columns[k].name === rule.field) {
columns = that.p.columns[k];
break;
}
}
if (!columns) { return; }
var editoptions = $.extend({}, columns.editoptions || {});
delete editoptions.readonly;
delete editoptions.disabled;
var searchoptions = $.extend(
{},
editoptions || {},
columns.searchoptions || {},
getCmInfo(columns.cmName),
{ id: jgrid.randId(), name: columns.name, mode: "search" }
);
searchoptions.column = columns; // add reference to that.p.columns[k];
if (isIE && columns.inputtype === "text") {
if (!searchoptions.size) {
searchoptions.size = 10;
}
}
var elm = jgrid.createEl.call($t, columns.inputtype,
$.extend({}, searchoptions, searchoptions.attr || {}),
"", true, that.p.ajaxSelectOptions || {}, true);
$(elm).addClass(getGuiStyles("searchDialog.elem", "input-elm"));
//that.createElement(rule, "");
if (searchoptions.sopt) {
op = searchoptions.sopt;
} else if (that.p.sopt) {
op = that.p.sopt;
} else if ($.inArray(columns.searchtype, that.p.strarr) !== -1) {
op = that.p.stropts;
} else {
op = that.p.numopts;
}
// operators
var s = "", so = 0, odataItem1, itemOper1, itemText;
aoprs = [];
$.each(that.p.ops, function () { aoprs.push(this.oper); });
// append aoprs array with custom operations defined in customSortOperations parameter jqGrid
if (that.p.cops) {
$.each(that.p.cops, function (propertyName) { aoprs.push(propertyName); });
}
for (k = 0; k < op.length; k++) {
itemOper1 = op[k];
ina = $.inArray(op[k], aoprs);
if (ina !== -1) {
odataItem1 = that.p.ops[ina];
itemText = odataItem1 !== undefined ? odataItem1.text : that.p.cops[itemOper1].text;
if (so === 0) {
// the first select item will be automatically selected in single-select
rule.op = itemOper1;
}
s += "";
so++;
}
}
$(".selectopts", trpar).empty().append(s);
$(".selectopts", trpar)[0].selectedIndex = 0;
if (jgrid.msie && jgrid.msiever() < 9) {
var sw = parseInt($("select.selectopts", trpar)[0].offsetWidth, 10) + 1;
$(".selectopts", trpar).width(sw);
$(".selectopts", trpar).css("width", "auto");
}
// data
$(".data", trpar).empty().append(elm);
if (columns.createColumnIndex && searchoptions.generateDatalist) {
var dataListId = "dl_" + elm.id,
$datalist = $($t).jqGrid("generateDatalistFromColumnIndex", columns.name);
if ($datalist != null && $datalist.length > 0) {
$(elm).attr("list", dataListId);
$(".data", trpar).append($datalist.attr("id", dataListId));
}
}
jgrid.bindEv.call($t, elm, searchoptions);
$(".input-elm", trpar).on("change", searchoptions, function (e) {
var elem = e.target, column = e.data.column;
rule.data = column && column.inputtype === "custom" && isFunction(column.searchoptions.custom_value) ?
column.searchoptions.custom_value.call($t, $(this).find(".customelement").first(), "get") :
elem.value;
if ($(elem).is("input[type=checkbox]") && !$(elem).is(":checked")) {
// value of checkbox contains checked value
rule.data = $(elem).data("offval");
}
that.onchange(); // signals that the filter has changed
});
setTimeout(function () { //IE, Opera, Chrome
rule.data = $(elm).val();
that.onchange(); // signals that the filter has changed
}, 0);
});
// populate drop down with user provided column definitions
var j = 0, searchable, hidden, ignoreHiding;
for (i = 0; i < that.p.columns.length; i++) {
// but show only serchable and serchhidden = true fields
searchable = (that.p.columns[i].search === undefined) ? true : that.p.columns[i].search;
hidden = (that.p.columns[i].hidden === true);
ignoreHiding = (that.p.columns[i].searchoptions.searchhidden === true);
if ((ignoreHiding && searchable) || (searchable && !hidden)) {
selected = "";
if (rule.field === that.p.columns[i].name) {
selected = " selected='selected'";
j = i;
}
str += "";
}
}
ruleFieldSelect.append(str);
// create operator container
var ruleOperatorTd = $("
");
tr.append(ruleOperatorTd);
cm = p.columns[j];
// create it here so it can be referentiated in the onchange event
//var RD = that.createElement(rule, rule.data);
if (isIE && cm.inputtype === "text") {
if (!cm.searchoptions.size) {
cm.searchoptions.size = 10;
}
}
var editoptions = $.extend({}, cm.editoptions || {});
delete editoptions.readonly;
delete editoptions.disabled;
var searchoptions = $.extend(
{},
editoptions,
cm.searchoptions || {},
getCmInfo(cm.cmName),
{ id: jgrid.randId(), name: cm.name, mode: "search" });
searchoptions.column = cm;
var ruleDataInput = jgrid.createEl.call($t, cm.inputtype,
$.extend({}, searchoptions, searchoptions.attr || {}),
rule.data, true, that.p.ajaxSelectOptions || {}, true);
if (rule.op === "nu" || rule.op === "nn" || $.inArray(rule.op, $t.p.customUnaryOperations) >= 0) {
$(ruleDataInput).attr("readonly", "true");
$(ruleDataInput).attr("disabled", "true");
} //retain the state of disabled text fields in case of null ops
// dropdown for: choosing operator
var ruleOperatorSelect = $("");
ruleOperatorTd.append(ruleOperatorSelect);
ruleOperatorSelect.on("change", function () {
rule.op = $(ruleOperatorSelect).val();
var trpar = $(this).parents("tr:first"),
rd = $(".input-elm", trpar)[0];
if (rule.op === "nu" || rule.op === "nn" || $.inArray(rule.op, $t.p.customUnaryOperations) >= 0) { // disable for operator "is null" and "is not null"
rule.data = "";
if (rd.tagName.toUpperCase() !== "SELECT") { rd.value = ""; }
rd.setAttribute("readonly", "true");
rd.setAttribute("disabled", "true");
} else {
if (rd.tagName.toUpperCase() === "SELECT") { rule.data = rd.value; }
rd.removeAttribute("readonly");
rd.removeAttribute("disabled");
}
that.onchange(); // signals that the filter has changed
});
// populate drop down with all available operators
if (cm.searchoptions.sopt) {
op = cm.searchoptions.sopt;
} else if (that.p.sopt) {
op = that.p.sopt;
} else if ($.inArray(cm.searchtype, that.p.strarr) !== -1) {
op = that.p.stropts;
} else {
op = that.p.numopts;
}
str = "";
var odataItem, itemOper;
$.each(that.p.ops, function () { aoprs.push(this.oper); });
// append aoprs array with custom operations defined in customSortOperations parameter jqGrid
if (that.p.cops) {
$.each(that.p.cops, function (propertyName) { aoprs.push(propertyName); });
}
for (i = 0; i < op.length; i++) {
itemOper = op[i];
ina = $.inArray(op[i], aoprs);
if (ina !== -1) {
odataItem = that.p.ops[ina];
selected = rule.op === itemOper ? " selected='selected'" : "";
str += "";
}
}
ruleOperatorSelect.append(str);
// create data container
var ruleDataTd = $("
");
tr.append(ruleDataTd);
// textbox for: data
// is created previously
//ruleDataInput.setAttribute("type", "text");
ruleDataTd.append(ruleDataInput);
if (cm.createColumnIndex && cm.searchoptions.generateDatalist) {
var dataListId = "dl_" + ruleDataInput.id,
$datalist = $($t).jqGrid("generateDatalistFromColumnIndex", cm.name);
if ($datalist != null && $datalist.length > 0) {
$(ruleDataInput).attr("list", dataListId);
ruleDataTd.append($datalist.attr("id", dataListId));
}
}
jgrid.bindEv.call($t, ruleDataInput, cm.searchoptions);
$(ruleDataInput).addClass(getGuiStyles("searchDialog.elem", "input-elm"))
.on("change", function () {
rule.data = cm.inputtype === "custom" ?
cm.searchoptions.custom_value.call($t, $(this).find(".customelement").first(), "get") :
$(this).val();
if ($(this).is("input[type=checkbox]") && !$(this).is(":checked")) {
// value of checkbox contains checked value
rule.data = $(this).data("offval");
}
if ($.isArray(rule.data)) {
rule.data = rule.data.join(p.inFilterSeparator || ",");
}
that.onchange(); // signals that the filter has changed
});
// create action container
var ruleDeleteTd = $("
");
tr.append(ruleDeleteTd);
// create button for: delete rule
if (p.ruleButtons === true) {
var ruleDeleteInput = $("");
ruleDeleteTd.append(ruleDeleteInput);
//$(ruleDeleteInput).html("").height(20).width(30).button({icons: { primary: "ui-icon-minus", text:false}});
ruleDeleteInput.on("click", function () {
// remove rule from group
for (i = 0; i < group.rules.length; i++) {
if (group.rules[i] === rule) {
group.rules.splice(i, 1);
break;
}
}
that.reDraw(); // the html has changed, force reDraw
that.onchange(); // signals that the filter has changed
return false;
});
}
return tr;
};
this.getStringForGroup = function (group) {
var s = "(", index;
if (group.groups !== undefined) {
for (index = 0; index < group.groups.length; index++) {
if (s.length > 1) {
s += " " + group.groupOp + " ";
}
try {
s += this.getStringForGroup(group.groups[index]);
} catch (eg) {
fatalErrorFunction(eg);
}
}
}
if (group.rules !== undefined) {
try {
for (index = 0; index < group.rules.length; index++) {
if (s.length > 1) {
s += " " + group.groupOp + " ";
}
s += this.getStringForRule(group.rules[index]);
}
} catch (e) {
fatalErrorFunction(e);
}
}
s += ")";
if (s === "()") {
return ""; // ignore groups that don't have rules
}
return s;
};
this.getStringForRule = function (rule) {
var operand = "", opC = "", i, cm, ret, val = rule.data, oper, numtypes = ["int", "integer", "float", "number", "currency"]; // jqGrid
for (i = 0; i < p.ops.length; i++) {
if (p.ops[i].oper === rule.op) {
operand = p.operands.hasOwnProperty(rule.op) ? p.operands[rule.op] : "";
opC = p.ops[i].oper;
break;
}
}
if (opC === "" && p.cops != null) {
for (oper in p.cops) {
if (p.cops.hasOwnProperty(oper)) {
opC = oper;
operand = p.cops[oper].operand;
if (isFunction(p.cops[oper].buildQueryValue)) {
return p.cops[oper].buildQueryValue.call(p, { cmName: rule.field, searchValue: val, operand: operand });
}
}
}
}
for (i = 0; i < p.columns.length; i++) {
if (p.columns[i].name === rule.field) {
cm = p.columns[i];
break;
}
}
if (cm == null) {
return "";
}
if (opC === "bw" || opC === "bn") {
val = val + "%";
}
if (opC === "ew" || opC === "en") {
val = "%" + val;
}
if (opC === "cn" || opC === "nc") {
val = "%" + val + "%";
}
if (opC === "in" || opC === "ni") {
val = " (" + val + ")";
}
if (p.errorcheck) {
checkData(rule.data, cm);
}
if ($.inArray(cm.searchtype, numtypes) !== -1 || opC === "nn" || opC === "nu" || $.inArray(opC, getGrid().p.customUnaryOperations) >= 0) {
ret = rule.field + " " + operand + " " + val;
} else {
ret = rule.field + " " + operand + ' "' + val + '"';
}
return ret;
};
this.resetFilter = function () {
p.filter = $.extend(true, {}, p.initFilter);
this.reDraw();
this.onchange();
};
this.hideError = function () {
$("th." + errorClass, this).html("");
$("tr.error", this).hide();
};
this.showError = function () {
$("th." + errorClass, this).html(p.errmsg);
$("tr.error", this).show();
};
this.toUserFriendlyString = function () {
return this.getStringForGroup(p.filter);
};
this.toString = function () {
// this will obtain a string that can be used to match an item.
var that = this;
function getStringRule(rule) {
if (that.p.errorcheck) {
var i, cm;
for (i = 0; i < that.p.columns.length; i++) {
if (that.p.columns[i].name === rule.field) {
cm = that.p.columns[i];
break;
}
}
if (cm) {
checkData(rule.data, cm);
}
}
return rule.op + "(item." + rule.field + ",'" + rule.data + "')";
}
function getStringForGroup(group) {
var s = "(", index;
if (group.groups !== undefined) {
for (index = 0; index < group.groups.length; index++) {
if (s.length > 1) {
if (group.groupOp === "OR") {
s += " || ";
} else {
s += " && ";
}
}
s += getStringForGroup(group.groups[index]);
}
}
if (group.rules !== undefined) {
for (index = 0; index < group.rules.length; index++) {
if (s.length > 1) {
if (group.groupOp === "OR") {
s += " || ";
} else {
s += " && ";
}
}
s += getStringRule(group.rules[index]);
}
}
s += ")";
if (s === "()") {
return ""; // ignore groups that don't have rules
}
return s;
}
return getStringForGroup(p.filter);
};
// Here we init the filter
this.reDraw();
if (p.showQuery) {
this.onchange();
}
// mark is as created so that it will not be created twice on this element
this.filter = true;
});
};
$.extend($.fn.jqFilter, {
/*
* Return SQL like string. Can be used directly
*/
toSQLString: function () {
var s = "";
this.each(function () {
s = this.toUserFriendlyString();
});
return s;
},
/*
* Return filter data as object.
*/
filterData: function () {
var s;
this.each(function () {
s = this.p.filter;
});
return s;
},
getParameter: function (param) {
if (param !== undefined) {
if (this.p.hasOwnProperty(param)) {
return this.p[param];
}
}
return this.p;
},
resetFilter: function () {
return this.each(function () {
this.resetFilter();
});
},
addFilter: function (pfilter) {
if (typeof pfilter === "string") {
pfilter = $.parseJSON(pfilter);
}
this.each(function () {
this.p.filter = pfilter;
this.reDraw();
this.onchange();
});
}
});
// end module grid.filter
/**
The below work is licensed under Creative Commons GNU LGPL License.
Original work:
License: http://creativecommons.org/licenses/LGPL/2.1/
Author: Stefan Goessner/2006
Web: http://goessner.net/
Modifications made:
Version: 0.9-p5
Description: Restructured code, JSLint validated (no strict whitespaces),
added handling of empty arrays, empty strings, and int/floats values.
Author: Michael Schøler/2008-01-29
Web: http://michael.hinnerup.net/blog/2008/01/26/converting-json-to-xml-and-xml-to-json/
Description: json2xml added support to convert functions as CDATA
so it will be easy to write characters that cause some problems when convert
Author: Tony Tomov
*/
// begin module jsonxml
var xmlJsonClass = {
// Param "xml": Element or document DOM node.
// Param "tab": Tab or indent string for pretty output formatting omit or use empty string "" to supress.
// Returns: JSON string
xml2json: function (xml, tab) {
if (xml.nodeType === 9) {
// document node
xml = xml.documentElement;
}
var nws = this.removeWhite(xml),
obj = this.toObj(nws),
json = this.toJson(obj, xml.nodeName, "\t");
return "{\n" + tab + (tab ? json.replace(/\t/g, tab) : json.replace(/\t|\n/g, "")) + "\n}";
},
// Param "o": JavaScript object
// Param "tab": tab or indent string for pretty output formatting omit or use empty string "" to supress.
// Returns: XML string
json2xml: function (o, tab) {
var toXml = function (v, name, ind) {
var xml = "", i, n, sXml, hasChild, m;
if (v instanceof Array) {
if (v.length === 0) {
xml += ind + "<" + name + ">__EMPTY_ARRAY_" + name + ">\n";
} else {
for (i = 0, n = v.length; i < n; i += 1) {
sXml = ind + toXml(v[i], name, ind + "\t") + "\n";
xml += sXml;
}
}
} else if (typeof v === "object") {
hasChild = false;
xml += ind + "<" + name;
for (m in v) {
if (v.hasOwnProperty(m)) {
if (m.charAt(0) === "@") {
xml += " " + m.substr(1) + "=\"" + v[m].toString() + "\"";
} else {
hasChild = true;
}
}
}
xml += hasChild ? ">" : "/>";
if (hasChild) {
for (m in v) {
if (v.hasOwnProperty(m)) {
if (m === "#text") {
xml += v[m];
} else if (m === "#cdata") {
xml += "";
} else if (m.charAt(0) !== "@") {
xml += toXml(v[m], m, ind + "\t");
}
}
}
xml += (xml.charAt(xml.length - 1) === "\n" ? ind : "") + "" + name + ">";
}
} else if (typeof v === "function") {
xml += ind + "<" + name + ">" + "" + "" + name + ">";
} else {
if (v === undefined) {
v = "";
}
if (v.toString() === "\"\"" || v.toString().length === 0) {
xml += ind + "<" + name + ">__EMPTY_STRING_" + name + ">";
} else {
xml += ind + "<" + name + ">" + v.toString() + "" + name + ">";
}
}
return xml;
},
xml1 = "",
p;
for (p in o) {
if (o.hasOwnProperty(p)) {
xml1 += toXml(o[p], p, "");
}
}
return tab ? xml1.replace(/\t/g, tab) : xml1.replace(/\t|\n/g, "");
},
// Internal methods
toObj: function (xml) {
var o = {}, funcTest = /function/i, i, textChild = 0, cdataChild = 0, hasElementChild = false, n;
if (xml.nodeType === 1) {
// element node ..
if (xml.attributes.length) {
// element with attributes ..
for (i = 0; i < xml.attributes.length; i += 1) {
o["@" + xml.attributes[i].nodeName] = (xml.attributes[i].nodeValue || "").toString();
}
}
if (xml.firstChild) {
// element has child nodes ..
for (n = xml.firstChild; n; n = n.nextSibling) {
if (n.nodeType === 1) {
hasElementChild = true;
} else if (n.nodeType === 3 && n.nodeValue.match(/[^ \f\n\r\t\v]/)) {
// non-whitespace text
textChild += 1;
} else if (n.nodeType === 4) {
// cdata section node
cdataChild += 1;
}
}
if (hasElementChild) {
if (textChild < 2 && cdataChild < 2) {
// structured element with evtl. a single text or/and cdata node ..
this.removeWhite(xml);
for (n = xml.firstChild; n; n = n.nextSibling) {
if (n.nodeType === 3) {
// text node
o["#text"] = this.escape(n.nodeValue);
} else if (n.nodeType === 4) {
// cdata node
if (funcTest.test(n.nodeValue)) {
o[n.nodeName] = [o[n.nodeName], n.nodeValue];
} else {
o["#cdata"] = this.escape(n.nodeValue);
}
} else if (o[n.nodeName]) {
// multiple occurence of element ..
if (o[n.nodeName] instanceof Array) {
o[n.nodeName][o[n.nodeName].length] = this.toObj(n);
} else {
o[n.nodeName] = [o[n.nodeName], this.toObj(n)];
}
} else {
// first occurence of element ..
o[n.nodeName] = this.toObj(n);
}
}
} else {
// mixed content
if (!xml.attributes.length) {
o = this.escape(this.innerXml(xml));
} else {
o["#text"] = this.escape(this.innerXml(xml));
}
}
} else if (textChild) {
// pure text
if (!xml.attributes.length) {
o = this.escape(this.innerXml(xml));
if (o === "__EMPTY_ARRAY_") {
o = "[]";
} else if (o === "__EMPTY_STRING_") {
o = "";
}
} else {
o["#text"] = this.escape(this.innerXml(xml));
}
} else if (cdataChild) {
// cdata
if (cdataChild > 1) {
o = this.escape(this.innerXml(xml));
} else {
for (n = xml.firstChild; n; n = n.nextSibling) {
if (funcTest.test(xml.firstChild.nodeValue)) {
o = xml.firstChild.nodeValue;
break;
}
o["#cdata"] = this.escape(n.nodeValue);
}
}
}
}
if (!xml.attributes.length && !xml.firstChild) {
o = null;
}
} else if (xml.nodeType === 9) {
// document.node
o = this.toObj(xml.documentElement);
} else {
($.jgrid != null && $.jgrid.defaults != null && $.isFunction($.jgrid.defaults.fatalError) ? $.jgrid.defaults.fatalError : alert)("unhandled node type: " + xml.nodeType);
}
return o;
},
toJson: function (o, name, ind, wellform) {
if (wellform === undefined) {
wellform = true;
}
var json = name ? ("\"" + name + "\"") : "", tab = "\t", newline = "\n", n, i, ar = [], arr = [], m;
if (!wellform) {
tab = "";
newline = "";
}
if (o === "[]") {
json += (name ? ":[]" : "[]");
} else if (o instanceof Array) {
for (i = 0, n = o.length; i < n; i += 1) {
ar[i] = this.toJson(o[i], "", ind + tab, wellform);
}
json += (name ? ":[" : "[") + (ar.length > 1 ? (newline + ind + tab + ar.join("," + newline + ind + tab) + newline + ind) : ar.join("")) + "]";
} else if (o === null) {
json += (name && ":") + "null";
} else if (typeof o === "object") {
for (m in o) {
if (o.hasOwnProperty(m)) {
arr[arr.length] = this.toJson(o[m], m, ind + tab, wellform);
}
}
json += (name ? ":{" : "{") + (arr.length > 1 ? (newline + ind + tab + arr.join("," + newline + ind + tab) + newline + ind) : arr.join("")) + "}";
} else if (typeof o === "string") {
json += (name && ":") + "\"" + o.replace(/\\/g, "\\\\").replace(/\"/g, '\\"') + "\"";
} else {
json += (name && ":") + o.toString();
}
return json;
},
innerXml: function (node) {
var s = "", child,
asXml = function (n) {
var str = "", i, c;
if (n.nodeType === 1) {
str += "<" + n.nodeName;
for (i = 0; i < n.attributes.length; i += 1) {
str += " " + n.attributes[i].nodeName + "=\"" + (n.attributes[i].nodeValue || "").toString() + "\"";
}
if (n.firstChild) {
str += ">";
for (c = n.firstChild; c; c = c.nextSibling) {
str += asXml(c);
}
str += "" + n.nodeName + ">";
} else {
str += "/>";
}
} else if (n.nodeType === 3) {
str += n.nodeValue;
} else if (n.nodeType === 4) {
str += "";
}
return str;
};
if (node.hasOwnProperty("innerHTML")) {
s = node.innerHTML;
} else {
for (child = node.firstChild; child; child = child.nextSibling) {
s += asXml(child);
}
}
return s;
},
escape: function (txt) {
return txt.replace(/[\\]/g, "\\\\").replace(/[\"]/g, '\\"').replace(/[\n]/g, "\\n").replace(/[\r]/g, "\\r");
},
removeWhite: function (e) {
e.normalize();
var n = e.firstChild, nxt;
while (n) {
if (n.nodeType === 3) {
// text node
if (!n.nodeValue.match(/[^ \f\n\r\t\v]/)) {
// pure whitespace text node
nxt = n.nextSibling;
e.removeChild(n);
n = nxt;
} else {
n = n.nextSibling;
}
} else if (n.nodeType === 1) {
// element node
this.removeWhite(n);
n = n.nextSibling;
} else {
// any other node
n = n.nextSibling;
}
}
return e;
}
};
window.xmlJsonClass = xmlJsonClass;
// end module jsonxml
/**
* jqGrid extension for form editing Grid Data
* Copyright (c) 2008-2014, Tony Tomov, [email protected], http://trirand.com/blog/
* Copyright (c) 2014-2018, Oleg Kiriljuk, [email protected]
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl-2.0.html
**/
// begin module grid.formedit
var jgridFeedback = jgrid.feedback, fullBoolFeedback = jgrid.fullBoolFeedback, builderFmButon = jgrid.builderFmButon,
addFormIcon = function ($fmButton, iconInfos, commonIcon) {
var iconspan;
if (iconInfos[0] === true) {
iconspan = "";
if (iconInfos[1] === "right") {
$fmButton.addClass("fm-button-icon-right").append(iconspan);
} else {
$fmButton.addClass("fm-button-icon-left").prepend(iconspan);
}
}
},
getGuiStateStyles = function (path) {
return getGuiStyles.call(this, "states." + path);
},
hideRowsWithoutVissibleCells = function ($tb) {
$tb.find("tr[data-rowpos]").each(function () {
var vissible = 0;
$(this).children("td").each(function () {
if ($(this).css("visibility") !== "hidden") {
vissible++;
}
});
if (!vissible) {
$(this).hide();
}
});
},
isEmptyString = function (htmlStr) {
return htmlStr === " " || htmlStr === " " || (htmlStr.length === 1 && htmlStr.charCodeAt(0) === 160);
};
jgrid.extend({
searchGrid: function (oMuligrid) {
// if one uses jQuery wrapper with multiple grids, then oMuligrid specify the object with common options
return this.each(function () {
var $t = this, $self = $($t), p = $t.p;
if (!$t.grid || p == null) { return; }
// make new copy of the options and use it for ONE specific grid.
// p.searching can contains grid specific options
// we will don't modify the input options oMuligrid
var o = $.extend(true,
{
drag: true,
sField: "searchField",
sValue: "searchString",
sOper: "searchOper",
sFilter: p.prmNames.filters,
loadDefaults: true, // this options activates loading of default filters from grid's postData for Multipe Search only.
beforeShowSearch: null,
afterShowSearch: null,
onInitializeSearch: null,
afterRedraw: null,
afterChange: null,
closeAfterSearch: false,
closeAfterReset: false,
closeOnEscape: false,
searchOnEnter: false,
multipleSearch: false,
multipleGroup: false,
// we can't use srort names like resetIcon because of conflict with existing "x" of filterToolbar
top: 0,
left: 0,
removemodal: true,
//jqModal : true,
//modal: false,
resize: true,
width: 450,
height: "auto",
dataheight: "auto",
showQuery: false,
errorcheck: true,
sopt: null,
stringResult: undefined,
onClose: null,
onSearch: null,
onReset: null,
//toTop : false,
//overlay : 30,
columns: [],
tmplNames: null,
tmplFilters: null,
tmplLabel: " Template: ",
showOnLoad: false,
layer: null,
operands: {
eq: "=",
ne: "<>",
lt: "<",
le: "<=",
gt: ">",
ge: ">=",
bw: "LIKE",
bn: "NOT LIKE",
"in": "IN",
ni: "NOT IN",
ew: "LIKE",
en: "NOT LIKE",
cn: "LIKE",
nc: "NOT LIKE",
nu: "IS NULL",
nn: "IS NOT NULL"
}
},
base.getGridRes.call($self, "search"),
jgrid.search || {},
p.searching || {},
oMuligrid || {});
var fid = "fbox_" + p.id, commonIconClass = o.commonIconClass,
ids = { themodal: "searchmod" + fid, modalhead: "searchhd" + fid, modalcontent: "searchcnt" + fid, resizeAlso: fid },
themodalSelector = "#" + jqID(ids.themodal), gboxSelector = p.gBox, gviewSelector = p.gView, each = $.each,
defaultFilters = p.postData[o.sFilter],
searchFeedback = function () {
var args = $.makeArray(arguments);
args.unshift("Search");
args.unshift("Filter");
args.unshift(o);
return jgridFeedback.apply($t, args);
},
hideModel = function () {
jgrid.hideModal(themodalSelector, {
gb: gboxSelector,
jqm: o.jqModal,
onClose: o.onClose,
removemodal: o.removemodal
});
};
if (typeof defaultFilters === "string") {
defaultFilters = $.trim(defaultFilters) !== "" ? $.parseJSON(defaultFilters) : undefined;
}
$(themodalSelector).remove();
function showFilter($filter) {
if (searchFeedback("beforeShow", $filter)) {
$(themodalSelector).data("onClose", o.onClose);
jgrid.viewModal.call($t, themodalSelector, {
gbox: gboxSelector,
jqm: o.jqModal,
overlay: o.overlay,
modal: o.modal,
overlayClass: o.overlayClass,
toTop: o.toTop,
onHide: function (h) {
h.w.remove();
if (h.o) { h.o.remove(); }
}
});
searchFeedback("afterShow", $filter);
}
}
if ($(themodalSelector)[0] !== undefined) {
showFilter($("#fbox_" + jqID(p.id)));
} else {
var fil = $("
").insertBefore(gviewSelector);
if (p.direction === "rtl") {
fil.attr("dir", "rtl");
}
var bQ = "", tmpl = "", colnm, found = false, bt, cmi = -1, columns = $.extend([], p.colModel),
bS = builderFmButon.call($t, fid + "_search", o.Find, mergeCssClasses(commonIconClass, o.findDialogIcon), "right"),
bC = builderFmButon.call($t, fid + "_reset", o.Reset, mergeCssClasses(commonIconClass, o.resetDialogIcon), "left");
if (o.showQuery) {
bQ = builderFmButon.call($t, fid + "_query", "Query", mergeCssClasses(commonIconClass, o.queryDialogIcon), "left") +
" ";
}
if (o.searchForAdditionalProperties) {
each(p.additionalProperties, function () {
var cm = typeof this === "string" ? { name: this } : this;
if (!cm.label) {
cm.label = cm.name;
}
cm.isAddProp = true,
columns.push(cm);
});
}
if (!o.columns.length) {
each(columns, function (i, n) {
if (!n.label) {
n.label = n.isAddProp ? n.name : p.colNames[i];
}
// find first searchable column and set it if no default filter
if (!found) {
var searchable = (n.search === undefined) ? true : n.search,
hidden = (n.hidden === true),
ignoreHiding = (n.searchoptions && n.searchoptions.searchhidden === true);
if ((ignoreHiding && searchable) || (searchable && !hidden)) {
found = true;
colnm = n.index || n.name;
cmi = i;
}
}
});
} else {
columns = o.columns;
cmi = 0;
colnm = columns[0].index || columns[0].name;
}
// old behaviour
if ((!defaultFilters && colnm) || o.multipleSearch === false) {
var cmop = "eq";
if (cmi >= 0 && columns[cmi].searchoptions && columns[cmi].searchoptions.sopt) {
cmop = columns[cmi].searchoptions.sopt[0];
} else if (o.sopt && o.sopt.length) {
cmop = o.sopt[0];
}
defaultFilters = { groupOp: "AND", rules: [{ field: colnm, op: cmop, data: "" }] };
}
found = false;
if (o.tmplNames && o.tmplNames.length) {
found = true;
tmpl = o.tmplLabel;
tmpl += "";
}
bt = "";
fid = jqID(fid);
o.gbox = gboxSelector; //"#gbox_" + fid;
o.height = "auto";
fid = "#" + fid;
$(fid).jqFilter({
columns: columns,
filter: o.loadDefaults ? defaultFilters : null,
showQuery: o.showQuery,
errorcheck: o.errorcheck,
sopt: o.sopt,
groupButton: o.multipleGroup,
ruleButtons: o.multipleSearch,
afterRedraw: o.afterRedraw,
ops: o.odata,
cops: p.customSortOperations,
operands: o.operands,
ajaxSelectOptions: p.ajaxSelectOptions,
groupOps: o.groupOps,
onChange: function (filterOptions, filterDiv) {
if (filterOptions.showQuery) {
$(".query", filterDiv).text(filterDiv.toUserFriendlyString());
}
fullBoolFeedback.call($t, o.afterChange, "jqGridFilterAfterChange", $(fid), o, filterOptions, filterDiv);
},
direction: p.direction,
id: p.id
});
fil.append(bt);
if (found && o.tmplFilters && o.tmplFilters.length) {
$(".ui-template", fil).on("change", function () {
var curtempl = $(this).val();
if (curtempl === "default") {
$(fid).jqFilter("addFilter", defaultFilters);
} else {
$(fid).jqFilter("addFilter", o.tmplFilters[parseInt(curtempl, 10)]);
}
return false;
});
}
if (o.multipleGroup === true) { o.multipleSearch = true; }
searchFeedback("onInitialize", $(fid));
if (o.layer) {
jgrid.createModal.call($t, ids, fil, o, gviewSelector, $(gboxSelector)[0], "#" + jqID(o.layer), { position: "relative" });
} else {
jgrid.createModal.call($t, ids, fil, o, gviewSelector, $(gboxSelector)[0]);
}
if (o.searchOnEnter || o.closeOnEscape) {
$(themodalSelector).keydown(function (e) {
var $target = $(e.target);
if (o.searchOnEnter && e.which === 13 && // 13 === $.ui.keyCode.ENTER
!$target.hasClass("add-group") && !$target.hasClass("add-rule") &&
!$target.hasClass("delete-group") && !$target.hasClass("delete-rule") &&
(!$target.hasClass("fm-button") || !$target.is("[id$=_query]"))) {
$(fid + "_search").click();
return false;
}
if (o.closeOnEscape && e.which === 27) { // 27 === $.ui.keyCode.ESCAPE
$("#" + jqID(ids.modalhead)).find(".ui-jqdialog-titlebar-close").click();
return false;
}
});
}
if (bQ) {
$(fid + "_query").on("click", function () {
$(".queryresult", fil).toggle();
return false;
});
}
if (o.stringResult === undefined) {
// to provide backward compatibility, inferring stringResult value from multipleSearch
o.stringResult = o.multipleSearch;
}
$(fid + "_search").on("click", function () {
var sdata = {}, res = "", filters, fl = $(fid), $inputs = fl.find(".input-elm");
if ($inputs.filter(":focus")) {
$inputs = $inputs.filter(":focus");
}
$inputs.change();
filters = fl.jqFilter("filterData");
if (o.errorcheck) {
fl[0].hideError();
if (!o.showQuery) { fl.jqFilter("toSQLString"); }
if (fl[0].p.error) {
fl[0].showError();
return false;
}
}
if (o.stringResult || p.datatype === "local") {
try {
res = JSON.stringify(filters);
} catch (ignore) { }
if (typeof res === "string") {
sdata[o.sFilter] = res;
each([o.sField, o.sValue, o.sOper], function () { sdata[this] = ""; });
}
} else {
if (o.multipleSearch) {
sdata[o.sFilter] = filters;
each([o.sField, o.sValue, o.sOper], function () { sdata[this] = ""; });
} else {
sdata[o.sField] = filters.rules[0].field;
sdata[o.sValue] = filters.rules[0].data;
sdata[o.sOper] = filters.rules[0].op;
sdata[o.sFilter] = "";
}
}
$.extend(p.postData, sdata);
if (fullBoolFeedback.call($t, o.onSearch, "jqGridFilterSearch", p.filters)) {
p.search = true;
$self.trigger("reloadGrid", [$.extend({ page: 1 }, o.reloadGridSearchOptions || {})]);
}
if (o.closeAfterSearch) {
hideModel();
}
return false;
});
$(fid + "_reset").on("click", function () {
var sdata = {}, fl1 = $(fid);
p.search = false;
p.resetsearch = true;
if (o.multipleSearch === false) {
sdata[o.sField] = sdata[o.sValue] = sdata[o.sOper] = "";
} else {
sdata[o.sFilter] = "";
}
fl1[0].resetFilter();
if (found) {
$(".ui-template", fil).val("default");
}
$.extend(p.postData, sdata);
if (fullBoolFeedback.call($t, o.onReset, "jqGridFilterReset")) {
$self.trigger("reloadGrid", [$.extend({ page: 1 }, o.reloadGridResetOptions || {})]);
}
if (o.closeAfterReset) {
hideModel();
}
return false;
});
showFilter($(fid));
var hoverClasses = getGuiStateStyles.call($t, "hover");
// !!! The next row will not work if "states.disabled" is defined using more as one CSS class
$(".fm-button:not(." + getGuiStateStyles.call($t, "disabled").split(" ").join(".") + ")", fil).hover(
function () { $(this).addClass(hoverClasses); },
function () { $(this).removeClass(hoverClasses); }
);
}
});
},
editGridRow: function (rowid, oMuligrid) { // if one uses jQuery wrapper with multiple grids, then oMultiple specify the object with common options
return this.each(function () {
var $t = this, $self = $($t), p = $t.p;
if (!$t.grid || p == null || !rowid) { return; }
// make new copy of the options oMuligrid and use it for ONE specific grid.
// p.formEditing can contains grid specific options
// we will don't modify the input options oMuligrid
var gridId = p.id, getGridRes = base.getGridRes, setSelection = base.setSelection,
o = $.extend(true,
{
top: 0,
left: 0,
width: 300,
datawidth: "auto",
height: "auto",
dataheight: "auto",
//modal: false,
//toTop : false,
//overlay : 30,
drag: true,
resize: true,
url: null,
mtype: "POST",
clearAfterAdd: true,
closeAfterEdit: false,
reloadAfterSubmit: true,
onInitializeForm: null,
beforeInitData: null,
beforeShowForm: null,
afterShowForm: null,
beforeSubmit: null,
afterSubmit: null,
onclickSubmit: null,
afterComplete: null,
onclickPgButtons: null,
afterclickPgButtons: null,
editData: {},
//jqModal : true,
closeOnEscape: false,
addedrow: "first",
topinfo: "",
bottominfo: "",
labelswidth: "",
savekey: [false, 13],
navkeys: [false, 38, 40],
checkOnSubmit: false,
checkOnUpdate: false,
_savedData: {},
processing: false,
onClose: null,
ajaxEditOptions: {},
serializeEditData: null,
viewPagerButtons: true,
overlayClass: getGuiStyles.call(this, "overlay"),
removemodal: true,
skipPostTypes: ["image", "file"],
saveui: "enable",
savetext: getGridRes.call($self, "defaults.savetext") || "Saving..."
},
getGridRes.call($self, "edit"),
jgrid.edit,
p.formEditing || {},
oMuligrid || {});
var frmgr = "FrmGrid_" + gridId, frmgrId = frmgr, frmtborg = "TblGrid_" + gridId, frmtb = "#" + jqID(frmtborg), frmtb2 = frmtb + "_2",
ids = { themodal: "editmod" + gridId, modalhead: "edithd" + gridId, modalcontent: "editcnt" + gridId, resizeAlso: frmgr },
themodalSelector = "#" + jqID(ids.themodal), gboxSelector = p.gBox, colModel = p.colModel, iColByName = p.iColByName,
maxCols = 1, maxRows = 0, postdata, diff, editOrAdd, commonIconClass = o.commonIconClass,
hideModal = function () {
jgrid.hideModal(themodalSelector, {
gb: gboxSelector,
jqm: o.jqModal,
onClose: o.onClose,
removemodal: o.removemodal
});
},
errcap = getGridRes.call($self, "errors.errcap"),
editFeedback = function () {
var args = $.makeArray(arguments);
args.unshift("");
args.unshift("AddEdit");
args.unshift(o);
return jgridFeedback.apply($t, args);
},
hoverClasses = getGuiStateStyles.call($t, "hover"),
disabledClass = getGuiStateStyles.call($t, "disabled"),
highlightClass = getGuiStateStyles.call($t, "select"),
activeClass = getGuiStateStyles.call($t, "active"),
errorClass = getGuiStateStyles.call($t, "error");
$(themodalSelector).remove();
frmgr = "#" + jqID(frmgr);
if (rowid === "new") {
rowid = "_empty";
editOrAdd = "add";
o.caption = o.addCaption;
} else {
o.caption = o.editCaption;
editOrAdd = "edit";
}
var closeovrl = true;
if (o.checkOnUpdate && (o.jqModal === true || o.jqModal === undefined) && !o.modal) {
closeovrl = false;
}
function getFormData() {
$(frmtb + " > tbody > tr > td .FormElement").each(function () {
var $celm = $(".customelement", this),
nm = $celm.length ? $celm.attr("name") : this.name,
iCol = iColByName[nm],
cm = iCol !== undefined ? colModel[iCol] || {} : {},
editoptions = cm.editoptions || {},
formatoptions, newformat, type;
if ($celm.length && $.isFunction(editoptions.custom_value)) {
try {
postdata[nm] = editoptions.custom_value.call($t, $("#" + jqID(nm), frmtb), "get");
if (postdata[nm] === undefined) { throw "e1"; }
} catch (e) {
if (e === "e1") {
jgrid.info_dialog.call($t, errcap, "function 'custom_value' " + o.msg.novalue, o.bClose);
} else {
jgrid.info_dialog.call($t, errcap, e.message, o.bClose);
}
}
return true;
} else {
type = $(this)[0].type;
switch (type) {
case "checkbox":
var checkBoxValues = typeof editoptions.value === "string" ?
editoptions.value.split(":") :
["Yes", "No"];
postdata[nm] = $(this).is(":checked") ? checkBoxValues[0] : checkBoxValues[1];
break;
case "select-one":
postdata[nm] = $("option:selected", this).val();
break;
case "select-multiple":
postdata[nm] = $(this).val();
postdata[nm] = postdata[nm] ? postdata[nm].join(",") : "";
var selectedText = [];
$("option:selected", this).each(
function (i, selected) {
selectedText[i] = $(selected).text();
}
);
break;
case "date":
postdata[nm] = $(this).val();
if (String(postdata[nm]).split("-").length === 3) {
formatoptions = cm.formatoptions || {};
newformat = formatoptions.newformat || getGridRes.call($self, "formatter.date.newformat");
postdata[nm] = jgrid.parseDate.call($self[0], "Y-m-d", postdata[nm], newformat);
}
break;
default:
if (type !== undefined && $.inArray(type, o.skipPostTypes) < 0) {
postdata[nm] = $(this).val();
}
break;
}
}
});
return true;
}
function createData(rowid1, tb, maxcols) {
var cnt = 0, retpos = [], ind = false, $tb = $(tb),
labelsWidth = String(o.labelswidth) + (!o.labelswidth || isNaN(o.labelswidth) ? "" : "px"),
tdtmpl = "
", tmpl = "", i; //*2
for (i = 1; i <= maxcols; i++) {
tmpl += tdtmpl;
}
if (rowid1 !== "_empty") {
ind = base.getInd.call($self, rowid1);
}
$(colModel).each(function (iCol) {
var cm = this, nm = cm.name, $td, hc, trdata, tmp, elc, editable = cm.editable, disabled = false, readonly = false,
mode = rowid1 === "_empty" ? "addForm" : "editForm";
if ($.isFunction(editable)) {
editable = editable.call($t, {
rowid: rowid1,
iCol: iCol,
iRow: ind, // can be false for Add operation
cmName: nm,
cm: cm,
mode: mode
});
}
// hidden fields are included in the form
if (cm.editrules && cm.editrules.edithidden === true) {
hc = false;
} else {
hc = cm.hidden === true || editable === "hidden" ? true : false;
}
switch (String(editable).toLowerCase()) {
case "hidden":
editable = true;
break;
case "disabled":
editable = true;
disabled = true;
break;
case "readonly":
editable = true;
readonly = true;
break;
}
if (nm !== "cb" && nm !== "subgrid" && editable === true && nm !== "rn") {
if (ind === false) {
tmp = "";
} else {
$td = $($t.rows[ind].cells[iCol]); // $("td[role=gridcell]:eq(" + i + ")", $t.rows[ind])
try {
tmp = $.unformat.call($t, $td, { rowId: rowid1, colModel: cm }, iCol);
} catch (_) {
tmp = (cm.edittype && cm.edittype === "textarea") ? $td.text() : $td.html();
}
if (isEmptyString(tmp)) { tmp = ""; }
}
var opt = $.extend({}, cm.editoptions || {},
{ id: nm, name: nm, rowId: rowid1, mode: mode, cm: cm, iCol: iCol }),
frmopt = $.extend({}, { elmprefix: "", elmsuffix: "", rowabove: false, rowcontent: "" }, cm.formoptions || {}),
rp = parseInt(frmopt.rowpos, 10) || cnt + 1,
cp = parseInt((parseInt(frmopt.colpos, 10) || 1) * 2, 10);
if (rowid1 === "_empty" && opt.defaultValue) {
tmp = $.isFunction(opt.defaultValue) ? opt.defaultValue.call($t) : opt.defaultValue;
}
if (!cm.edittype) { cm.edittype = "text"; }
if (p.autoEncodeOnEdit) { tmp = jgrid.oldDecodePostedData(tmp); }
elc = jgrid.createEl.call($t, cm.edittype, opt, tmp, false, $.extend({}, jgrid.ajaxOptions, p.ajaxSelectOptions || {}));
//if(tmp === "" && cm.edittype == "checkbox") {tmp = $(elc).data("offval");}
//if(tmp === "" && cm.edittype == "select") {tmp = $("option:eq(0)",elc).text();}
if (o.checkOnSubmit || o.checkOnUpdate) { o._savedData[nm] = tmp; }
$(elc).addClass("FormElement");
if ($.inArray(cm.edittype, ["text", "textarea", "checkbox", "password", "select"]) > -1) {
$(elc).addClass(getGuiStyles.call($t, "dialog.dataField"));
}
trdata = $tb.find("tr[data-rowpos=" + rp + "]");
if (frmopt.rowabove) {
var newdata = $("