";
try {
if ($("#info_dialog").attr("aria-hidden") === "false") {
$.jgrid.hideModal("#info_dialog", { jqm: jm });
}
$("#info_dialog").remove();
} catch (e) { }
$.jgrid.createModal({
themodal: 'info_dialog',
modalhead: 'info_head',
modalcontent: 'info_content',
scrollelm: 'infocnt'
},
cnt,
mopt,
'', '', true
);
// attach onclick after inserting into the dom
if (buttstr) {
$.each(mopt.buttons, function (i) {
$("#" + $.jgrid.jqID(this.id), "#info_id").bind('click', function () { mopt.buttons[i].onClick.call($("#info_dialog")); return false; });
});
}
$("#closedialog", "#info_id").click(function () {
self.hideModal("#info_dialog", {
jqm: jm,
onClose: $("#info_dialog").data("onClose") || mopt.onClose,
gb: $("#info_dialog").data("gbox") || mopt.gbox
});
return false;
});
$(".fm-button", "#info_dialog").hover(
function () { $(this).addClass(common.hover); },
function () { $(this).removeClass(common.hover); }
);
if ($.isFunction(mopt.beforeOpen)) { mopt.beforeOpen(); }
$.jgrid.viewModal("#info_dialog", {
onHide: function (h) {
h.w.hide().remove();
if (h.o) { h.o.remove(); }
},
modal: mopt.modal,
jqm: jm
});
if ($.isFunction(mopt.afterOpen)) { mopt.afterOpen(); }
try { $("#info_dialog").focus(); } catch (m) { }
},
bindEv: function (el, opt) {
var $t = this;
if ($.isFunction(opt.dataInit)) {
opt.dataInit.call($t, el, opt);
}
if (opt.dataEvents) {
$.each(opt.dataEvents, function () {
if (this.data !== undefined) {
$(el).bind(this.type, this.data, this.fn);
} else {
$(el).bind(this.type, this.fn);
}
});
}
},
// Form Functions
createEl: function (eltype, options, vl, autowidth, ajaxso) {
var elem = "", $t = this;
function setAttributes(elm, atr, exl) {
var exclude = ['dataInit', 'dataEvents', 'dataUrl', 'buildSelect', 'sopt', 'searchhidden', 'defaultValue', 'attr', 'custom_element', 'custom_value', 'oper'];
if (exl !== undefined && $.isArray(exl)) {
$.merge(exclude, exl);
}
$.each(atr, function (key, value) {
if ($.inArray(key, exclude) === -1) {
$(elm).attr(key, value);
}
});
if (!atr.hasOwnProperty('id')) {
$(elm).attr('id', $.jgrid.randId());
}
}
switch (eltype) {
case "textarea":
elem = document.createElement("textarea");
if (autowidth) {
if (!options.cols) { $(elem).css({ width: "98%" }); }
} else if (!options.cols) { options.cols = 20; }
if (!options.rows) { options.rows = 2; }
if (vl === ' ' || vl === ' ' || (vl.length === 1 && vl.charCodeAt(0) === 160)) { vl = ""; }
elem.value = vl;
setAttributes(elem, options);
$(elem).attr({ "role": "textbox", "multiline": "true" });
break;
case "checkbox": //what code for simple checkbox
elem = document.createElement("input");
elem.type = "checkbox";
if (!options.value) {
var vl1 = (vl + "").toLowerCase();
if (vl1.search(/(false|f|0|no|n|off|undefined)/i) < 0 && vl1 !== "") {
elem.checked = true;
elem.defaultChecked = true;
elem.value = vl;
} else {
elem.value = "on";
}
$(elem).attr("offval", "off");
} else {
var cbval = options.value.split(":");
if (vl === cbval[0]) {
elem.checked = true;
elem.defaultChecked = true;
}
elem.value = cbval[0];
$(elem).attr("offval", cbval[1]);
}
setAttributes(elem, options, ['value']);
$(elem).attr("role", "checkbox");
break;
case "select":
elem = document.createElement("select");
elem.setAttribute("role", "select");
var msl, ovm = [];
if (options.multiple === true) {
msl = true;
elem.multiple = "multiple";
$(elem).attr("aria-multiselectable", "true");
} else { msl = false; }
if (options.dataUrl != null) {
var rowid = null, postData = options.postData || ajaxso.postData;
try {
rowid = options.rowId;
} catch (e) { }
if ($t.p && $t.p.idPrefix) {
rowid = $.jgrid.stripPref($t.p.idPrefix, rowid);
}
$.ajax($.extend({
url: $.isFunction(options.dataUrl) ? options.dataUrl.call($t, rowid, vl, String(options.name)) : options.dataUrl,
type: "GET",
dataType: "html",
data: $.isFunction(postData) ? postData.call($t, rowid, vl, String(options.name)) : postData,
context: { elem: elem, options: options, vl: vl },
success: function (data) {
var ovm = [], elem = this.elem, vl = this.vl,
options = $.extend({}, this.options),
msl = options.multiple === true,
cU = options.cacheUrlData === true,
oV = '', txt,
a = $.isFunction(options.buildSelect) ? options.buildSelect.call($t, data) : data;
if (typeof a === 'string') {
a = $($.trim(a)).html();
}
if (a) {
$(elem).append(a);
setAttributes(elem, options, postData ? ['postData'] : undefined);
if (options.size === undefined) { options.size = msl ? 3 : 1; }
if (msl) {
ovm = vl.split(",");
ovm = $.map(ovm, function (n) { return $.trim(n); });
} else {
ovm[0] = $.trim(vl);
}
//$(elem).attr(options);
//setTimeout(function(){
$("option", elem).each(function (i) {
txt = $(this).text();
vl = $(this).val() || txt;
if (cU) {
oV += (i !== 0 ? ";" : "") + vl + ":" + txt;
}
//if(i===0) { this.selected = ""; }
// fix IE8/IE7 problem with selecting of the first item on multiple=true
if (i === 0 && elem.multiple) { this.selected = false; }
$(this).attr("role", "option");
if ($.inArray($.trim(txt), ovm) > -1 || $.inArray($.trim(vl), ovm) > -1) {
this.selected = "selected";
}
});
if (cU) {
if (options.oper === 'edit') {
$($t).jqGrid('setColProp', options.name, { editoptions: { buildSelect: null, dataUrl: null, value: oV } });
} else if (options.oper === 'search') {
$($t).jqGrid('setColProp', options.name, { searchoptions: { dataUrl: null, value: oV } });
} else if (options.oper === 'filter') {
if ($("#fbox_" + $t.p.id)[0].p) {
var cols = $("#fbox_" + $t.p.id)[0].p.columns, nm;
$.each(cols, function (i) {
nm = this.index || this.name;
if (options.name === nm) {
this.searchoptions.dataUrl = null;
this.searchoptions.value = oV;
return false;
}
});
}
}
}
$($t).triggerHandler("jqGridAddEditAfterSelectUrlComplete", [elem]);
//},0);
}
}
}, ajaxso || {}));
} else if (options.value) {
var i;
if (options.size === undefined) {
options.size = msl ? 3 : 1;
}
if (msl) {
ovm = vl.split(",");
ovm = $.map(ovm, function (n) { return $.trim(n); });
}
if (typeof options.value === 'function') { options.value = options.value(); }
var so, sv, ov, oSv, key, value,
sep = options.separator === undefined ? ":" : options.separator,
delim = options.delimiter === undefined ? ";" : options.delimiter;
if (typeof options.value === 'string') {
so = options.value.split(delim);
for (i = 0; i < so.length; i++) {
sv = so[i].split(sep);
if (sv.length > 2) {
sv[1] = $.map(sv, function (n, ii) { if (ii > 0) { return n; } }).join(sep);
}
ov = document.createElement("option");
ov.setAttribute("role", "option");
ov.value = sv[0]; ov.innerHTML = sv[1];
elem.appendChild(ov);
if (!msl && ($.trim(sv[0]) === $.trim(vl) || $.trim(sv[1]) === $.trim(vl))) { ov.selected = "selected"; }
if (msl && ($.inArray($.trim(sv[1]), ovm) > -1 || $.inArray($.trim(sv[0]), ovm) > -1)) { ov.selected = "selected"; }
}
} else if (Object.prototype.toString.call(options.value) === "[object Array]") {
oSv = options.value;
// array of arrays [[Key, Value], [Key, Value], ...]
for (i = 0; i < oSv.length; i++) {
if (oSv[i].length === 2) {
key = oSv[i][0];
value = oSv[i][1];
ov = document.createElement("option");
ov.setAttribute("role", "option");
ov.value = key; ov.innerHTML = value;
elem.appendChild(ov);
if (!msl && ($.trim(key) === $.trim(vl) || $.trim(value) === $.trim(vl))) { ov.selected = "selected"; }
if (msl && ($.inArray($.trim(value), ovm) > -1 || $.inArray($.trim(key), ovm) > -1)) { ov.selected = "selected"; }
}
}
} else if (typeof options.value === 'object') {
oSv = options.value;
for (key in oSv) {
if (oSv.hasOwnProperty(key)) {
ov = document.createElement("option");
ov.setAttribute("role", "option");
ov.value = key; ov.innerHTML = oSv[key];
elem.appendChild(ov);
if (!msl && ($.trim(key) === $.trim(vl) || $.trim(oSv[key]) === $.trim(vl))) { ov.selected = "selected"; }
if (msl && ($.inArray($.trim(oSv[key]), ovm) > -1 || $.inArray($.trim(key), ovm) > -1)) { ov.selected = "selected"; }
}
}
}
setAttributes(elem, options, ['value']);
}
break;
case "image":
case "file":
elem = document.createElement("input");
elem.type = eltype;
setAttributes(elem, options);
break;
case "custom":
elem = document.createElement("span");
try {
if ($.isFunction(options.custom_element)) {
var celm = options.custom_element.call($t, vl, options);
if (celm) {
celm = $(celm).addClass("customelement").attr({ id: options.id, name: options.name });
$(elem).empty().append(celm);
} else {
throw "e2";
}
} else {
throw "e1";
}
} catch (e) {
var errors = $.jgrid.getRegional($t, 'errors'),
edit = $.jgrid.getRegional($t, 'edit');
if (e === "e1") { $.jgrid.info_dialog(errors.errcap, "function 'custom_element' " + edit.msg.nodefined, edit.bClose, { styleUI: $t.p.styleUI }); }
else if (e === "e2") { $.jgrid.info_dialog(errors.errcap, "function 'custom_element' " + edit.msg.novalue, edit.bClose, { styleUI: $t.p.styleUI }); }
else { $.jgrid.info_dialog(errors.errcap, typeof e === "string" ? e : e.message, edit.bClose, { styleUI: $t.p.styleUI }); }
}
break;
default:
var role;
if (eltype === "button") { role = "button"; }
else { role = "textbox"; } // ???
elem = document.createElement("input");
elem.type = eltype;
elem.value = vl;
setAttributes(elem, options);
if (eltype !== "button") {
if (autowidth) {
if (!options.size) { $(elem).css({ width: "96%" }); }
} else if (!options.size) { options.size = 20; }
}
$(elem).attr("role", role);
}
return elem;
},
// Date Validation Javascript
checkDate: function (format, date) {
var daysInFebruary = function (year) {
// February has 29 days in any year evenly divisible by four,
// EXCEPT for centurial years which are not also divisible by 400.
return (((year % 4 === 0) && (year % 100 !== 0 || (year % 400 === 0))) ? 29 : 28);
},
tsp = {}, sep;
format = format.toLowerCase();
//we search for /,-,. for the date separator
if (format.indexOf("/") !== -1) {
sep = "/";
} else if (format.indexOf("-") !== -1) {
sep = "-";
} else if (format.indexOf(".") !== -1) {
sep = ".";
} else {
sep = "/";
}
format = format.split(sep);
date = date.split(sep);
if (date.length !== 3) { return false; }
var j = -1, yln, dln = -1, mln = -1, i;
for (i = 0; i < format.length; i++) {
var dv = isNaN(date[i]) ? 0 : parseInt(date[i], 10);
tsp[format[i]] = dv;
yln = format[i];
if (yln.indexOf("y") !== -1) { j = i; }
if (yln.indexOf("m") !== -1) { mln = i; }
if (yln.indexOf("d") !== -1) { dln = i; }
}
if (format[j] === "y" || format[j] === "yyyy") {
yln = 4;
} else if (format[j] === "yy") {
yln = 2;
} else {
yln = -1;
}
var daysInMonth = [0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
strDate;
if (j === -1) {
return false;
}
strDate = tsp[format[j]].toString();
if (yln === 2 && strDate.length === 1) { yln = 1; }
if (strDate.length !== yln || (tsp[format[j]] === 0 && date[j] !== "00")) {
return false;
}
if (mln === -1) {
return false;
}
strDate = tsp[format[mln]].toString();
if (strDate.length < 1 || tsp[format[mln]] < 1 || tsp[format[mln]] > 12) {
return false;
}
if (dln === -1) {
return false;
}
strDate = tsp[format[dln]].toString();
if (strDate.length < 1 || tsp[format[dln]] < 1 || tsp[format[dln]] > 31 || (tsp[format[mln]] === 2 && tsp[format[dln]] > daysInFebruary(tsp[format[j]])) || tsp[format[dln]] > daysInMonth[tsp[format[mln]]]) {
return false;
}
return true;
},
isEmpty: function (val) {
if (val.match(/^\s+$/) || val === "") {
return true;
}
return false;
},
checkTime: function (time) {
// checks only hh:ss (and optional am/pm)
var re = /^(\d{1,2}):(\d{2})([apAP][Mm])?$/, regs;
if (!$.jgrid.isEmpty(time)) {
regs = time.match(re);
if (regs) {
if (regs[3]) {
if (regs[1] < 1 || regs[1] > 12) { return false; }
} else {
if (regs[1] > 23) { return false; }
}
if (regs[2] > 59) {
return false;
}
} else {
return false;
}
}
return true;
},
checkValues: function (val, valref, customobject, nam) {
var edtrul, i, nm, dft, len, g = this, cm = g.p.colModel,
msg = $.jgrid.getRegional(this, 'edit.msg'), fmtdate;
if (customobject === undefined) {
if (typeof valref === 'string') {
for (i = 0, len = cm.length; i < len; i++) {
if (cm[i].name === valref) {
edtrul = cm[i].editrules;
valref = i;
if (cm[i].formoptions != null) { nm = cm[i].formoptions.label; }
break;
}
}
} else if (valref >= 0) {
edtrul = cm[valref].editrules;
}
} else {
edtrul = customobject;
nm = nam === undefined ? "_" : nam;
}
if (edtrul) {
if (!nm) { nm = g.p.colNames != null ? g.p.colNames[valref] : cm[valref].label; }
if (edtrul.required === true) {
if ($.jgrid.isEmpty(val)) { return [false, nm + ": " + msg.required, ""]; }
}
// force required
var rqfield = edtrul.required === false ? false : true;
if (edtrul.number === true) {
if (!(rqfield === false && $.jgrid.isEmpty(val))) {
if (isNaN(val)) { return [false, nm + ": " + msg.number, ""]; }
}
}
if (edtrul.minValue !== undefined && !isNaN(edtrul.minValue)) {
if (parseFloat(val) < parseFloat(edtrul.minValue)) { return [false, nm + ": " + msg.minValue + " " + edtrul.minValue, ""]; }
}
if (edtrul.maxValue !== undefined && !isNaN(edtrul.maxValue)) {
if (parseFloat(val) > parseFloat(edtrul.maxValue)) { return [false, nm + ": " + msg.maxValue + " " + edtrul.maxValue, ""]; }
}
var filter;
if (edtrul.email === true) {
if (!(rqfield === false && $.jgrid.isEmpty(val))) {
// taken from $ Validate plugin
filter = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i;
if (!filter.test(val)) { return [false, nm + ": " + msg.email, ""]; }
}
}
if (edtrul.integer === true) {
if (!(rqfield === false && $.jgrid.isEmpty(val))) {
if (isNaN(val)) { return [false, nm + ": " + msg.integer, ""]; }
if ((val % 1 !== 0) || (val.indexOf('.') !== -1)) { return [false, nm + ": " + msg.integer, ""]; }
}
}
if (edtrul.date === true) {
if (!(rqfield === false && $.jgrid.isEmpty(val))) {
if (cm[valref].formatoptions && cm[valref].formatoptions.newformat) {
dft = cm[valref].formatoptions.newformat;
fmtdate = $.jgrid.getRegional(g, 'formatter.date.masks');
if (fmtdate && fmtdate.hasOwnProperty(dft)) {
dft = fmtdate[dft];
}
} else {
dft = cm[valref].datefmt || "Y-m-d";
}
if (!$.jgrid.checkDate(dft, val)) { return [false, nm + ": " + msg.date + " - " + dft, ""]; }
}
}
if (edtrul.time === true) {
if (!(rqfield === false && $.jgrid.isEmpty(val))) {
if (!$.jgrid.checkTime(val)) { return [false, nm + ": " + msg.date + " - hh:mm (am/pm)", ""]; }
}
}
if (edtrul.url === true) {
if (!(rqfield === false && $.jgrid.isEmpty(val))) {
filter = /^(((https?)|(ftp)):\/\/([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\\/+@`~=%!]*)(\.\w{2,})?)*\/?)/i;
if (!filter.test(val)) { return [false, nm + ": " + msg.url, ""]; }
}
}
if (edtrul.custom === true) {
if (!(rqfield === false && $.jgrid.isEmpty(val))) {
if ($.isFunction(edtrul.custom_func)) {
var ret = edtrul.custom_func.call(g, val, nm, valref);
return $.isArray(ret) ? ret : [false, msg.customarray, ""];
}
return [false, msg.customfcheck, ""];
}
}
}
return [true, "", ""];
}
});
//module begin
$.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: [],
sortStrategy: null,
onChange: null,
afterRedraw: null,
checkValues: 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,
uniqueSearchFields: false,
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 (this.p.filter === null || this.p.filter === undefined) {
this.p.filter = {
groupOp: this.p.groupOps[0].op,
rules: [],
groups: []
};
}
// Sort the columns if the sort strategy is provided.
if (this.p.sortStrategy != null && $.isFunction(this.p.sortStrategy)) {
this.p.columns.sort(this.p.sortStrategy);
}
var i, len = this.p.columns.length, cl,
isIE = /msie/i.test(navigator.userAgent) && !window.opera;
// translating the options
this.p.initFilter = $.extend(true, {}, this.p.filter);
// set default values for the columns if they are not set
if (!len) { return; }
for (i = 0; i < len; i++) {
cl = this.p.columns[i];
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;
}
if (cl.index) {
cl.name = cl.index;
}
if (!cl.hasOwnProperty('searchoptions')) {
cl.searchoptions = {};
}
if (!cl.hasOwnProperty('searchrules')) {
cl.searchrules = {};
}
if (cl.search === undefined) {
cl.inlist = true;
} else {
cl.inlist = cl.search;
}
}
var getGrid = function () {
return $("#" + $.jgrid.jqID(p.id))[0] || null;
},
$tg = getGrid(),
classes = $.jgrid.styleUI[($tg.p.styleUI || 'jQueryUI')].filter,
common = $.jgrid.styleUI[($tg.p.styleUI || 'jQueryUI')].common;
if (this.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 (e) { }
}
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
this.p.error = false;
this.p.errmsg = "";
return $.isFunction(this.p.onChange) ? this.p.onChange.call(this, this.p) : 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(this.p.afterRedraw)) {
this.p.afterRedraw.call(this, this.p);
}
};
/*
* 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 (this.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)
.bind('change', function () {
group.groupOp = $(groupOpSelect).val();
that.onchange(); // signals that the filter has changed
});
}
// button for adding a new subgroup
var inputAddSubgroup = "";
if (this.p.groupButton) {
inputAddSubgroup = $("");
inputAddSubgroup.bind('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 (this.p.ruleButtons === true) {
// button for adding a new rule
var inputAddRule = $(""), cm;
inputAddRule.bind('click', function () {
//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
var 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;
}
}
if (!cm) {
return false;
}
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.bind('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) {
for (i = 0; i < group.groups.length; i++) {
var trHolderForSubgroup = $("
");
table.append(trHolderForSubgroup);
var tdFirstHolderForSubgroup = $("
");
trHolderForSubgroup.append(tdFirstHolderForSubgroup);
var tdMainHolderForSubgroup = $("
");
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
var suni = that.p.ruleButtons && that.p.uniqueSearchFields;
if (suni) {
for (var ii = 0; ii < that.p.columns.length; ii++) {
if (that.p.columns[ii].inlist) {
that.p.columns[ii].search = true;
}
}
}
if (group.rules !== undefined) {
for (i = 0; i < group.rules.length; i++) {
table.append(
this.createTableRowForRule(group.rules[i], group)
);
if (suni) {
var field = group.rules[i].field;
for (var ii = 0; ii < that.p.columns.length; ii++) {
if (field === that.p.columns[ii].name) {
that.p.columns[ii].search = false;
break;
}
}
}
}
}
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 = $("
"),
//document.createElement("tr"),
// first column used for padding
//tdFirstHolderForRule = document.createElement("td"),
i, op, trpar, cm, str = "", selected;
//tdFirstHolderForRule.setAttribute("class", "first");
tr.append("
");
// create field container
var ruleFieldTd = $("
");
tr.append(ruleFieldTd);
// dropdown for: choosing field
var ruleFieldSelect = $(""), ina, aoprs = [];
ruleFieldTd.append(ruleFieldSelect);
ruleFieldSelect.bind('change', function () {
rule.field = $(ruleFieldSelect).val();
trpar = $(this).parents("tr:first");
$(".data", trpar).empty();
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) { return; }
cm.searchoptions.id = $.jgrid.randId();
cm.searchoptions.name = rule.field;
cm.searchoptions.oper = 'filter';
if (isIE && cm.inputtype === "text") {
if (!cm.searchoptions.size) {
cm.searchoptions.size = 10;
}
}
var elm = $.jgrid.createEl.call($t, cm.inputtype, cm.searchoptions, "", true, that.p.ajaxSelectOptions || {}, true);
$(elm).addClass("input-elm " + classes.srInput);
//that.createElement(rule, "");
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; }
// operators
var s = "", so = 0;
aoprs = [];
$.each(that.p.ops, function () { aoprs.push(this.oper); });
for (i = 0 ; i < op.length; i++) {
ina = $.inArray(op[i], aoprs);
if (ina !== -1) {
if (so === 0) {
rule.op = that.p.ops[ina].oper;
}
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).append(elm);
$.jgrid.bindEv.call($t, elm, cm.searchoptions);
$(".input-elm", trpar).bind('change', function (e) {
var elem = e.target;
rule.data = elem.nodeName.toUpperCase() === "SPAN" && cm.searchoptions && $.isFunction(cm.searchoptions.custom_value) ?
cm.searchoptions.custom_value.call($t, $(elem).children(".customelement:first"), 'get') : elem.value;
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;
for (i = 0; i < that.p.columns.length; i++) {
// but show only serchable and serchhidden = true fields
var 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);
cm.searchoptions.id = $.jgrid.randId();
if (isIE && cm.inputtype === "text") {
if (!cm.searchoptions.size) {
cm.searchoptions.size = 10;
}
}
cm.searchoptions.name = rule.field;
cm.searchoptions.oper = 'filter';
var ruleDataInput = $.jgrid.createEl.call($t, cm.inputtype, cm.searchoptions, rule.data, true, that.p.ajaxSelectOptions || {}, true);
if (rule.op === 'nu' || rule.op === 'nn') {
$(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.bind('change', function () {
rule.op = $(ruleOperatorSelect).val();
trpar = $(this).parents("tr:first");
var rd = $(".input-elm", trpar)[0];
if (rule.op === "nu" || rule.op === "nn") { // 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 = "";
$.each(that.p.ops, function () { aoprs.push(this.oper); });
for (i = 0; i < op.length; i++) {
ina = $.inArray(op[i], aoprs);
if (ina !== -1) {
selected = rule.op === that.p.ops[ina].oper ? " 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);
$.jgrid.bindEv.call($t, ruleDataInput, cm.searchoptions);
$(ruleDataInput)
.addClass("input-elm " + classes.srInput)
.bind('change', function () {
rule.data = cm.inputtype === 'custom' ? cm.searchoptions.custom_value.call($t, $(this).children(".customelement:first"), 'get') : $(this).val();
that.onchange(); // signals that the filter has changed
});
// create action container
var ruleDeleteTd = $("
");
tr.append(ruleDeleteTd);
// create button for: delete rule
if (this.p.ruleButtons === true) {
var ruleDeleteInput = $("");
ruleDeleteTd.append(ruleDeleteInput);
//$(ruleDeleteInput).html("").height(20).width(30).button({icons: { primary: "ui-icon-minus", text:false}});
ruleDeleteInput.bind('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) { alert(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) { alert(e); }
}
s += ")";
if (s === "()") {
return ""; // ignore groups that don't have rules
}
return s;
};
this.getStringForRule = function (rule) {
var opUF = "", opC = "", i, cm, ret, val,
numtypes = ['int', 'integer', 'float', 'number', 'currency']; // jqGrid
for (i = 0; i < this.p.ops.length; i++) {
if (this.p.ops[i].oper === rule.op) {
opUF = this.p.operands.hasOwnProperty(rule.op) ? this.p.operands[rule.op] : "";
opC = this.p.ops[i].oper;
break;
}
}
for (i = 0; i < this.p.columns.length; i++) {
if (this.p.columns[i].name === rule.field) {
cm = this.p.columns[i];
break;
}
}
if (cm === undefined) { return ""; }
val = rule.data;
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') { ret = rule.field + " " + opUF + " " + val; }
else { ret = rule.field + " " + opUF + " \"" + val + "\""; }
return ret;
};
this.resetFilter = function () {
this.p.filter = $.extend(true, {}, this.p.initFilter);
this.reDraw();
this.onchange();
};
this.hideError = function () {
$("th." + common.error, this).html("");
$("tr.error", this).hide();
};
this.showError = function () {
$("th." + common.error, this).html(this.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(this.p.filter);
};
// Here we init the filter
this.reDraw();
if (this.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 = $.jgrid.parse(pfilter);
}
this.each(function () {
this.p.filter = pfilter;
this.reDraw();
this.onchange();
});
}
});
$.jgrid.extend({
filterToolbar: function (p) {
var regional = $.jgrid.getRegional(this[0], 'search');
p = $.extend({
autosearch: true,
autosearchDelay: 500,
searchOnEnter: true,
beforeSearch: null,
afterSearch: null,
beforeClear: null,
afterClear: null,
onClearSearchValue: null,
searchurl: '',
stringResult: false,
groupOp: 'AND',
defaultSearch: "bw",
searchOperators: false,
resetIcon: "x",
splitSelect: ",",
groupOpSelect: "OR",
operands: { "eq": "==", "ne": "!", "lt": "<", "le": "<=", "gt": ">", "ge": ">=", "bw": "^", "bn": "!^", "in": "=", "ni": "!=", "ew": "|", "en": "!@", "cn": "~", "nc": "!~", "nu": "#", "nn": "!#", "bt": "..." }
}, regional, p || {});
return this.each(function () {
var $t = this;
if ($t.p.filterToolbar) { return; }
if (!$($t).data('filterToolbar')) {
$($t).data('filterToolbar', p);
}
if ($t.p.force_regional) {
p = $.extend(p, regional);
}
var classes = $.jgrid.styleUI[($t.p.styleUI || 'jQueryUI')].filter,
common = $.jgrid.styleUI[($t.p.styleUI || 'jQueryUI')].common,
base = $.jgrid.styleUI[($t.p.styleUI || 'jQueryUI')].base,
triggerToolbar = function () {
var sdata = {}, j = 0, v, nm, sopt = {}, so, ms = false, ssfield = [], bbt = false, sop;
$.each($t.p.colModel, function () {
var $elem = $("#gs_" + $t.p.idPrefix + $.jgrid.jqID(this.name), (this.frozen === true && $t.p.frozenColumns === true) ? $t.grid.fhDiv : $t.grid.hDiv);
nm = this.index || this.name;
sop = this.searchoptions || {};
if (p.searchOperators && sop.searchOperMenu) {
so = $elem.parent().prev().children("a").attr("soper") || p.defaultSearch;
} else {
so = (sop.sopt) ? sop.sopt[0] : this.stype === 'select' ? 'eq' : p.defaultSearch;
}
v = this.stype === "custom" && $.isFunction(sop.custom_value) && $elem.length > 0 && $elem[0].nodeName.toUpperCase() === "SPAN" ?
sop.custom_value.call($t, $elem.children(".customelement:first"), "get") :
$elem.val();
// detect multiselect
if (this.stype === 'select' && sop.multiple && $.isArray(v) && v.length) {
ms = true;
ssfield.push(nm);
v = v.length === 1 ? v[0] : v;
}
if (so === "bt") {
bbt = true;
}
if (v || so === "nu" || so === "nn") {
sdata[nm] = v;
sopt[nm] = so;
j++;
} else {
try {
delete $t.p.postData[nm];
} catch (z) { }
}
});
var sd = j > 0 ? true : false;
if (p.stringResult === true || $t.p.datatype === "local" || p.searchOperators === true) {
var ruleGroup = "{\"groupOp\":\"" + p.groupOp + "\",\"rules\":[";
var gi = 0;
$.each(sdata, function (i, n) {
if (gi > 0) { ruleGroup += ","; }
ruleGroup += "{\"field\":\"" + i + "\",";
ruleGroup += "\"op\":\"" + sopt[i] + "\",";
n += "";
ruleGroup += "\"data\":\"" + n.replace(/\\/g, '\\\\').replace(/\"/g, '\\"') + "\"}";
gi++;
});
ruleGroup += "]}";
// multiselect
var filters, rules, k, str, rule, ssdata, group;
if (ms) {
filters = $.jgrid.parse(ruleGroup);//, rules, k,str, rule, ssdata, group;
if (filters.rules && filters.rules.length) {
rules = filters.rules;
for (k = 0; k < rules.length; k++) {
rule = rules[k];
if ($.inArray(rule.filed, ssfield)) {
ssdata = rule.data.split(p.splitSelect);
if (ssdata.length > 1) {
if (filters.groups === undefined) {
filters.groups = [];
}
group = { groupOp: p.groupOpSelect, groups: [], rules: [] };
filters.groups.push(group);
$.each(ssdata, function (l) {
str = ssdata[l];
if (str) {
group.rules.push({ data: ssdata[l], op: rule.op, field: rule.field });
}
});
rules.splice(k, 1);
k--;
}
}
}
}
//ruleGroup = JSON.stringify( filters );
}
if (bbt) {
if (!$.isPlainObject(filters)) {
filters = $.jgrid.parse(ruleGroup);
}
if (filters.rules && filters.rules.length) {
rules = filters.rules;
for (k = 0; k < rules.length; k++) {
rule = rules[k];
if (rule.op === "bt") {
ssdata = rule.data.split("...");
if (ssdata.length > 1) {
if (filters.groups === undefined) {
filters.groups = [];
}
group = { groupOp: 'AND', groups: [], rules: [] };
filters.groups.push(group);
$.each(ssdata, function (l) {
var btop = l === 0 ? 'ge' : 'le';
str = ssdata[l];
if (str) {
group.rules.push({ data: ssdata[l], op: btop, field: rule.field });
}
});
rules.splice(k, 1);
k--;
}
}
}
}
}
if (bbt || ms) {
ruleGroup = JSON.stringify(filters);
}
$.extend($t.p.postData, { filters: ruleGroup });
$.each(['searchField', 'searchString', 'searchOper'], function (i, n) {
if ($t.p.postData.hasOwnProperty(n)) { delete $t.p.postData[n]; }
});
} else {
$.extend($t.p.postData, sdata);
}
var saveurl;
if ($t.p.searchurl) {
saveurl = $t.p.url;
$($t).jqGrid("setGridParam", { url: $t.p.searchurl });
}
var bsr = $($t).triggerHandler("jqGridToolbarBeforeSearch") === 'stop' ? true : false;
if (!bsr && $.isFunction(p.beforeSearch)) { bsr = p.beforeSearch.call($t); }
if (!bsr) { $($t).jqGrid("setGridParam", { search: sd }).trigger("reloadGrid", [{ page: 1 }]); }
if (saveurl) { $($t).jqGrid("setGridParam", { url: saveurl }); }
$($t).triggerHandler("jqGridToolbarAfterSearch");
if ($.isFunction(p.afterSearch)) { p.afterSearch.call($t); }
},
clearToolbar = function (trigger) {
var sdata = {}, j = 0, nm;
trigger = (typeof trigger !== 'boolean') ? true : trigger;
$.each($t.p.colModel, function () {
var v, $elem = $("#gs_" + $t.p.idPrefix + $.jgrid.jqID(this.name), (this.frozen === true && $t.p.frozenColumns === true) ? $t.grid.fhDiv : $t.grid.hDiv);
if (this.searchoptions && this.searchoptions.defaultValue !== undefined) {
v = this.searchoptions.defaultValue;
}
nm = this.index || this.name;
switch (this.stype) {
case 'select':
$elem.find("option").each(function (i) {
if (i === 0) { this.selected = true; }
if ($(this).val() === v) {
this.selected = true;
return false;
}
});
if (v !== undefined) {
// post the key and not the text
sdata[nm] = v;
j++;
} else {
try {
delete $t.p.postData[nm];
} catch (e) { }
}
break;
case 'text':
$elem.val(v || "");
if (v !== undefined) {
sdata[nm] = v;
j++;
} else {
try {
delete $t.p.postData[nm];
} catch (y) { }
}
break;
case 'custom':
if ($.isFunction(this.searchoptions.custom_value) && $elem.length > 0 && $elem[0].nodeName.toUpperCase() === "SPAN") {
this.searchoptions.custom_value.call($t, $elem.children(".customelement:first"), "set", v || "");
}
break;
}
});
var sd = j > 0 ? true : false;
$t.p.resetsearch = true;
if (p.stringResult === true || $t.p.datatype === "local") {
var ruleGroup = "{\"groupOp\":\"" + p.groupOp + "\",\"rules\":[";
var gi = 0;
$.each(sdata, function (i, n) {
if (gi > 0) { ruleGroup += ","; }
ruleGroup += "{\"field\":\"" + i + "\",";
ruleGroup += "\"op\":\"" + "eq" + "\",";
n += "";
ruleGroup += "\"data\":\"" + n.replace(/\\/g, '\\\\').replace(/\"/g, '\\"') + "\"}";
gi++;
});
ruleGroup += "]}";
$.extend($t.p.postData, { filters: ruleGroup });
$.each(['searchField', 'searchString', 'searchOper'], function (i, n) {
if ($t.p.postData.hasOwnProperty(n)) { delete $t.p.postData[n]; }
});
} else {
$.extend($t.p.postData, sdata);
}
var saveurl;
if ($t.p.searchurl) {
saveurl = $t.p.url;
$($t).jqGrid("setGridParam", { url: $t.p.searchurl });
}
var bcv = $($t).triggerHandler("jqGridToolbarBeforeClear") === 'stop' ? true : false;
if (!bcv && $.isFunction(p.beforeClear)) { bcv = p.beforeClear.call($t); }
if (!bcv) {
if (trigger) {
$($t).jqGrid("setGridParam", { search: sd }).trigger("reloadGrid", [{ page: 1 }]);
}
}
if (saveurl) { $($t).jqGrid("setGridParam", { url: saveurl }); }
$($t).triggerHandler("jqGridToolbarAfterClear");
if ($.isFunction(p.afterClear)) { p.afterClear(); }
},
toggleToolbar = function () {
var trow = $("tr.ui-search-toolbar", $t.grid.hDiv),
trow2 = $t.p.frozenColumns === true ? $("tr.ui-search-toolbar", $t.grid.fhDiv) : false;
if (trow.css("display") === 'none') {
trow.show();
if (trow2) {
trow2.show();
}
} else {
trow.hide();
if (trow2) {
trow2.hide();
}
}
},
buildRuleMenu = function (elem, left, top) {
$("#sopt_menu").remove();
left = parseInt(left, 10);
top = parseInt(top, 10) + 18;
var fs = $('.ui-jqgrid-view').css('font-size') || '11px';
var str = '
',
selected = $(elem).attr("soper"), selclass,
aoprs = [], ina;
var i = 0, nm = $(elem).attr("colname"), len = $t.p.colModel.length;
while (i < len) {
if ($t.p.colModel[i].name === nm) {
break;
}
i++;
}
var cm = $t.p.colModel[i], options = $.extend({}, cm.searchoptions);
if (!options.sopt) {
options.sopt = [];
options.sopt[0] = cm.stype === 'select' ? 'eq' : p.defaultSearch;
}
$.each(p.odata, function () { aoprs.push(this.oper); });
for (i = 0 ; i < options.sopt.length; i++) {
ina = $.inArray(options.sopt[i], aoprs);
if (ina !== -1) {
selclass = selected === p.odata[ina].oper ? common.highlight : "";
str += '
' + p.operands[p.odata[ina].oper] + '
' + p.odata[ina].text + '
';
}
}
str += "
";
$('body').append(str);
$("#sopt_menu").addClass("ui-menu " + classes.menu_widget);
$("#sopt_menu > li > a").hover(
function () { $(this).addClass(common.hover); },
function () { $(this).removeClass(common.hover); }
).click(function () {
var v = $(this).attr("value"),
oper = $(this).attr("oper");
$($t).triggerHandler("jqGridToolbarSelectOper", [v, oper, elem]);
$("#sopt_menu").hide();
$(elem).text(oper).attr("soper", v);
if (p.autosearch === true) {
var inpelm = $(elem).parent().next().children()[0];
if ($(inpelm).val() || v === "nu" || v === "nn") {
triggerToolbar();
}
}
});
};
// create the row
var tr = $("
"),
timeoutHnd, rules, filterobj;
if (p.restoreFromFilters) {
filterobj = $t.p.postData.filters;
if (filterobj) {
if (typeof filterobj === "string") {
filterobj = $.jgrid.parse(filterobj);
}
rules = filterobj.rules.length ? filterobj.rules : false;
}
}
$.each($t.p.colModel, function (ci) {
var cm = this, soptions, select = "", sot = "=", so, i, st, csv, df, elem, restores,
th = $("
"),
thd = $(""),
stbl = $("
");
if (this.hidden === true) { $(th).css("display", "none"); }
this.search = this.search === false ? false : true;
if (this.stype === undefined) { this.stype = 'text'; }
this.searchoptions = this.searchoptions || {};
if (this.searchoptions.searchOperMenu === undefined) {
this.searchoptions.searchOperMenu = true;
}
soptions = $.extend({}, this.searchoptions, { name: cm.index || cm.name, id: "gs_" + $t.p.idPrefix + cm.name, oper: 'search' });
if (this.search) {
if (p.restoreFromFilters && rules) {
restores = false;
for (var is = 0; is < rules.length; is++) {
if (rules[is].field) {
var snm = cm.index || cm.name;
if (snm === rules[is].field) {
restores = rules[is];
break;
}
}
}
}
if (p.searchOperators) {
so = (soptions.sopt) ? soptions.sopt[0] : cm.stype === 'select' ? 'eq' : p.defaultSearch;
// overwrite search operators
if (p.restoreFromFilters && restores) {
so = restores.op;
}
for (i = 0; i < p.odata.length; i++) {
if (p.odata[i].oper === so) {
sot = p.operands[so] || "";
break;
}
}
st = soptions.searchtitle != null ? soptions.searchtitle : p.operandTitle;
select = this.searchoptions.searchOperMenu ? "" + sot + "" : "";
}
$("td:eq(0)", stbl).attr("colindex", ci).append(select);
if (soptions.clearSearch === undefined) {
soptions.clearSearch = true;
}
if (soptions.clearSearch) {
csv = p.resetTitle || 'Clear Search Value';
$("td:eq(2)", stbl).append("" + p.resetIcon + "");
} else {
$("td:eq(2)", stbl).hide();
}
if (this.surl) {
soptions.dataUrl = this.surl;
}
df = "";
if (soptions.defaultValue) {
df = $.isFunction(soptions.defaultValue) ? soptions.defaultValue.call($t) : soptions.defaultValue;
}
//overwrite default value if restore from filters
if (p.restoreFromFilters && restores) {
df = restores.data;
}
elem = $.jgrid.createEl.call($t, this.stype, soptions, df, false, $.extend({}, $.jgrid.ajaxOptions, $t.p.ajaxSelectOptions || {}));
$(elem).addClass(classes.srInput);
$("td:eq(1)", stbl).append(elem);
$(thd).append(stbl);
if (soptions.dataEvents == null) {
soptions.dataEvents = [];
}
switch (this.stype) {
case "select":
if (p.autosearch === true) {
soptions.dataEvents.push({
type: "change",
fn: function () {
triggerToolbar();
return false;
}
});
}
break;
case "text":
if (p.autosearch === true) {
if (p.searchOnEnter) {
soptions.dataEvents.push({
type: "keypress",
fn: function (e) {
var key = e.charCode || e.keyCode || 0;
if (key === 13) {
triggerToolbar();
return false;
}
return this;
}
});
} else {
soptions.dataEvents.push({
type: "keydown",
fn: function (e) {
var key = e.which;
switch (key) {
case 13:
return false;
case 9:
case 16:
case 37:
case 38:
case 39:
case 40:
case 27:
break;
default:
if (timeoutHnd) { clearTimeout(timeoutHnd); }
timeoutHnd = setTimeout(function () { triggerToolbar(); }, p.autosearchDelay);
}
}
});
}
}
break;
}
$.jgrid.bindEv.call($t, elem, soptions);
}
$(th).append(thd);
$(tr).append(th);
if (!p.searchOperators || select === "") {
$("td:eq(0)", stbl).hide();
}
});
$("table thead", $t.grid.hDiv).append(tr);
if (p.searchOperators) {
$(".soptclass", tr).click(function (e) {
var offset = $(this).offset(),
left = (offset.left),
top = (offset.top);
buildRuleMenu(this, left, top);
e.stopPropagation();
});
$("body").on('click', function (e) {
if (e.target.className !== "soptclass") {
$("#sopt_menu").remove();
}
});
}
$(".clearsearchclass", tr).click(function () {
var ptr = $(this).parents("tr:first"),
coli = parseInt($("td.ui-search-oper", ptr).attr('colindex'), 10),
sval = $.extend({}, $t.p.colModel[coli].searchoptions || {}),
dval = sval.defaultValue ? sval.defaultValue : "",
elem;
if ($t.p.colModel[coli].stype === "select") {
elem = $("td.ui-search-input select", ptr);
if (dval) {
elem.val(dval);
} else {
elem[0].selectedIndex = 0;
}
} else {
elem = $("td.ui-search-input input", ptr);
elem.val(dval);
}
$($t).triggerHandler("jqGridToolbarClearVal", [elem[0], coli, sval, dval]);
if ($.isFunction(p.onClearSearchValue)) {
p.onClearSearchValue.call($t, elem[0], coli, sval, dval);
}
// ToDo custom search type
if (p.autosearch === true) {
triggerToolbar();
}
});
this.p.filterToolbar = true;
this.triggerToolbar = triggerToolbar;
this.clearToolbar = clearToolbar;
this.toggleToolbar = toggleToolbar;
});
},
destroyFilterToolbar: function () {
return this.each(function () {
if (!this.p.filterToolbar) {
return;
}
this.triggerToolbar = null;
this.clearToolbar = null;
this.toggleToolbar = null;
this.p.filterToolbar = false;
$(this.grid.hDiv).find("table thead tr.ui-search-toolbar").remove();
});
},
refreshFilterToolbar: function (p) {
p = $.extend(true, {
filters: "",
onClearVal: null,
onSetVal: null
}, p || {});
return this.each(function () {
var $t = this, cm = $t.p.colModel, i, l = $t.p.colModel.length,
searchitem, filters, rules, rule, ssfield = [], ia;
// clear the values on toolbar.
// do not call clearToolbar
if (!$t.p.filterToolbar) {
return;
}
for (i = 0; i < l; i++) {
ssfield.push(cm[i].name);
searchitem = $("#gs_" + $t.p.idPrefix + $.jgrid.jqID(cm[i].name));
switch (cm[i].stype) {
case 'select':
case 'text':
searchitem.val("");
break;
}
if ($.isFunction(p.onClearVal)) {
p.onClearVal.call($t, searchitem, cm[i].name);
}
}
function setrules(filter) {
if (filter && filter.rules) { // condition to exit
rules = filter.rules;
l = rules.length;
for (i = 0; i < l; i++) {
rule = rules[i];
ia = $.inArray(rule.field, ssfield);
if (ia !== -1) {
searchitem = $("#gs_" + $t.p.idPrefix + $.jgrid.jqID(cm[ia].name));
// problem for between operator
if (searchitem.length > 0) {
if (cm[ia].stype === "select") {
searchitem.find("option[value='" + $.jgrid.jqID(rule.data) + "']").prop('selected', true);
} else if (cm[ia].stype === "text") {
searchitem.val(rule.data);
}
if ($.isFunction(p.onSetVal)) {
p.onSetVal.call($t, searchitem, cm[ia].name);
}
}
}
}
if (filter.groups) {
for (var k = 0; k < filter.groups.length; k++) {
setrules(filter.groups[k]);
}
}
}
}
if (typeof (p.filters) === "string" && p.filters.length) {
filters = $.jgrid.parse(p.filters);
// flat filters only
}
if ($.isPlainObject(filters)) {
setrules(filters);
}
});
},
searchGrid: function (p) {
var regional = $.jgrid.getRegional(this[0], 'search');
p = $.extend(true, {
recreateFilter: false,
drag: true,
sField: 'searchField',
sValue: 'searchString',
sOper: 'searchOper',
sFilter: '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,
sortStrategy: null,
closeAfterSearch: false,
closeAfterReset: false,
closeOnEscape: false,
searchOnEnter: false,
multipleSearch: false,
multipleGroup: false,
//cloneSearchRowOnAdd: true,
top: 0,
left: 0,
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: true,
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": "ISNOT NULL" }
}, regional, p || {});
return this.each(function () {
var $t = this;
if (!$t.grid) { return; }
var fid = "fbox_" + $t.p.id,
showFrm = true,
mustReload = true,
IDs = { themodal: 'searchmod' + fid, modalhead: 'searchhd' + fid, modalcontent: 'searchcnt' + fid, scrollelm: fid },
defaultFilters = $t.p.postData[p.sFilter],
fl,
classes = $.jgrid.styleUI[($t.p.styleUI || 'jQueryUI')].filter,
common = $.jgrid.styleUI[($t.p.styleUI || 'jQueryUI')].common;
p.styleUI = $t.p.styleUI;
if (typeof defaultFilters === "string") {
defaultFilters = $.jgrid.parse(defaultFilters);
}
if (p.recreateFilter === true) {
$("#" + $.jgrid.jqID(IDs.themodal)).remove();
}
function showFilter(_filter) {
showFrm = $($t).triggerHandler("jqGridFilterBeforeShow", [_filter]);
if (showFrm === undefined) {
showFrm = true;
}
if (showFrm && $.isFunction(p.beforeShowSearch)) {
showFrm = p.beforeShowSearch.call($t, _filter);
}
if (showFrm) {
$.jgrid.viewModal("#" + $.jgrid.jqID(IDs.themodal), { gbox: "#gbox_" + $.jgrid.jqID(fid), jqm: p.jqModal, modal: p.modal, overlay: p.overlay, toTop: p.toTop });
$($t).triggerHandler("jqGridFilterAfterShow", [_filter]);
if ($.isFunction(p.afterShowSearch)) {
p.afterShowSearch.call($t, _filter);
}
}
}
if ($("#" + $.jgrid.jqID(IDs.themodal))[0] !== undefined) {
showFilter($("#fbox_" + $.jgrid.jqID($t.p.id)));
} else {
var fil = $("
").insertBefore("#gview_" + $.jgrid.jqID($t.p.id)),
align = "left", butleft = "";
if ($t.p.direction === "rtl") {
align = "right";
butleft = " style='text-align:left'";
fil.attr("dir", "rtl");
}
var columns = $.extend([], $t.p.colModel),
bS = "" + p.Find + "",
bC = "" + p.Reset + "",
bQ = "", tmpl = "", colnm, found = false, bt, cmi = -1;
if (p.showQuery) {
bQ = "Query";
}
if (!p.columns.length) {
$.each(columns, function (i, n) {
if (!n.label) {
n.label = $t.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 = p.columns;
cmi = 0;
colnm = columns[0].index || columns[0].name;
}
// old behaviour
if ((!defaultFilters && colnm) || p.multipleSearch === false) {
var cmop = "eq";
if (cmi >= 0 && columns[cmi].searchoptions && columns[cmi].searchoptions.sopt) {
cmop = columns[cmi].searchoptions.sopt[0];
} else if (p.sopt && p.sopt.length) {
cmop = p.sopt[0];
}
defaultFilters = { groupOp: "AND", rules: [{ field: colnm, op: cmop, data: "" }] };
}
found = false;
if (p.tmplNames && p.tmplNames.length) {
found = true;
tmpl = "
";
}
toEnd = jj;
}
}
});
$("#" + $.jgrid.jqID($t.p.id) + " tbody:first").append(str);
// free up memory
str = null;
});
},
groupingGroupBy: function (name, options) {
return this.each(function () {
var $t = this;
if (typeof name === "string") {
name = [name];
}
var grp = $t.p.groupingView;
$t.p.grouping = true;
grp._locgr = false;
//Set default, in case visibilityOnNextGrouping is undefined
if (grp.visibiltyOnNextGrouping === undefined) {
grp.visibiltyOnNextGrouping = [];
}
var i;
// show previous hidden groups if they are hidden and weren't removed yet
for (i = 0; i < grp.groupField.length; i++) {
if (!grp.groupColumnShow[i] && grp.visibiltyOnNextGrouping[i]) {
$($t).jqGrid('showCol', grp.groupField[i]);
}
}
// set visibility status of current group columns on next grouping
for (i = 0; i < name.length; i++) {
grp.visibiltyOnNextGrouping[i] = $("#" + $.jgrid.jqID($t.p.id) + "_" + $.jgrid.jqID(name[i])).is(":visible");
}
$t.p.groupingView = $.extend($t.p.groupingView, options || {});
grp.groupField = name;
$($t).trigger("reloadGrid");
});
},
groupingRemove: function (current) {
return this.each(function () {
var $t = this;
if (current === undefined) {
current = true;
}
$t.p.grouping = false;
if (current === true) {
var grp = $t.p.groupingView, i;
// show previous hidden groups if they are hidden and weren't removed yet
for (i = 0; i < grp.groupField.length; i++) {
if (!grp.groupColumnShow[i] && grp.visibiltyOnNextGrouping[i]) {
$($t).jqGrid('showCol', grp.groupField);
}
}
$("tr.jqgroup, tr.jqfoot", "#" + $.jgrid.jqID($t.p.id) + " tbody:first").remove();
$("tr.jqgrow:hidden", "#" + $.jgrid.jqID($t.p.id) + " tbody:first").show();
} else {
$($t).trigger("reloadGrid");
}
});
},
groupingCalculations: {
handler: function (fn, v, field, round, roundType, rc) {
var funcs = {
sum: function () {
return parseFloat(v || 0) + parseFloat((rc[field] || 0));
},
min: function () {
if (v === "") {
return parseFloat(rc[field] || 0);
}
return Math.min(parseFloat(v), parseFloat(rc[field] || 0));
},
max: function () {
if (v === "") {
return parseFloat(rc[field] || 0);
}
return Math.max(parseFloat(v), parseFloat(rc[field] || 0));
},
count: function () {
if (v === "") { v = 0; }
if (rc.hasOwnProperty(field)) {
return v + 1;
}
return 0;
},
avg: function () {
// the same as sum, but at end we divide it
// so use sum instead of duplicating the code (?)
return funcs.sum();
}
};
if (!funcs[fn]) {
throw ("jqGrid Grouping No such method: " + fn);
}
var res = funcs[fn]();
if (round != null) {
if (roundType === 'fixed') {
res = res.toFixed(round);
} else {
var mul = Math.pow(10, round);
res = Math.round(res * mul) / mul;
}
}
return res;
}
},
setGroupHeaders: function (o) {
o = $.extend({
useColSpanStyle: false,
groupHeaders: []
}, o || {});
return this.each(function () {
var ts = this,
i, cmi, skip = 0, $tr, $colHeader, th, $th, thStyle,
iCol,
cghi,
//startColumnName,
numberOfColumns,
titleText,
cVisibleColumns,
className,
colModel = ts.p.colModel,
cml = colModel.length,
ths = ts.grid.headers,
$htable = $("table.ui-jqgrid-htable", ts.grid.hDiv),
$trLabels = $htable.children("thead").children("tr.ui-jqgrid-labels:last").addClass("jqg-second-row-header"),
$thead = $htable.children("thead"),
$theadInTable,
$firstHeaderRow = $htable.find(".jqg-first-row-header"),
//classes = $.jgrid.styleUI[($t.p.styleUI || 'jQueryUI')]['grouping'],
base = $.jgrid.styleUI[(ts.p.styleUI || 'jQueryUI')].base;
if (!ts.p.groupHeader) {
ts.p.groupHeader = [];
}
ts.p.groupHeader.push(o);
if ($firstHeaderRow[0] === undefined) {
$firstHeaderRow = $('
', { role: "row", "aria-hidden": "true" }).addClass("jqg-first-row-header").css("height", "auto");
} else {
$firstHeaderRow.empty();
}
var $firstRow,
inColumnHeader = function (text, columnHeaders) {
var length = columnHeaders.length, i;
for (i = 0; i < length; i++) {
if (columnHeaders[i].startColumnName === text) {
return i;
}
}
return -1;
};
$(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
thStyle = { height: '0px', width: ths[i].width + 'px', display: (cmi.hidden ? 'none' : '') };
$("
", { role: 'gridcell' }).css(thStyle).addClass("ui-first-th-" + ts.p.direction).appendTo($firstHeaderRow);
th.style.width = ""; // remove unneeded style
iCol = inColumnHeader(cmi.name, o.groupHeaders);
if (iCol >= 0) {
cghi = o.groupHeaders[iCol];
numberOfColumns = cghi.numberOfColumns;
titleText = cghi.titleText;
className = cghi.className || "";
// 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) {
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 = $('
').attr({ role: "columnheader" })
.addClass(base.headerBox + " ui-th-column-header ui-th-" + ts.p.direction + " " + className)
//.css({'height':'22px', 'border-top': '0 none'})
.html(titleText);
if (cVisibleColumns > 0) {
$colHeader.attr("colspan", String(cVisibleColumns));
}
if (ts.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 coumter 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", "2");
} else {
$('
', { role: "columnheader" })
.addClass(base.headerBox + " ui-th-column-header ui-th-" + ts.p.direction)
.css({ "display": cmi.hidden ? 'none' : '' })
.insertBefore($th);
$tr.append(th);
}
} else {
// move the header to the next row
//$th.css({"padding-top": "2px", height: "19px"});
$tr.append(th);
skip--;
}
}
}
$theadInTable = $(ts).children("thead");
$theadInTable.prepend($firstHeaderRow);
$tr.insertAfter($trLabels);
$htable.append($theadInTable);
if (o.useColSpanStyle) {
// Increase the height of resizing span of visible headers
$htable.find("span.ui-jqgrid-resize").each(function () {
var $parent = $(this).parent();
if ($parent.is(":visible")) {
this.style.cssText = 'height: ' + $parent.height() + 'px !important; cursor: col-resize;';
}
});
// Set position of the sortable div (the main lable)
// with the column header text to the middle of the cell.
// One should not do this for hidden headers.
$htable.find("div.ui-jqgrid-sortable").each(function () {
var $ts = $(this), $parent = $ts.parent();
if ($parent.is(":visible") && $parent.is(":has(span.ui-jqgrid-resize)")) {
// minus 4px from the margins of the resize markers
$ts.css('top', ($parent.height() - $ts.outerHeight()) / 2 - 4 + 'px');
}
});
}
$firstRow = $theadInTable.find("tr.jqg-first-row-header");
$(ts).bind('jqGridResizeStop.setGroupHeaders', function (e, nw, idx) {
$firstRow.find('th').eq(idx)[0].style.width = nw + "px";
});
});
},
destroyGroupHeader: function (nullHeader) {
if (nullHeader === undefined) {
nullHeader = true;
}
return this.each(function () {
var $t = this, $tr, i, l, headers, $th, $resizing, grid = $t.grid,
thead = $("table.ui-jqgrid-htable thead", grid.hDiv), cm = $t.p.colModel, hc;
if (!grid) { return; }
$(this).unbind('.setGroupHeaders');
$tr = $("
", { role: "row" }).addClass("ui-jqgrid-labels");
headers = grid.headers;
for (i = 0, l = headers.length; i < l; i++) {
hc = cm[i].hidden ? "none" : "";
$th = $(headers[i].el)
.width(headers[i].width)
.css('display', hc);
try {
$th.removeAttr("rowSpan");
} catch (rs) {
//IE 6/7
$th.attr("rowSpan", 1);
}
$tr.append($th);
$resizing = $th.children("span.ui-jqgrid-resize");
if ($resizing.length > 0) {// resizable column
$resizing[0].style.height = "";
}
$th.children("div")[0].style.top = "";
}
$(thead).children('tr.ui-jqgrid-labels').remove();
$(thead).prepend($tr);
if (nullHeader === true) {
$($t).jqGrid('setGridParam', { 'groupHeader': null });
}
});
}
});
//module begin
$.jgrid = $.jgrid || {};
$.extend($.jgrid, {
saveState: function (jqGridId, o) {
o = $.extend({
useStorage: true,
storageType: "localStorage", // localStorage or sessionStorage
beforeSetItem: null,
compression: false,
compressionModule: 'LZString', // object by example gzip, LZString
compressionMethod: 'compressToUTF16', // string by example zip, compressToUTF16
debug: false
}, o || {});
if (!jqGridId) { return; }
var gridstate = "", data = "", ret, $t = $("#" + jqGridId)[0], tmp;
// to use navigator set storeNavOptions to true in grid options
if (!$t.grid) { return; }
tmp = $($t).data('inlineNav');
if (tmp && $t.p.inlineNav) {
$($t).jqGrid('setGridParam', { _iN: tmp });
}
tmp = $($t).data('filterToolbar');
if (tmp && $t.p.filterToolbar) {
$($t).jqGrid('setGridParam', { _fT: tmp });
}
gridstate = $($t).jqGrid('jqGridExport', { exptype: "jsonstring", ident: "", root: "" });
data = $($t.grid.bDiv).find(".ui-jqgrid-btable tbody:first").html();
var firstrow = data.indexOf("
");
data = data.slice(firstrow + 5);
if ($.isFunction(o.beforeSetItem)) {
ret = o.beforeSetItem.call($t, gridstate);
if (ret != null) {
gridstate = ret;
}
}
if (o.debug) {
$("#gbox_tree").prepend('Click to save Dump Data');
var temp = [], file, properties = {}, url;
temp.push("Grid Options\n");
temp.push(gridstate);
temp.push("\n");
temp.push("GridData\n");
temp.push(data);
properties.type = 'plain/text;charset=utf-8'; // Specify the file's mime-type.
try {
file = new File(temp, "jqGrid_dump.txt", properties);
} catch (e) {
file = new Blob(temp, properties);
}
//saveAs(file, "jqGrid_dump.txt" );
url = URL.createObjectURL(file);
$("#link_save").attr("href", url).bind('click', function () {
$(this).remove();
});
}
if (o.compression) {
if (o.compressionModule) {
try {
ret = window[o.compressionModule][o.compressionMethod](gridstate);
if (ret != null) {
gridstate = ret;
data = window[o.compressionModule][o.compressionMethod](data);
}
} catch (e) {
// can not execute a compression.
}
}
}
if (o.useStorage && $.jgrid.isLocalStorage()) {
try {
window[o.storageType].setItem("jqGrid" + $t.p.id, gridstate);
window[o.storageType].setItem("jqGrid" + $t.p.id + "_data", data);
} catch (e) {
if (e.code === 22) { // chrome is 21
// just for now. we should make some additionla changes and eventually clear some local items
alert("Local storage limit is over!");
}
}
}
return gridstate;
},
loadState: function (jqGridId, gridstring, o) {
o = $.extend({
useStorage: true,
storageType: "localStorage",
clearAfterLoad: false, // clears the jqGrid localStorage items aftre load
beforeSetGrid: null,
afterSetGrid: null,
decompression: false,
decompressionModule: 'LZString', // object by example gzip, LZString
decompressionMethod: 'decompressFromUTF16' // string by example unzip, decompressFromUTF16
}, o || {});
if (!jqGridId) { return; }
var ret, tmp, $t = $("#" + jqGridId)[0], data, iN, fT;
if (o.useStorage) {
try {
gridstring = window[o.storageType].getItem("jqGrid" + $t.id);
data = window[o.storageType].getItem("jqGrid" + $t.id + "_data");
} catch (e) {
// can not get data
}
}
if (!gridstring) { return; }
if (o.decompression) {
if (o.decompressionModule) {
try {
ret = window[o.decompressionModule][o.decompressionMethod](gridstring);
if (ret != null) {
gridstring = ret;
data = window[o.decompressionModule][o.decompressionMethod](data);
}
} catch (e) {
// decompression can not be done
}
}
}
ret = jqGridUtils.parse(gridstring);
if (ret && $.type(ret) === 'object') {
if ($t.grid) {
$.jgrid.gridUnload(jqGridId);
}
if ($.isFunction(o.beforeSetGrid)) {
tmp = o.beforeSetGrid(ret);
if (tmp && $.type(tmp) === 'object') {
ret = tmp;
}
}
// some preparings
var retfunc = function (param) { var p; p = param; return p; },
prm = {
"reccount": ret.reccount,
"records": ret.records,
"lastpage": ret.lastpage,
"shrinkToFit": retfunc(ret.shrinkToFit),
"data": retfunc(ret.data),
"datatype": retfunc(ret.datatype),
"grouping": retfunc(ret.grouping)
};
ret.shrinkToFit = false;
ret.data = [];
ret.datatype = 'local';
ret.grouping = false;
//ret.navGrid = false;
if (ret.inlineNav) {
iN = retfunc(ret._iN);
ret._iN = null; delete ret._iN;
}
if (ret.filterToolbar) {
fT = retfunc(ret._fT);
ret._fT = null; delete ret._fT;
}
var grid = $("#" + jqGridId).jqGrid(ret);
grid.append(data);
grid.jqGrid('setGridParam', prm);
if (ret.storeNavOptions && ret.navGrid) {
// set to false so that nav grid can be run
grid[0].p.navGrid = false;
grid.jqGrid('navGrid', ret.pager, ret.navOptions, ret.editOptions, ret.addOptions, ret.delOptions, ret.searchOptions, ret.viewOptions);
if (ret.navButtons && ret.navButtons.length) {
for (var b = 0; b < ret.navButtons.length; b++) {
if ('sepclass' in ret.navButtons[b][1]) {
grid.jqGrid('navSeparatorAdd', ret.navButtons[b][0], ret.navButtons[b][1]);
} else {
grid.jqGrid('navButtonAdd', ret.navButtons[b][0], ret.navButtons[b][1]);
}
}
}
}
// refresh index
grid[0].refreshIndex();
// subgrid
if (ret.subGrid) {
var ms = ret.multiselect === 1 ? 1 : 0,
rn = ret.rownumbers === true ? 1 : 0;
grid.jqGrid('addSubGrid', ms + rn);
}
// treegrid
if (ret.treeGrid) {
var i = 1, len = grid[0].rows.length,
expCol = ret.expColInd,
isLeaf = ret.treeReader.leaf_field,
expanded = ret.treeReader.expanded_field;
// optimization of code needed here
while (i < len) {
$(grid[0].rows[i].cells[expCol])
.find("div.treeclick")
.bind("click", function (e) {
var target = e.target || e.srcElement,
ind2 = $.jgrid.stripPref(ret.idPrefix, $(target, grid[0].rows).closest("tr.jqgrow")[0].id),
pos = grid[0].p._index[ind2];
if (!grid[0].p.data[pos][isLeaf]) {
if (grid[0].p.data[pos][expanded]) {
grid.jqGrid("collapseRow", grid[0].p.data[pos]);
grid.jqGrid("collapseNode", grid[0].p.data[pos]);
} else {
grid.jqGrid("expandRow", grid[0].p.data[pos]);
grid.jqGrid("expandNode", grid[0].p.data[pos]);
}
}
return false;
});
if (ret.ExpandColClick === true) {
$(grid[0].rows[i].cells[expCol])
.find("span.cell-wrapper")
.css("cursor", "pointer")
.bind("click", function (e) {
var target = e.target || e.srcElement,
ind2 = $.jgrid.stripPref(ret.idPrefix, $(target, grid[0].rows).closest("tr.jqgrow")[0].id),
pos = grid[0].p._index[ind2];
if (!grid[0].p.data[pos][isLeaf]) {
if (grid[0].p.data[pos][expanded]) {
grid.jqGrid("collapseRow", grid[0].p.data[pos]);
grid.jqGrid("collapseNode", grid[0].p.data[pos]);
} else {
grid.jqGrid("expandRow", grid[0].p.data[pos]);
grid.jqGrid("expandNode", grid[0].p.data[pos]);
}
}
grid.jqGrid("setSelection", ind2);
return false;
});
}
i++;
}
}
// multiselect
if (ret.multiselect) {
$.each(ret.selarrrow, function () {
$("#jqg_" + jqGridId + "_" + this)[ret.useProp ? 'prop' : 'attr']("checked", "checked");
});
}
// grouping
// pivotgrid
if (ret.inlineNav && iN) {
grid.jqGrid('setGridParam', { inlineNav: false });
grid.jqGrid('inlineNav', ret.pager, iN);
}
if (ret.filterToolbar && fT) {
grid.jqGrid('setGridParam', { filterToolbar: false });
fT.restoreFromFilters = true;
grid.jqGrid('filterToolbar', fT);
}
// finally frozenColums
if (ret.frozenColumns) {
grid.jqGrid('setFrozenColumns');
}
grid[0].updatepager(true, true);
if ($.isFunction(o.afterSetGrid)) {
o.afterSetGrid(grid);
}
if (o.clearAfterLoad) {
window[o.storageType].removeItem("jqGrid" + $t.id);
window[o.storageType].removeItem("jqGrid" + $t.id + "_data");
}
} else {
alert("can not convert to object");
}
},
isGridInStorage: function (jqGridId, options) {
var o = {
storageType: "localStorage"
};
o = $.extend(o, options || {});
var ret, gridstring, data;
try {
gridstring = window[o.storageType].getItem("jqGrid" + jqGridId);
data = window[o.storageType].getItem("jqGrid" + jqGridId + "_data");
ret = gridstring != null && data != null && typeof gridstring === "string" && typeof data === "string";
} catch (e) {
ret = false;
}
return ret;
},
setRegional: function (jqGridId, options) {
var o = {
storageType: "sessionStorage"
};
o = $.extend(o, options || {});
if (!o.regional) {
return;
}
$.jgrid.saveState(jqGridId, o);
o.beforeSetGrid = function (params) {
params.regional = o.regional;
params.force_regional = true;
return params;
};
$.jgrid.loadState(jqGridId, null, o);
// check for formatter actions
var grid = $("#" + jqGridId)[0],
model = $(grid).jqGrid('getGridParam', 'colModel'), i = -1, nav = $.jgrid.getRegional(grid, 'nav');
$.each(model, function (k) {
if (this.formatter && this.formatter === 'actions') {
i = k;
return false;
}
});
if (i !== -1 && nav) {
$("#" + jqGridId + " tbody tr").each(function () {
var td = this.cells[i];
$(td).find(".ui-inline-edit").attr("title", nav.edittitle);
$(td).find(".ui-inline-del").attr("title", nav.deltitle);
$(td).find(".ui-inline-save").attr("title", nav.savetitle);
$(td).find(".ui-inline-cancel").attr("title", nav.canceltitle);
});
}
try {
window[o.storageType].removeItem("jqGrid" + grid.id);
window[o.storageType].removeItem("jqGrid" + grid.id + "_data");
} catch (e) { }
},
jqGridImport: function (jqGridId, o) {
o = $.extend({
imptype: "xml", // xml, json, xmlstring, jsonstring
impstring: "",
impurl: "",
mtype: "GET",
impData: {},
xmlGrid: {
config: "root>grid",
data: "root>rows"
},
jsonGrid: {
config: "grid",
data: "data"
},
ajaxOptions: {}
}, o || {});
var $t = (jqGridId.indexOf("#") === 0 ? "" : "#") + $.jgrid.jqID(jqGridId);
var xmlConvert = function (xml, o) {
var cnfg = $(o.xmlGrid.config, xml)[0];
var xmldata = $(o.xmlGrid.data, xml)[0], jstr, jstr1, key;
if (jqGridUtils.xmlToJSON) {
jstr = jqGridUtils.xmlToJSON(cnfg);
//jstr = $.jgrid.parse(jstr);
for (key in jstr) {
if (jstr.hasOwnProperty(key)) {
jstr1 = jstr[key];
}
}
if (xmldata) {
// save the datatype
var svdatatype = jstr.grid.datatype;
jstr.grid.datatype = 'xmlstring';
jstr.grid.datastr = xml;
$($t).jqGrid(jstr1).jqGrid("setGridParam", { datatype: svdatatype });
} else {
setTimeout(function () { $($t).jqGrid(jstr1); }, 0);
}
} else {
alert("xml2json or parse are not present");
}
};
var jsonConvert = function (jsonstr, o) {
if (jsonstr && typeof jsonstr === 'string') {
var json = jqGridUtils.parse(jsonstr);
var gprm = json[o.jsonGrid.config];
var jdata = json[o.jsonGrid.data];
if (jdata) {
var svdatatype = gprm.datatype;
gprm.datatype = 'jsonstring';
gprm.datastr = jdata;
$($t).jqGrid(gprm).jqGrid("setGridParam", { datatype: svdatatype });
} else {
$($t).jqGrid(gprm);
}
}
};
switch (o.imptype) {
case 'xml':
$.ajax($.extend({
url: o.impurl,
type: o.mtype,
data: o.impData,
dataType: "xml",
complete: function (xml, stat) {
if (stat === 'success') {
xmlConvert(xml.responseXML, o);
$($t).triggerHandler("jqGridImportComplete", [xml, o]);
if ($.isFunction(o.importComplete)) {
o.importComplete(xml);
}
}
xml = null;
}
}, o.ajaxOptions));
break;
case 'xmlstring':
// we need to make just the conversion and use the same code as xml
if (o.impstring && typeof o.impstring === 'string') {
var xmld = $.parseXML(o.impstring);
if (xmld) {
xmlConvert(xmld, o);
$($t).triggerHandler("jqGridImportComplete", [xmld, o]);
if ($.isFunction(o.importComplete)) {
o.importComplete(xmld);
}
}
}
break;
case 'json':
$.ajax($.extend({
url: o.impurl,
type: o.mtype,
data: o.impData,
dataType: "json",
complete: function (json) {
try {
jsonConvert(json.responseText, o);
$($t).triggerHandler("jqGridImportComplete", [json, o]);
if ($.isFunction(o.importComplete)) {
o.importComplete(json);
}
} catch (ee) { }
json = null;
}
}, o.ajaxOptions));
break;
case 'jsonstring':
if (o.impstring && typeof o.impstring === 'string') {
jsonConvert(o.impstring, o);
$($t).triggerHandler("jqGridImportComplete", [o.impstring, o]);
if ($.isFunction(o.importComplete)) {
o.importComplete(o.impstring);
}
}
break;
}
}
});
$.jgrid.extend({
jqGridExport: function (o) {
o = $.extend({
exptype: "xmlstring",
root: "grid",
ident: "\t",
addOptions: {}
}, o || {});
var ret = null;
this.each(function () {
if (!this.grid) { return; }
var key, gprm = $.extend(true, {}, $(this).jqGrid("getGridParam"), o.addOptions);
// we need to check for:
// 1.multiselect, 2.subgrid 3. treegrid and remove the unneded columns from colNames
if (gprm.rownumbers) {
gprm.colNames.splice(0, 1);
gprm.colModel.splice(0, 1);
}
if (gprm.multiselect) {
gprm.colNames.splice(0, 1);
gprm.colModel.splice(0, 1);
}
if (gprm.subGrid) {
gprm.colNames.splice(0, 1);
gprm.colModel.splice(0, 1);
}
gprm.knv = null;
switch (o.exptype) {
case 'xmlstring':
ret = "<" + o.root + ">" + jqGridUtils.jsonToXML(gprm, { xmlDecl: "" }) + "" + o.root + ">";
break;
case 'jsonstring':
ret = jqGridUtils.stringify(gprm);
if (o.root) { ret = "{" + o.root + ":" + ret + "}"; }
break;
}
});
return ret;
},
excelExport: function (o) {
o = $.extend({
exptype: "remote",
url: null,
oper: "oper",
tag: "excel",
beforeExport: null,
exporthidden: false,
exportgrouping: false,
exportOptions: {}
}, o || {});
return this.each(function () {
if (!this.grid) { return; }
var url;
if (o.exptype === "remote") {
var pdata = $.extend({}, this.p.postData), expg;
pdata[o.oper] = o.tag;
if ($.isFunction(o.beforeExport)) {
var result = o.beforeExport.call(this, pdata);
if ($.isPlainObject(result)) {
pdata = result;
}
}
if (o.exporthidden) {
var cm = this.p.colModel, i, len = cm.length, newm = [];
for (i = 0; i < len; i++) {
if (cm[i].hidden === undefined) { cm[i].hidden = false; }
newm.push({ name: cm[i].name, hidden: cm[i].hidden });
}
var newm1 = JSON.stringify(newm);
if (typeof newm1 === 'string') {
pdata['colModel'] = newm1;
}
}
if (o.exportgrouping) {
expg = JSON.stringify(this.p.groupingView)
if (typeof expg === 'string') {
pdata['groupingView'] = expg;
}
}
var params = jQuery.param(pdata);
if (o.url.indexOf("?") !== -1) { url = o.url + "&" + params; }
else { url = o.url + "?" + params; }
window.location = url;
}
});
}
});
//module begin
$.jgrid.inlineEdit = $.jgrid.inlineEdit || {};
$.jgrid.extend({
//Editing
editRow: function (rowid, keys, oneditfunc, successfunc, url, extraparam, aftersavefunc, errorfunc, afterrestorefunc) {
// Compatible mode old versions
var o = {}, args = $.makeArray(arguments).slice(1);
if ($.type(args[0]) === "object") {
o = args[0];
} else {
if (keys !== undefined) { o.keys = keys; }
if ($.isFunction(oneditfunc)) { o.oneditfunc = oneditfunc; }
if ($.isFunction(successfunc)) { o.successfunc = successfunc; }
if (url !== undefined) { o.url = url; }
if (extraparam !== undefined) { o.extraparam = extraparam; }
if ($.isFunction(aftersavefunc)) { o.aftersavefunc = aftersavefunc; }
if ($.isFunction(errorfunc)) { o.errorfunc = errorfunc; }
if ($.isFunction(afterrestorefunc)) { o.afterrestorefunc = afterrestorefunc; }
// last two not as param, but as object (sorry)
//if (restoreAfterError !== undefined) { o.restoreAfterError = restoreAfterError; }
//if (mtype !== undefined) { o.mtype = mtype || "POST"; }
}
o = $.extend(true, {
keys: false,
keyevent: "keydown",
oneditfunc: null,
successfunc: null,
url: null,
extraparam: {},
aftersavefunc: null,
errorfunc: null,
afterrestorefunc: null,
restoreAfterError: true,
mtype: "POST",
focusField: true
}, $.jgrid.inlineEdit, o);
// End compatible
return this.each(function () {
var $t = this, nm, tmp, editable, cnt = 0, focus = null, svr = {}, ind, cm, bfer,
inpclass = $(this).jqGrid('getStyleUI', $t.p.styleUI + ".inlinedit", 'inputClass', true);
if (!$t.grid) { return; }
ind = $($t).jqGrid("getInd", rowid, true);
if (ind === false) { return; }
bfer = $.isFunction(o.beforeEditRow) ? o.beforeEditRow.call($t, o, rowid) : undefined;
if (bfer === undefined) {
bfer = true;
}
if (!bfer) { return; }
editable = $(ind).attr("editable") || "0";
if (editable === "0" && !$(ind).hasClass("not-editable-row")) {
cm = $t.p.colModel;
$('td[role="gridcell"]', ind).each(function (i) {
nm = cm[i].name;
var treeg = $t.p.treeGrid === true && nm === $t.p.ExpandColumn;
if (treeg) { tmp = $("span:first", this).html(); }
else {
try {
tmp = $.unformat.call($t, this, { rowId: rowid, colModel: cm[i] }, i);
} catch (_) {
tmp = (cm[i].edittype && cm[i].edittype === 'textarea') ? $(this).text() : $(this).html();
}
}
if (nm !== 'cb' && nm !== 'subgrid' && nm !== 'rn') {
if ($t.p.autoencode) { tmp = $.jgrid.htmlDecode(tmp); }
svr[nm] = tmp;
if (cm[i].editable === true) {
if (focus === null) { focus = i; }
if (treeg) { $("span:first", this).html(""); }
else { $(this).html(""); }
var opt = $.extend({}, cm[i].editoptions || {}, { id: rowid + "_" + nm, name: nm, rowId: rowid, oper: 'edit' });
if (!cm[i].edittype) { cm[i].edittype = "text"; }
if (tmp === " " || tmp === " " || (tmp.length === 1 && tmp.charCodeAt(0) === 160)) { tmp = ''; }
var elc = $.jgrid.createEl.call($t, cm[i].edittype, opt, tmp, true, $.extend({}, $.jgrid.ajaxOptions, $t.p.ajaxSelectOptions || {}));
$(elc).addClass("editable inline-edit-cell");
if ($.inArray(cm[i].edittype, ['text', 'textarea', 'password', 'select']) > -1) {
$(elc).addClass(inpclass);
}
if (treeg) { $("span:first", this).append(elc); }
else { $(this).append(elc); }
$.jgrid.bindEv.call($t, elc, opt);
//Again IE
if (cm[i].edittype === "select" && cm[i].editoptions !== undefined && cm[i].editoptions.multiple === true && cm[i].editoptions.dataUrl === undefined && $.jgrid.msie) {
$(elc).width($(elc).width());
}
cnt++;
}
}
});
if (cnt > 0) {
svr.id = rowid; $t.p.savedRow.push(svr);
$(ind).attr("editable", "1");
if (o.focusField) {
if (typeof o.focusField === 'number' && parseInt(o.focusField, 10) <= cm.length) {
focus = o.focusField;
}
setTimeout(function () {
var fe = $("td:eq(" + focus + ") :input:visible", ind).not(":disabled");
if (fe.length > 0) {
fe.focus();
}
}, 0);
}
if (o.keys === true) {
$(ind).bind(o.keyevent, function (e) {
if (e.keyCode === 27) {
$($t).jqGrid("restoreRow", rowid, o.afterrestorefunc);
if ($t.p.inlineNav) {
try {
$($t).jqGrid('showAddEditButtons');
} catch (eer1) { }
}
return false;
}
if (e.keyCode === 13) {
var ta = e.target;
if (ta.tagName === 'TEXTAREA') { return true; }
if ($($t).jqGrid("saveRow", rowid, o)) {
if ($t.p.inlineNav) {
try {
$($t).jqGrid('showAddEditButtons');
} catch (eer2) { }
}
}
return false;
}
});
}
$($t).triggerHandler("jqGridInlineEditRow", [rowid, o]);
if ($.isFunction(o.oneditfunc)) { o.oneditfunc.call($t, rowid); }
}
}
});
},
saveRow: function (rowid, successfunc, url, extraparam, aftersavefunc, errorfunc, afterrestorefunc) {
// Compatible mode old versions
var args = $.makeArray(arguments).slice(1), o = {}, $t = this[0];
if ($.type(args[0]) === "object") {
o = args[0];
} else {
if ($.isFunction(successfunc)) { o.successfunc = successfunc; }
if (url !== undefined) { o.url = url; }
if (extraparam !== undefined) { o.extraparam = extraparam; }
if ($.isFunction(aftersavefunc)) { o.aftersavefunc = aftersavefunc; }
if ($.isFunction(errorfunc)) { o.errorfunc = errorfunc; }
if ($.isFunction(afterrestorefunc)) { o.afterrestorefunc = afterrestorefunc; }
}
o = $.extend(true, {
successfunc: null,
url: null,
extraparam: {},
aftersavefunc: null,
errorfunc: null,
afterrestorefunc: null,
restoreAfterError: true,
mtype: "POST",
saveui: "enable",
savetext: $.jgrid.getRegional($t, 'defaults.savetext')
}, $.jgrid.inlineEdit, o);
// End compatible
var success = false, nm, tmp = {}, tmp2 = {}, tmp3 = {}, editable, fr, cv, ind, nullIfEmpty = false,
error = $.trim($($t).jqGrid('getStyleUI', $t.p.styleUI + '.common', 'error', true));
if (!$t.grid) { return success; }
ind = $($t).jqGrid("getInd", rowid, true);
if (ind === false) { return success; }
var errors = $.jgrid.getRegional($t, 'errors'),
edit = $.jgrid.getRegional($t, 'edit'),
bfsr = $.isFunction(o.beforeSaveRow) ? o.beforeSaveRow.call($t, o, rowid) : undefined;
if (bfsr === undefined) {
bfsr = true;
}
if (!bfsr) { return; }
editable = $(ind).attr("editable");
o.url = o.url || $t.p.editurl;
if (editable === "1") {
var cm;
$('td[role="gridcell"]', ind).each(function (i) {
cm = $t.p.colModel[i];
nm = cm.name;
if (nm !== 'cb' && nm !== 'subgrid' && cm.editable === true && nm !== 'rn' && !$(this).hasClass('not-editable-cell')) {
switch (cm.edittype) {
case "checkbox":
var cbv = ["Yes", "No"];
if (cm.editoptions) {
cbv = cm.editoptions.value.split(":");
}
tmp[nm] = $("input", this).is(":checked") ? cbv[0] : cbv[1];
break;
case 'text':
case 'password':
case 'textarea':
case "button":
tmp[nm] = $("input, textarea", this).val();
break;
case 'select':
if (!cm.editoptions.multiple) {
tmp[nm] = $("select option:selected", this).val();
tmp2[nm] = $("select option:selected", this).text();
} else {
var sel = $("select", this), selectedText = [];
tmp[nm] = $(sel).val();
if (tmp[nm]) { tmp[nm] = tmp[nm].join(","); } else { tmp[nm] = ""; }
$("select option:selected", this).each(
function (i, selected) {
selectedText[i] = $(selected).text();
}
);
tmp2[nm] = selectedText.join(",");
}
if (cm.formatter && cm.formatter === 'select') { tmp2 = {}; }
break;
case 'custom':
try {
if (cm.editoptions && $.isFunction(cm.editoptions.custom_value)) {
tmp[nm] = cm.editoptions.custom_value.call($t, $(".customelement", this), 'get');
if (tmp[nm] === undefined) { throw "e2"; }
} else { throw "e1"; }
} catch (e) {
if (e === "e1") { $.jgrid.info_dialog(errors.errcap, "function 'custom_value' " + edit.msg.nodefined, edit.bClose, { styleUI: $t.p.styleUI }); }
else { $.jgrid.info_dialog(errors.errcap, e.message, edit.bClose, { styleUI: $t.p.styleUI }); }
}
break;
}
cv = $.jgrid.checkValues.call($t, tmp[nm], i);
if (cv[0] === false) {
return false;
}
if ($t.p.autoencode) { tmp[nm] = $.jgrid.htmlEncode(tmp[nm]); }
if (o.url !== 'clientArray' && cm.editoptions && cm.editoptions.NullIfEmpty === true) {
if (tmp[nm] === "") {
tmp3[nm] = 'null';
nullIfEmpty = true;
}
}
}
});
if (cv[0] === false) {
try {
var tr = $($t).jqGrid('getGridRowById', rowid), positions = $.jgrid.findPos(tr);
$.jgrid.info_dialog(errors.errcap, cv[1], edit.bClose, { left: positions[0], top: positions[1] + $(tr).outerHeight(), styleUI: $t.p.styleUI });
} catch (e) {
alert(cv[1]);
}
return success;
}
var idname, opers = $t.p.prmNames, oldRowId = rowid;
if ($t.p.keyName === false) {
idname = opers.id;
} else {
idname = $t.p.keyName;
}
if (tmp) {
tmp[opers.oper] = opers.editoper;
if (tmp[idname] === undefined || tmp[idname] === "") {
tmp[idname] = rowid;
} else if (ind.id !== $t.p.idPrefix + tmp[idname]) {
// rename rowid
var oldid = $.jgrid.stripPref($t.p.idPrefix, rowid);
if ($t.p._index[oldid] !== undefined) {
$t.p._index[tmp[idname]] = $t.p._index[oldid];
delete $t.p._index[oldid];
}
rowid = $t.p.idPrefix + tmp[idname];
$(ind).attr("id", rowid);
if ($t.p.selrow === oldRowId) {
$t.p.selrow = rowid;
}
if ($.isArray($t.p.selarrrow)) {
var i = $.inArray(oldRowId, $t.p.selarrrow);
if (i >= 0) {
$t.p.selarrrow[i] = rowid;
}
}
if ($t.p.multiselect) {
var newCboxId = "jqg_" + $t.p.id + "_" + rowid;
$("input.cbox", ind)
.attr("id", newCboxId)
.attr("name", newCboxId);
}
// TODO: to test the case of frozen columns
}
if ($t.p.inlineData === undefined) { $t.p.inlineData = {}; }
tmp = $.extend({}, tmp, $t.p.inlineData, o.extraparam);
}
if (o.url === 'clientArray') {
tmp = $.extend({}, tmp, tmp2);
if ($t.p.autoencode) {
$.each(tmp, function (n, v) {
tmp[n] = $.jgrid.htmlDecode(v);
});
}
var k, resp = $($t).jqGrid("setRowData", rowid, tmp);
$(ind).attr("editable", "0");
for (k = 0; k < $t.p.savedRow.length; k++) {
if (String($t.p.savedRow[k].id) === String(oldRowId)) { fr = k; break; }
}
if (fr >= 0) { $t.p.savedRow.splice(fr, 1); }
$($t).triggerHandler("jqGridInlineAfterSaveRow", [rowid, resp, tmp, o]);
if ($.isFunction(o.aftersavefunc)) { o.aftersavefunc.call($t, rowid, resp, tmp, o); }
success = true;
$(ind).removeClass("jqgrid-new-row").unbind("keydown");
} else {
$($t).jqGrid("progressBar", { method: "show", loadtype: o.saveui, htmlcontent: o.savetext });
tmp3 = $.extend({}, tmp, tmp3);
tmp3[idname] = $.jgrid.stripPref($t.p.idPrefix, tmp3[idname]);
$.ajax($.extend({
url: o.url,
data: $.isFunction($t.p.serializeRowData) ? $t.p.serializeRowData.call($t, tmp3) : tmp3,
type: o.mtype,
async: false, //?!?
complete: function (res, stat) {
$($t).jqGrid("progressBar", { method: "hide", loadtype: o.saveui, htmlcontent: o.savetext });
if (stat === "success") {
var ret = true, sucret, k;
sucret = $($t).triggerHandler("jqGridInlineSuccessSaveRow", [res, rowid, o]);
if (!$.isArray(sucret)) { sucret = [true, tmp3]; }
if (sucret[0] && $.isFunction(o.successfunc)) { sucret = o.successfunc.call($t, res); }
if ($.isArray(sucret)) {
// expect array - status, data, rowid
ret = sucret[0];
tmp = sucret[1] || tmp;
} else {
ret = sucret;
}
if (ret === true) {
if ($t.p.autoencode) {
$.each(tmp, function (n, v) {
tmp[n] = $.jgrid.htmlDecode(v);
});
}
if (nullIfEmpty) {
$.each(tmp, function (n) {
if (tmp[n] === 'null') {
tmp[n] = '';
}
});
}
tmp = $.extend({}, tmp, tmp2);
$($t).jqGrid("setRowData", rowid, tmp);
$(ind).attr("editable", "0");
for (k = 0; k < $t.p.savedRow.length; k++) {
if (String($t.p.savedRow[k].id) === String(rowid)) { fr = k; break; }
}
if (fr >= 0) { $t.p.savedRow.splice(fr, 1); }
$($t).triggerHandler("jqGridInlineAfterSaveRow", [rowid, res, tmp, o]);
if ($.isFunction(o.aftersavefunc)) { o.aftersavefunc.call($t, rowid, res, tmp, o); }
success = true;
$(ind).removeClass("jqgrid-new-row").unbind("keydown");
} else {
$($t).triggerHandler("jqGridInlineErrorSaveRow", [rowid, res, stat, null, o]);
if ($.isFunction(o.errorfunc)) {
o.errorfunc.call($t, rowid, res, stat, null);
}
if (o.restoreAfterError === true) {
$($t).jqGrid("restoreRow", rowid, o.afterrestorefunc);
}
}
}
},
error: function (res, stat, err) {
$("#lui_" + $.jgrid.jqID($t.p.id)).hide();
$($t).triggerHandler("jqGridInlineErrorSaveRow", [rowid, res, stat, err, o]);
if ($.isFunction(o.errorfunc)) {
o.errorfunc.call($t, rowid, res, stat, err);
} else {
var rT = res.responseText || res.statusText;
try {
$.jgrid.info_dialog(errors.errcap, '
' + rT + '
', edit.bClose, { buttonalign: 'right', styleUI: $t.p.styleUI });
} catch (e) {
alert(rT);
}
}
if (o.restoreAfterError === true) {
$($t).jqGrid("restoreRow", rowid, o.afterrestorefunc);
}
}
}, $.jgrid.ajaxOptions, $t.p.ajaxRowOptions || {}));
}
}
return success;
},
restoreRow: function (rowid, afterrestorefunc) {
// Compatible mode old versions
var args = $.makeArray(arguments).slice(1), o = {};
if ($.type(args[0]) === "object") {
o = args[0];
} else {
if ($.isFunction(afterrestorefunc)) { o.afterrestorefunc = afterrestorefunc; }
}
o = $.extend(true, {}, $.jgrid.inlineEdit, o);
// End compatible
return this.each(function () {
var $t = this, fr = -1, ind, ares = {}, k;
if (!$t.grid) { return; }
ind = $($t).jqGrid("getInd", rowid, true);
if (ind === false) { return; }
var bfcr = $.isFunction(o.beforeCancelRow) ? o.beforeCancelRow.call($t, o, rowid) : undefined;
if (bfcr === undefined) {
bfcr = true;
}
if (!bfcr) { return; }
for (k = 0; k < $t.p.savedRow.length; k++) {
if (String($t.p.savedRow[k].id) === String(rowid)) { fr = k; break; }
}
if (fr >= 0) {
if ($.isFunction($.fn.datepicker)) {
try {
$("input.hasDatepicker", "#" + $.jgrid.jqID(ind.id)).datepicker('hide');
} catch (e) { }
}
$.each($t.p.colModel, function () {
if (this.editable === true && $t.p.savedRow[fr].hasOwnProperty(this.name)) {
ares[this.name] = $t.p.savedRow[fr][this.name];
}
});
$($t).jqGrid("setRowData", rowid, ares);
$(ind).attr("editable", "0").unbind("keydown");
$t.p.savedRow.splice(fr, 1);
if ($("#" + $.jgrid.jqID(rowid), "#" + $.jgrid.jqID($t.p.id)).hasClass("jqgrid-new-row")) {
setTimeout(function () {
$($t).jqGrid("delRowData", rowid);
$($t).jqGrid('showAddEditButtons');
}, 0);
}
}
$($t).triggerHandler("jqGridInlineAfterRestoreRow", [rowid]);
if ($.isFunction(o.afterrestorefunc)) {
o.afterrestorefunc.call($t, rowid);
}
});
},
addRow: function (p) {
p = $.extend(true, {
rowID: null,
initdata: {},
position: "first",
useDefValues: true,
useFormatter: false,
addRowParams: { extraparam: {} }
}, p || {});
return this.each(function () {
if (!this.grid) { return; }
var $t = this;
var bfar = $.isFunction(p.beforeAddRow) ? p.beforeAddRow.call($t, p.addRowParams) : undefined;
if (bfar === undefined) {
bfar = true;
}
if (!bfar) { return; }
p.rowID = $.isFunction(p.rowID) ? p.rowID.call($t, p) : ((p.rowID != null) ? p.rowID : $.jgrid.randId());
if (p.useDefValues === true) {
$($t.p.colModel).each(function () {
if (this.editoptions && this.editoptions.defaultValue) {
var opt = this.editoptions.defaultValue,
tmp = $.isFunction(opt) ? opt.call($t) : opt;
p.initdata[this.name] = tmp;
}
});
}
$($t).jqGrid('addRowData', p.rowID, p.initdata, p.position);
p.rowID = $t.p.idPrefix + p.rowID;
$("#" + $.jgrid.jqID(p.rowID), "#" + $.jgrid.jqID($t.p.id)).addClass("jqgrid-new-row");
if (p.useFormatter) {
$("#" + $.jgrid.jqID(p.rowID) + " .ui-inline-edit", "#" + $.jgrid.jqID($t.p.id)).click();
} else {
var opers = $t.p.prmNames,
oper = opers.oper;
p.addRowParams.extraparam[oper] = opers.addoper;
$($t).jqGrid('editRow', p.rowID, p.addRowParams);
$($t).jqGrid('setSelection', p.rowID);
}
});
},
inlineNav: function (elem, o) {
var $t = this[0],
regional = $.jgrid.getRegional($t, 'nav'),
icons = $.jgrid.styleUI[$t.p.styleUI].inlinedit;
o = $.extend(true, {
edit: true,
editicon: icons.icon_edit_nav,
add: true,
addicon: icons.icon_add_nav,
save: true,
saveicon: icons.icon_save_nav,
cancel: true,
cancelicon: icons.icon_cancel_nav,
addParams: { addRowParams: { extraparam: {} } },
editParams: {},
restoreAfterSelect: true,
saveAfterSelect: false
}, regional, o || {});
return this.each(function () {
if (!this.grid || this.p.inlineNav) { return; }
var gID = $.jgrid.jqID($t.p.id),
disabled = $.trim($($t).jqGrid('getStyleUI', $t.p.styleUI + '.common', 'disabled', true));
// check to see if navgrid is started, if not call it with all false parameters.
if (!$t.p.navGrid) {
$($t).jqGrid('navGrid', elem, { refresh: false, edit: false, add: false, del: false, search: false, view: false });
}
if (!$($t).data('inlineNav')) {
$($t).data('inlineNav', o);
}
if ($t.p.force_regional) {
o = $.extend(o, regional);
}
$t.p.inlineNav = true;
// detect the formatactions column
if (o.addParams.useFormatter === true) {
var cm = $t.p.colModel, i;
for (i = 0; i < cm.length; i++) {
if (cm[i].formatter && cm[i].formatter === "actions") {
if (cm[i].formatoptions) {
var defaults = {
keys: false,
onEdit: null,
onSuccess: null,
afterSave: null,
onError: null,
afterRestore: null,
extraparam: {},
url: null
},
ap = $.extend(defaults, cm[i].formatoptions);
o.addParams.addRowParams = {
"keys": ap.keys,
"oneditfunc": ap.onEdit,
"successfunc": ap.onSuccess,
"url": ap.url,
"extraparam": ap.extraparam,
"aftersavefunc": ap.afterSave,
"errorfunc": ap.onError,
"afterrestorefunc": ap.afterRestore
};
}
break;
}
}
}
if (o.add) {
$($t).jqGrid('navButtonAdd', elem, {
caption: o.addtext,
title: o.addtitle,
buttonicon: o.addicon,
id: $t.p.id + "_iladd",
internal: true,
onClickButton: function () {
$($t).jqGrid('addRow', o.addParams);
if (!o.addParams.useFormatter) {
$("#" + gID + "_ilsave").removeClass(disabled);
$("#" + gID + "_ilcancel").removeClass(disabled);
$("#" + gID + "_iladd").addClass(disabled);
$("#" + gID + "_iledit").addClass(disabled);
}
}
});
}
if (o.edit) {
$($t).jqGrid('navButtonAdd', elem, {
caption: o.edittext,
title: o.edittitle,
buttonicon: o.editicon,
id: $t.p.id + "_iledit",
internal: true,
onClickButton: function () {
var sr = $($t).jqGrid('getGridParam', 'selrow');
if (sr) {
$($t).jqGrid('editRow', sr, o.editParams);
$("#" + gID + "_ilsave").removeClass(disabled);
$("#" + gID + "_ilcancel").removeClass(disabled);
$("#" + gID + "_iladd").addClass(disabled);
$("#" + gID + "_iledit").addClass(disabled);
} else {
$.jgrid.viewModal("#alertmod_" + gID, { gbox: "#gbox_" + gID, jqm: true }); $("#jqg_alrt").focus();
}
}
});
}
if (o.save) {
$($t).jqGrid('navButtonAdd', elem, {
caption: o.savetext || '',
title: o.savetitle || 'Save row',
buttonicon: o.saveicon,
id: $t.p.id + "_ilsave",
internal: true,
onClickButton: function () {
var sr = $t.p.savedRow[0].id;
if (sr) {
var opers = $t.p.prmNames,
oper = opers.oper, tmpParams = o.editParams;
if ($("#" + $.jgrid.jqID(sr), "#" + gID).hasClass("jqgrid-new-row")) {
o.addParams.addRowParams.extraparam[oper] = opers.addoper;
tmpParams = o.addParams.addRowParams;
} else {
if (!o.editParams.extraparam) {
o.editParams.extraparam = {};
}
o.editParams.extraparam[oper] = opers.editoper;
}
if ($($t).jqGrid('saveRow', sr, tmpParams)) {
$($t).jqGrid('showAddEditButtons');
}
} else {
$.jgrid.viewModal("#alertmod_" + gID, { gbox: "#gbox_" + gID, jqm: true }); $("#jqg_alrt").focus();
}
}
});
$("#" + gID + "_ilsave").addClass(disabled);
}
if (o.cancel) {
$($t).jqGrid('navButtonAdd', elem, {
caption: o.canceltext || '',
title: o.canceltitle || 'Cancel row editing',
buttonicon: o.cancelicon,
id: $t.p.id + "_ilcancel",
internal: true,
onClickButton: function () {
var sr = $t.p.savedRow[0].id, cancelPrm = o.editParams;
if (sr) {
if ($("#" + $.jgrid.jqID(sr), "#" + gID).hasClass("jqgrid-new-row")) {
cancelPrm = o.addParams.addRowParams;
}
$($t).jqGrid('restoreRow', sr, cancelPrm);
$($t).jqGrid('showAddEditButtons');
} else {
$.jgrid.viewModal("#alertmod", { gbox: "#gbox_" + gID, jqm: true }); $("#jqg_alrt").focus();
}
}
});
$("#" + gID + "_ilcancel").addClass(disabled);
}
if (o.restoreAfterSelect === true || o.saveAfterSelect === true) {
$($t).bind("jqGridBeforeSelectRow.inlineNav", function (event, id) {
if ($t.p.savedRow.length > 0 && $t.p.inlineNav === true && (id !== $t.p.selrow && $t.p.selrow !== null)) {
if ($t.p.selrow === o.addParams.rowID) {
$($t).jqGrid('delRowData', $t.p.selrow);
} else {
if (o.restoreAfterSelect === true) {
$($t).jqGrid('restoreRow', $t.p.selrow, o.editParams);
} else {
$($t).jqGrid('saveRow', $t.p.selrow, o.editParams);
}
}
$($t).jqGrid('showAddEditButtons');
}
});
}
});
},
showAddEditButtons: function () {
return this.each(function () {
if (!this.grid) { return; }
var gID = $.jgrid.jqID(this.p.id),
disabled = $.trim($(this).jqGrid('getStyleUI', this.p.styleUI + '.common', 'disabled', true));
$("#" + gID + "_ilsave").addClass(disabled);
$("#" + gID + "_ilcancel").addClass(disabled);
$("#" + gID + "_iladd").removeClass(disabled);
$("#" + gID + "_iledit").removeClass(disabled);
});
}
//end inline edit
});
//module begin
if ($.jgrid.msie && $.jgrid.msiever() === 8) {
$.expr[":"].hidden = function (elem) {
return elem.offsetWidth === 0 || elem.offsetHeight === 0 ||
elem.style.display === "none";
};
}
// requiere load multiselect before grid
$.jgrid._multiselect = false;
if ($.ui) {
if ($.ui.multiselect) {
if ($.ui.multiselect.prototype._setSelected) {
var setSelected = $.ui.multiselect.prototype._setSelected;
$.ui.multiselect.prototype._setSelected = function (item, selected) {
var ret = setSelected.call(this, item, selected);
if (selected && this.selectedList) {
var elt = this.element;
this.selectedList.find('li').each(function () {
if ($(this).data('optionLink')) {
$(this).data('optionLink').remove().appendTo(elt);
}
});
}
return ret;
};
}
if ($.ui.multiselect.prototype.destroy) {
$.ui.multiselect.prototype.destroy = function () {
this.element.show();
this.container.remove();
if ($.Widget === undefined) {
$.widget.prototype.destroy.apply(this, arguments);
} else {
$.Widget.prototype.destroy.apply(this, arguments);
}
};
}
$.jgrid._multiselect = true;
}
}
$.jgrid.extend({
sortableColumns: function (tblrow) {
return this.each(function () {
var ts = this, tid = $.jgrid.jqID(ts.p.id);
function start() { ts.p.disableClick = true; }
var sortable_opts = {
"tolerance": "pointer",
"axis": "x",
"scrollSensitivity": "1",
"items": '>th:not(:has(#jqgh_' + tid + '_cb' + ',#jqgh_' + tid + '_rn' + ',#jqgh_' + tid + '_subgrid),:hidden)',
"placeholder": {
element: function (item) {
var el = $(document.createElement(item[0].nodeName))
.addClass(item[0].className + " ui-sortable-placeholder ui-state-highlight")
.removeClass("ui-sortable-helper")[0];
return el;
},
update: function (self, p) {
p.height(self.currentItem.innerHeight() - parseInt(self.currentItem.css('paddingTop') || 0, 10) - parseInt(self.currentItem.css('paddingBottom') || 0, 10));
p.width(self.currentItem.innerWidth() - parseInt(self.currentItem.css('paddingLeft') || 0, 10) - parseInt(self.currentItem.css('paddingRight') || 0, 10));
}
},
"update": function (event, ui) {
var p = $(ui.item).parent(),
th = $(">th", p),
colModel = ts.p.colModel,
cmMap = {}, tid = ts.p.id + "_";
$.each(colModel, function (i) { cmMap[this.name] = i; });
var permutation = [];
th.each(function () {
var id = $(">div", this).get(0).id.replace(/^jqgh_/, "").replace(tid, "");
if (cmMap.hasOwnProperty(id)) {
permutation.push(cmMap[id]);
}
});
$(ts).jqGrid("remapColumns", permutation, true, true);
if ($.isFunction(ts.p.sortable.update)) {
ts.p.sortable.update(permutation);
}
setTimeout(function () { ts.p.disableClick = false; }, 50);
}
};
if (ts.p.sortable.options) {
$.extend(sortable_opts, ts.p.sortable.options);
} else if ($.isFunction(ts.p.sortable)) {
ts.p.sortable = { "update": ts.p.sortable };
}
if (sortable_opts.start) {
var s = sortable_opts.start;
sortable_opts.start = function (e, ui) {
start();
s.call(this, e, ui);
};
} else {
sortable_opts.start = start;
}
if (ts.p.sortable.exclude) {
sortable_opts.items += ":not(" + ts.p.sortable.exclude + ")";
}
var $e = tblrow.sortable(sortable_opts), dataObj = $e.data("sortable") || $e.data("uiSortable");
if (dataObj != null) {
dataObj.data("sortable").floating = true;
}
});
},
columnChooser: function (opts) {
var self = this, selector, select, colMap = {}, fixedCols = [], dopts, mopts, $dialogContent, multiselectData, listHeight,
colModel = self.jqGrid("getGridParam", "colModel"),
colNames = self.jqGrid("getGridParam", "colNames"),
getMultiselectWidgetData = function ($elem) {
return ($.ui.multiselect.prototype && $elem.data($.ui.multiselect.prototype.widgetFullName || $.ui.multiselect.prototype.widgetName)) ||
$elem.data("ui-multiselect") || $elem.data("multiselect");
},
regional = $.jgrid.getRegional(this[0], 'col');
if ($("#colchooser_" + $.jgrid.jqID(self[0].p.id)).length) { return; }
selector = $('
');
select = $('select', selector);
function insert(perm, i, v) {
var a, b;
if (i >= 0) {
a = perm.slice();
b = a.splice(i, Math.max(perm.length - i, i));
if (i > perm.length) { i = perm.length; }
a[i] = v;
return a.concat(b);
}
return perm;
}
function call(fn, obj) {
if (!fn) { return; }
if (typeof fn === 'string') {
if ($.fn[fn]) {
$.fn[fn].apply(obj, $.makeArray(arguments).slice(2));
}
} else if ($.isFunction(fn)) {
fn.apply(obj, $.makeArray(arguments).slice(2));
}
}
opts = $.extend({
width: 400,
height: 240,
classname: null,
done: function (perm) { if (perm) { self.jqGrid("remapColumns", perm, true); } },
/* msel is either the name of a ui widget class that
extends a multiselect, or a function that supports
creating a multiselect object (with no argument,
or when passed an object), and destroying it (when
passed the string "destroy"). */
msel: "multiselect",
/* "msel_opts" : {}, */
/* dlog is either the name of a ui widget class that
behaves in a dialog-like way, or a function, that
supports creating a dialog (when passed dlog_opts)
or destroying a dialog (when passed the string
"destroy")
*/
dlog: "dialog",
dialog_opts: {
minWidth: 470,
dialogClass: "ui-jqdialog"
},
/* dlog_opts is either an option object to be passed
to "dlog", or (more likely) a function that creates
the options object.
The default produces a suitable options object for
ui.dialog */
dlog_opts: function (options) {
var buttons = {};
buttons[options.bSubmit] = function () {
options.apply_perm();
options.cleanup(false);
};
buttons[options.bCancel] = function () {
options.cleanup(true);
};
return $.extend(true, {
buttons: buttons,
close: function () {
options.cleanup(true);
},
modal: options.modal || false,
resizable: options.resizable || true,
width: options.width + 70,
resize: function () {
var widgetData = getMultiselectWidgetData(select),
$thisDialogContent = widgetData.container.closest(".ui-dialog-content");
if ($thisDialogContent.length > 0 && typeof $thisDialogContent[0].style === "object") {
$thisDialogContent[0].style.width = "";
} else {
$thisDialogContent.css("width", ""); // or just remove width style
}
widgetData.selectedList.height(Math.max(widgetData.selectedContainer.height() - widgetData.selectedActions.outerHeight() - 1, 1));
widgetData.availableList.height(Math.max(widgetData.availableContainer.height() - widgetData.availableActions.outerHeight() - 1, 1));
}
}, options.dialog_opts || {});
},
/* Function to get the permutation array, and pass it to the
"done" function */
apply_perm: function () {
var perm = [];
$('option', select).each(function () {
if ($(this).is(":selected")) {
self.jqGrid("showCol", colModel[this.value].name);
} else {
self.jqGrid("hideCol", colModel[this.value].name);
}
});
//fixedCols.slice(0);
$('option[selected]', select).each(function () { perm.push(parseInt(this.value, 10)); });
$.each(perm, function () { delete colMap[colModel[parseInt(this, 10)].name]; });
$.each(colMap, function () {
var ti = parseInt(this, 10);
perm = insert(perm, ti, ti);
});
if (opts.done) {
opts.done.call(self, perm);
}
self.jqGrid("setGridWidth", self[0].p.width, self[0].p.shrinkToFit);
},
/* Function to cleanup the dialog, and select. Also calls the
done function with no permutation (to indicate that the
columnChooser was aborted */
cleanup: function (calldone) {
call(opts.dlog, selector, 'destroy');
call(opts.msel, select, 'destroy');
selector.remove();
if (calldone && opts.done) {
opts.done.call(self);
}
},
msel_opts: {}
}, regional, opts || {});
if ($.ui) {
if ($.ui.multiselect && $.ui.multiselect.defaults) {
if (!$.jgrid._multiselect) {
// should be in language file
alert("Multiselect plugin loaded after jqGrid. Please load the plugin before the jqGrid!");
return;
}
// ??? the next line uses $.ui.multiselect.defaults which will be typically undefined
opts.msel_opts = $.extend($.ui.multiselect.defaults, opts.msel_opts);
}
}
if (opts.caption) {
selector.attr("title", opts.caption);
}
if (opts.classname) {
selector.addClass(opts.classname);
select.addClass(opts.classname);
}
if (opts.width) {
$(">div", selector).css({ width: opts.width, margin: "0 auto" });
select.css("width", opts.width);
}
if (opts.height) {
$(">div", selector).css("height", opts.height);
select.css("height", opts.height - 10);
}
select.empty();
$.each(colModel, function (i) {
colMap[this.name] = i;
if (this.hidedlg) {
if (!this.hidden) {
fixedCols.push(i);
}
return;
}
select.append("");
});
dopts = $.isFunction(opts.dlog_opts) ? opts.dlog_opts.call(self, opts) : opts.dlog_opts;
call(opts.dlog, selector, dopts);
mopts = $.isFunction(opts.msel_opts) ? opts.msel_opts.call(self, opts) : opts.msel_opts;
call(opts.msel, select, mopts);
// fix height of elements of the multiselect widget
$dialogContent = $("#colchooser_" + $.jgrid.jqID(self[0].p.id));
$dialogContent.css({ margin: "auto" });
$dialogContent.find(">div").css({ width: "100%", height: "100%", margin: "auto" });
multiselectData = getMultiselectWidgetData(select);
multiselectData.container.css({ width: "100%", height: "100%", margin: "auto" });
multiselectData.selectedContainer.css({ width: multiselectData.options.dividerLocation * 100 + "%", height: "100%", margin: "auto", boxSizing: "border-box" });
multiselectData.availableContainer.css({ width: (100 - multiselectData.options.dividerLocation * 100) + "%", height: "100%", margin: "auto", boxSizing: "border-box" });
// set height for both selectedList and availableList
multiselectData.selectedList.css("height", "auto");
multiselectData.availableList.css("height", "auto");
listHeight = Math.max(multiselectData.selectedList.height(), multiselectData.availableList.height());
listHeight = Math.min(listHeight, $(window).height());
multiselectData.selectedList.css("height", listHeight);
multiselectData.availableList.css("height", listHeight);
},
sortableRows: function (opts) {
// Can accept all sortable options and events
return this.each(function () {
var $t = this;
if (!$t.grid) { return; }
// Currently we disable a treeGrid sortable
if ($t.p.treeGrid) { return; }
if ($.fn.sortable) {
opts = $.extend({
"cursor": "move",
"axis": "y",
"items": " > .jqgrow"
},
opts || {});
if (opts.start && $.isFunction(opts.start)) {
opts._start_ = opts.start;
delete opts.start;
} else { opts._start_ = false; }
if (opts.update && $.isFunction(opts.update)) {
opts._update_ = opts.update;
delete opts.update;
} else { opts._update_ = false; }
opts.start = function (ev, ui) {
$(ui.item).css("border-width", "0");
$("td", ui.item).each(function (i) {
this.style.width = $t.grid.cols[i].style.width;
});
if ($t.p.subGrid) {
var subgid = $(ui.item).attr("id");
try {
$($t).jqGrid('collapseSubGridRow', subgid);
} catch (e) { }
}
if (opts._start_) {
opts._start_.apply(this, [ev, ui]);
}
};
opts.update = function (ev, ui) {
$(ui.item).css("border-width", "");
if ($t.p.rownumbers === true) {
$("td.jqgrid-rownum", $t.rows).each(function (i) {
$(this).html(i + 1 + (parseInt($t.p.page, 10) - 1) * parseInt($t.p.rowNum, 10));
});
}
if (opts._update_) {
opts._update_.apply(this, [ev, ui]);
}
};
$("tbody:first", $t).sortable(opts);
$("tbody:first > .jqgrow", $t).disableSelection();
}
});
},
gridDnD: function (opts) {
return this.each(function () {
var $t = this, i, cn;
if (!$t.grid) { return; }
// Currently we disable a treeGrid drag and drop
if ($t.p.treeGrid) { return; }
if (!$.fn.draggable || !$.fn.droppable) { return; }
function updateDnD() {
var datadnd = $.data($t, "dnd");
$("tr.jqgrow:not(.ui-draggable)", $t).draggable($.isFunction(datadnd.drag) ? datadnd.drag.call($($t), datadnd) : datadnd.drag);
}
var appender = "
";
if ($("#jqgrid_dnd")[0] === undefined) {
$('body').append(appender);
}
if (typeof opts === 'string' && opts === 'updateDnD' && $t.p.jqgdnd === true) {
updateDnD();
return;
}
opts = $.extend({
"drag": function (opts) {
return $.extend({
start: function (ev, ui) {
var i, subgid;
// if we are in subgrid mode try to collapse the node
if ($t.p.subGrid) {
subgid = $(ui.helper).attr("id");
try {
$($t).jqGrid('collapseSubGridRow', subgid);
} catch (e) { }
}
// hack
// drag and drop does not insert tr in table, when the table has no rows
// we try to insert new empty row on the target(s)
for (i = 0; i < $.data($t, "dnd").connectWith.length; i++) {
if ($($.data($t, "dnd").connectWith[i]).jqGrid('getGridParam', 'reccount') === 0) {
$($.data($t, "dnd").connectWith[i]).jqGrid('addRowData', 'jqg_empty_row', {});
}
}
ui.helper.addClass("ui-state-highlight");
$("td", ui.helper).each(function (i) {
this.style.width = $t.grid.headers[i].width + "px";
});
if (opts.onstart && $.isFunction(opts.onstart)) { opts.onstart.call($($t), ev, ui); }
},
stop: function (ev, ui) {
var i, ids;
if (ui.helper.dropped && !opts.dragcopy) {
ids = $(ui.helper).attr("id");
if (ids === undefined) { ids = $(this).attr("id"); }
$($t).jqGrid('delRowData', ids);
}
// if we have a empty row inserted from start event try to delete it
for (i = 0; i < $.data($t, "dnd").connectWith.length; i++) {
$($.data($t, "dnd").connectWith[i]).jqGrid('delRowData', 'jqg_empty_row');
}
if (opts.onstop && $.isFunction(opts.onstop)) { opts.onstop.call($($t), ev, ui); }
}
}, opts.drag_opts || {});
},
"drop": function (opts) {
return $.extend({
accept: function (d) {
if (!$(d).hasClass('jqgrow')) { return d; }
var tid = $(d).closest("table.ui-jqgrid-btable");
if (tid.length > 0 && $.data(tid[0], "dnd") !== undefined) {
var cn = $.data(tid[0], "dnd").connectWith;
return $.inArray('#' + $.jgrid.jqID(this.id), cn) !== -1 ? true : false;
}
return false;
},
drop: function (ev, ui) {
if (!$(ui.draggable).hasClass('jqgrow')) { return; }
var accept = $(ui.draggable).attr("id");
var getdata = ui.draggable.parent().parent().jqGrid('getRowData', accept);
if (!opts.dropbyname) {
var j = 0, tmpdata = {}, nm, key;
var dropmodel = $("#" + $.jgrid.jqID(this.id)).jqGrid('getGridParam', 'colModel');
try {
for (key in getdata) {
if (getdata.hasOwnProperty(key)) {
nm = dropmodel[j].name;
if (!(nm === 'cb' || nm === 'rn' || nm === 'subgrid')) {
if (getdata.hasOwnProperty(key) && dropmodel[j]) {
tmpdata[nm] = getdata[key];
}
}
j++;
}
}
getdata = tmpdata;
} catch (e) { }
}
ui.helper.dropped = true;
if (opts.beforedrop && $.isFunction(opts.beforedrop)) {
//parameters to this callback - event, element, data to be inserted, sender, reciever
// should return object which will be inserted into the reciever
var datatoinsert = opts.beforedrop.call(this, ev, ui, getdata, $('#' + $.jgrid.jqID($t.p.id)), $(this));
if (datatoinsert !== undefined && datatoinsert !== null && typeof datatoinsert === "object") { getdata = datatoinsert; }
}
if (ui.helper.dropped) {
var grid;
if (opts.autoid) {
if ($.isFunction(opts.autoid)) {
grid = opts.autoid.call(this, getdata);
} else {
grid = Math.ceil(Math.random() * 1000);
grid = opts.autoidprefix + grid;
}
}
// NULL is interpreted as undefined while null as object
$("#" + $.jgrid.jqID(this.id)).jqGrid('addRowData', grid, getdata, opts.droppos);
}
if (opts.ondrop && $.isFunction(opts.ondrop)) { opts.ondrop.call(this, ev, ui, getdata); }
}
}, opts.drop_opts || {});
},
"onstart": null,
"onstop": null,
"beforedrop": null,
"ondrop": null,
"drop_opts": {
"activeClass": "ui-state-active",
"hoverClass": "ui-state-hover"
},
"drag_opts": {
"revert": "invalid",
"helper": "clone",
"cursor": "move",
"appendTo": "#jqgrid_dnd",
"zIndex": 5000
},
"dragcopy": false,
"dropbyname": false,
"droppos": "first",
"autoid": true,
"autoidprefix": "dnd_"
}, opts || {});
if (!opts.connectWith) { return; }
opts.connectWith = opts.connectWith.split(",");
opts.connectWith = $.map(opts.connectWith, function (n) { return $.trim(n); });
$.data($t, "dnd", opts);
if ($t.p.reccount !== 0 && !$t.p.jqgdnd) {
updateDnD();
}
$t.p.jqgdnd = true;
for (i = 0; i < opts.connectWith.length; i++) {
cn = opts.connectWith[i];
$(cn).droppable($.isFunction(opts.drop) ? opts.drop.call($($t), opts) : opts.drop);
}
});
},
gridResize: function (opts) {
return this.each(function () {
var $t = this, gID = $.jgrid.jqID($t.p.id), req;
if (!$t.grid || !$.fn.resizable) { return; }
opts = $.extend({}, opts || {});
if (opts.alsoResize) {
opts._alsoResize_ = opts.alsoResize;
delete opts.alsoResize;
} else {
opts._alsoResize_ = false;
}
if (opts.stop && $.isFunction(opts.stop)) {
opts._stop_ = opts.stop;
delete opts.stop;
} else {
opts._stop_ = false;
}
opts.stop = function (ev, ui) {
$($t).jqGrid('setGridParam', { height: $("#gview_" + gID + " .ui-jqgrid-bdiv").height() });
$($t).jqGrid('setGridWidth', ui.size.width, opts.shrinkToFit);
if (opts._stop_) { opts._stop_.call($t, ev, ui); }
if ($t.p.caption) {
$("#gbox_" + gID).css({ 'height': 'auto' });
}
if ($t.p.frozenColumns) {
if (req) clearTimeout(req);
req = setTimeout(function () {
if (req) clearTimeout(req);
$("#" + gID).jqGrid("destroyFrozenColumns");
$("#" + gID).jqGrid("setFrozenColumns");
});
}
};
if (opts._alsoResize_) {
var optstest = "{\'#gview_" + gID + " .ui-jqgrid-bdiv\':true,'" + opts._alsoResize_ + "':true}";
opts.alsoResize = eval('(' + optstest + ')'); // the only way that I found to do this
} else {
opts.alsoResize = $(".ui-jqgrid-bdiv", "#gview_" + gID);
}
delete opts._alsoResize_;
$("#gbox_" + gID).resizable(opts);
});
}
});
//module begin
function _pivotfilter(fn, context) {
/*jshint validthis: true */
var i,
value,
result = [],
length;
if (!this || typeof fn !== 'function' || (fn instanceof RegExp)) {
throw new TypeError();
}
length = this.length;
for (i = 0; i < length; i++) {
if (this.hasOwnProperty(i)) {
value = this[i];
if (fn.call(context, value, i, this)) {
result.push(value);
// We need break in order to cancel loop
// in case the row is found
break;
}
}
}
return result;
}
$.assocArraySize = function (obj) {
// http://stackoverflow.com/a/6700/11236
var size = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) {
size++;
}
}
return size;
};
$.jgrid.extend({
pivotSetup: function (data, options) {
// data should come in json format
// The function return the new colModel and the transformed data
// again with group setup options which then will be passed to the grid
var columns = [],
pivotrows = [],
summaries = [],
member = [],
labels = [],
groupOptions = {
grouping: true,
groupingView: {
groupField: [],
groupSummary: [],
groupSummaryPos: []
}
},
headers = [],
o = $.extend({
rowTotals: false,
rowTotalsText: 'Total',
// summary columns
colTotals: false,
groupSummary: true,
groupSummaryPos: 'header',
frozenStaticCols: false
}, options || {});
this.each(function () {
var
row,
rowindex,
i,
rowlen = data.length,
xlen, ylen, aggrlen,
tmp,
newObj,
r = 0;
// utility funcs
/*
* Filter the data to a given criteria. Return the firt occurance
*/
function find(ar, fun, extra) {
var res;
res = _pivotfilter.call(ar, fun, extra);
return res.length > 0 ? res[0] : null;
}
/*
* Check if the grouped row column exist (See find)
* If the row is not find in pivot rows retun null,
* otherviese the column
*/
function findGroup(item, index) {
/*jshint validthis: true */
var j = 0, ret = true, i;
for (i in item) {
if (item.hasOwnProperty(i)) {
if (item[i] != this[j]) {
ret = false;
break;
}
j++;
if (j >= this.length) {
break;
}
}
}
if (ret) {
rowindex = index;
}
return ret;
}
/*
* Perform calculations of the pivot values.
*/
function calculation(oper, v, field, rc, _cnt) {
var ret;
switch (oper) {
case "sum":
ret = parseFloat(v || 0) + parseFloat((rc[field] || 0));
break;
case "count":
if (v === "" || v == null) {
v = 0;
}
if (rc.hasOwnProperty(field)) {
ret = v + 1;
} else {
ret = 0;
}
break;
case "min":
if (v === "" || v == null) {
ret = parseFloat(rc[field] || 0);
} else {
ret = Math.min(parseFloat(v), parseFloat(rc[field] || 0));
}
break;
case "max":
if (v === "" || v == null) {
ret = parseFloat(rc[field] || 0);
} else {
ret = Math.max(parseFloat(v), parseFloat(rc[field] || 0));
}
break;
case "avg": //avg grouping
ret = (parseFloat(v || 0) * (_cnt - 1) + parseFloat(rc[field] || 0)) / _cnt;
break;
}
return ret;
}
/*
* The function agragates the values of the pivot grid.
* Return the current row with pivot summary values
*/
function agregateFunc(row, aggr, value, curr) {
// default is sum
var arrln = aggr.length, i, label, j, jv, mainval = "", swapvals = [];
if ($.isArray(value)) {
jv = value.length;
swapvals = value;
} else {
jv = 1;
swapvals[0] = value;
}
member = [];
labels = [];
member.root = 0;
if (! !!curr._count) {
curr._count = 1;
} else {
curr._count++;
}
for (j = 0; j < jv; j++) {
var tmpmember = [], vl;
for (i = 0; i < arrln; i++) {
if (value == null) {
label = $.trim(aggr[i].member) + "_" + aggr[i].aggregator;
vl = label;
swapvals[0] = aggr[i].label || (aggr[i].aggregator + " " + $.trim(aggr[i].member));
} else {
vl = value[j].replace(/\s+/g, '');
try {
label = (arrln === 1 ? mainval + vl : mainval + vl + "_" + aggr[i].aggregator + "_" + String(i));
} catch (e) { }
swapvals[j] = value[j];
}
//if(j<=1 && vl !== '_r_Totals' && mainval === "") { // this does not fix full the problem
//mainval = vl;
//}
label = !isNaN(parseInt(label, 10)) ? label + " " : label;
curr[label] = tmpmember[label] = calculation(aggr[i].aggregator, curr[label], aggr[i].member, row, curr._count);
}
mainval += value[j].replace(/\s+/g, '');
//vl = !isNaN(parseInt(vl,10)) ? vl + " " : vl;
member[label] = tmpmember;
labels[label] = swapvals[j];
}
return curr;
}
// Making the row totals without to add in yDimension
if (o.rowTotals && o.yDimension.length > 0) {
var dn = o.yDimension[0].dataName;
o.yDimension.splice(0, 0, { dataName: dn });
o.yDimension[0].converter = function () { return '_r_Totals'; };
}
// build initial columns (colModel) from xDimension
xlen = $.isArray(o.xDimension) ? o.xDimension.length : 0;
ylen = o.yDimension.length;
aggrlen = $.isArray(o.aggregates) ? o.aggregates.length : 0;
if (xlen === 0 || aggrlen === 0) {
throw ("xDimension or aggregates optiona are not set!");
}
var colc;
for (i = 0; i < xlen; i++) {
colc = { name: o.xDimension[i].dataName, frozen: o.frozenStaticCols };
if (o.xDimension[i].isGroupField == null) {
o.xDimension[i].isGroupField = true;
}
colc = $.extend(true, colc, o.xDimension[i]);
columns.push(colc);
}
var groupfields = xlen - 1, tree = {};
//tree = { text: 'root', leaf: false, children: [] };
//loop over alll the source data
while (r < rowlen) {
row = data[r];
var xValue = [];
var yValue = [];
tmp = {};
i = 0;
// build the data from xDimension
do {
xValue[i] = $.trim(row[o.xDimension[i].dataName]);
tmp[o.xDimension[i].dataName] = xValue[i];
i++;
} while (i < xlen);
var k = 0;
rowindex = -1;
// check to see if the row is in our new pivotrow set
newObj = find(pivotrows, findGroup, xValue);
if (!newObj) {
// if the row is not in our set
k = 0;
// if yDimension is set
if (ylen >= 1) {
// build the cols set in yDimension
for (k = 0; k < ylen; k++) {
yValue[k] = $.trim(row[o.yDimension[k].dataName]);
// Check to see if we have user defined conditions
if (o.yDimension[k].converter && $.isFunction(o.yDimension[k].converter)) {
yValue[k] = o.yDimension[k].converter.call(this, yValue[k], xValue, yValue);
}
}
// make the colums based on aggregates definition
// and return the members for late calculation
tmp = agregateFunc(row, o.aggregates, yValue, tmp);
} else if (ylen === 0) {
// if not set use direct the aggregates
tmp = agregateFunc(row, o.aggregates, null, tmp);
}
// add the result in pivot rows
pivotrows.push(tmp);
} else {
// the pivot exists
if (rowindex >= 0) {
k = 0;
// make the recalculations
if (ylen >= 1) {
for (k = 0; k < ylen; k++) {
yValue[k] = $.trim(row[o.yDimension[k].dataName]);
if (o.yDimension[k].converter && $.isFunction(o.yDimension[k].converter)) {
yValue[k] = o.yDimension[k].converter.call(this, yValue[k], xValue, yValue);
}
}
newObj = agregateFunc(row, o.aggregates, yValue, newObj);
} else if (ylen === 0) {
newObj = agregateFunc(row, o.aggregates, null, newObj);
}
// update the row
pivotrows[rowindex] = newObj;
}
}
var kj = 0, current = null, existing = null, kk;
// Build a JSON tree from the member (see aggregateFunc)
// to make later the columns
//
for (kk in member) {
if (member.hasOwnProperty(kk)) {
if (kj === 0) {
if (!tree.children || tree.children === undefined) {
tree = { text: kk, level: 0, children: [], label: kk };
}
current = tree.children;
} else {
existing = null;
for (i = 0; i < current.length; i++) {
if (current[i].text === kk) {
//current[i].fields=member[kk];
existing = current[i];
break;
}
}
if (existing) {
current = existing.children;
} else {
current.push({ children: [], text: kk, level: kj, fields: member[kk], label: labels[kk] });
current = current[current.length - 1].children;
}
}
kj++;
}
}
r++;
}
var lastval = [], initColLen = columns.length, swaplen = initColLen;
if (ylen > 0) {
headers[ylen - 1] = { useColSpanStyle: false, groupHeaders: [] };
}
/*
* Recursive function which uses the tree to build the
* columns from the pivot values and set the group Headers
*/
function list(items) {
var l, j, key, k, col;
for (key in items) { // iterate
if (items.hasOwnProperty(key)) {
// write amount of spaces according to level
// and write name and newline
if (typeof items[key] !== "object") {
// If not a object build the header of the appropriate level
if (key === 'level') {
if (lastval[items.level] === undefined) {
lastval[items.level] = '';
if (items.level > 0 && items.text.indexOf('_r_Totals') === -1) {
headers[items.level - 1] = {
useColSpanStyle: false,
groupHeaders: []
};
}
}
if (lastval[items.level] !== items.text && items.children.length && items.text.indexOf('_r_Totals') === -1) {
if (items.level > 0) {
headers[items.level - 1].groupHeaders.push({
titleText: items.label,
numberOfColumns: 0
});
var collen = headers[items.level - 1].groupHeaders.length - 1,
colpos = collen === 0 ? swaplen : initColLen;//+aggrlen;
if (items.level - 1 === (o.rowTotals ? 1 : 0)) {
if (collen > 0) {
var l1 = 0;
for (var kk = 0; kk < collen; kk++) {
l1 += headers[items.level - 1].groupHeaders[kk].numberOfColumns;
}
if (l1) {
colpos = l1 + xlen;
}
}
}
if (columns[colpos]) {
headers[items.level - 1].groupHeaders[collen].startColumnName = columns[colpos].name;
headers[items.level - 1].groupHeaders[collen].numberOfColumns = columns.length - colpos;
}
initColLen = columns.length;
}
}
lastval[items.level] = items.text;
}
// This is in case when the member contain more than one summary item
if (items.level === ylen && key === 'level' && ylen > 0) {
if (aggrlen > 1) {
var ll = 1;
for (l in items.fields) {
if (items.fields.hasOwnProperty(l)) {
if (ll === 1) {
headers[ylen - 1].groupHeaders.push({ startColumnName: l, numberOfColumns: 1, titleText: items.label || items.text });
}
ll++;
}
}
headers[ylen - 1].groupHeaders[headers[ylen - 1].groupHeaders.length - 1].numberOfColumns = ll - 1;
} else {
headers.splice(ylen - 1, 1);
}
}
}
// if object, call recursively
if (items[key] != null && typeof items[key] === "object") {
list(items[key]);
}
// Finally build the columns
if (key === 'level') {
if (items.level > 0 && (items.level === (ylen === 0 ? items.level : ylen) || lastval[items.level].indexOf('_r_Totals') !== -1)) {
j = 0;
for (l in items.fields) {
if (items.fields.hasOwnProperty(l)) {
col = {};
for (k in o.aggregates[j]) {
if (o.aggregates[j].hasOwnProperty(k)) {
switch (k) {
case 'member':
case 'label':
case 'aggregator':
break;
default:
col[k] = o.aggregates[j][k];
}
}
}
if (aggrlen > 1) {
col.name = l;
col.label = o.aggregates[j].label || items.label;
} else {
col.name = items.text;
col.label = items.text === '_r_Totals' ? o.rowTotalsText : items.label;
}
columns.push(col);
j++;
}
}
}
}
}
}
}
list(tree);
var nm;
// loop again trougth the pivot rows in order to build grand total
if (o.colTotals) {
var plen = pivotrows.length;
while (plen--) {
for (i = xlen; i < columns.length; i++) {
nm = columns[i].name;
if (!summaries[nm]) {
summaries[nm] = parseFloat(pivotrows[plen][nm] || 0);
} else {
summaries[nm] += parseFloat(pivotrows[plen][nm] || 0);
}
}
}
}
// based on xDimension levels build grouping
if (groupfields > 0) {
for (i = 0; i < groupfields; i++) {
if (columns[i].isGroupField) {
groupOptions.groupingView.groupField.push(columns[i].name);
groupOptions.groupingView.groupSummary.push(o.groupSummary);
groupOptions.groupingView.groupSummaryPos.push(o.groupSummaryPos);
}
}
} else {
// no grouping is needed
groupOptions.grouping = false;
}
groupOptions.sortname = columns[groupfields].name;
groupOptions.groupingView.hideFirstGroupCol = true;
});
// return the final result.
return { "colModel": columns, "rows": pivotrows, "groupOptions": groupOptions, "groupHeaders": headers, summary: summaries };
},
jqPivot: function (data, pivotOpt, gridOpt, ajaxOpt) {
return this.each(function () {
var $t = this;
function pivot(data) {
var pivotGrid = jQuery($t).jqGrid('pivotSetup', data, pivotOpt),
footerrow = $.assocArraySize(pivotGrid.summary) > 0 ? true : false,
query = $.jgrid.from.call($t, pivotGrid.rows), i, so, st, len;
if (pivotOpt.ignoreCase) {
query = query.ignoreCase();
}
for (i = 0; i < pivotGrid.groupOptions.groupingView.groupField.length; i++) {
so = pivotOpt.xDimension[i].sortorder ? pivotOpt.xDimension[i].sortorder : 'asc';
st = pivotOpt.xDimension[i].sorttype ? pivotOpt.xDimension[i].sorttype : 'text';
query.orderBy(pivotGrid.groupOptions.groupingView.groupField[i], so, st, '', st);
}
len = pivotOpt.xDimension.length;
if (pivotGrid.groupOptions.sortname && len) {
so = pivotOpt.xDimension[len - 1].sortorder ? pivotOpt.xDimension[len - 1].sortorder : 'asc';
st = pivotOpt.xDimension[len - 1].sorttype ? pivotOpt.xDimension[len - 1].sorttype : 'text';
query.orderBy(pivotGrid.groupOptions.sortname, so, st, '', st);
}
jQuery($t).jqGrid($.extend(true, {
datastr: $.extend(query.select(), footerrow ? { userdata: pivotGrid.summary } : {}),
datatype: "jsonstring",
footerrow: footerrow,
userDataOnFooter: footerrow,
colModel: pivotGrid.colModel,
viewrecords: true,
sortname: pivotOpt.xDimension[0].dataName // ?????
}, pivotGrid.groupOptions, gridOpt || {}));
var gHead = pivotGrid.groupHeaders;
if (gHead.length) {
for (i = 0; i < gHead.length ; i++) {
if (gHead[i] && gHead[i].groupHeaders.length) {
jQuery($t).jqGrid('setGroupHeaders', gHead[i]);
}
}
}
if (pivotOpt.frozenStaticCols) {
jQuery($t).jqGrid("setFrozenColumns");
}
}
if (typeof data === "string") {
$.ajax($.extend({
url: data,
dataType: 'json',
success: function (response) {
pivot($.jgrid.getAccessor(response, ajaxOpt && ajaxOpt.reader ? ajaxOpt.reader : 'rows'));
}
}, ajaxOpt || {}));
} else {
pivot(data);
}
});
}
});
//module begin
$.jgrid.extend({
setSubGrid: function () {
return this.each(function () {
var $t = this, cm, i,
classes = $.jgrid.styleUI[($t.p.styleUI || 'jQueryUI')].subgrid,
suboptions = {
plusicon: classes.icon_plus,
minusicon: classes.icon_minus,
openicon: classes.icon_open,
expandOnLoad: false,
delayOnLoad: 50,
selectOnExpand: false,
selectOnCollapse: false,
reloadOnExpand: true
};
$t.p.subGridOptions = $.extend(suboptions, $t.p.subGridOptions || {});
$t.p.colNames.unshift("");
$t.p.colModel.unshift({ name: 'subgrid', width: $.jgrid.cell_width ? $t.p.subGridWidth + $t.p.cellLayout : $t.p.subGridWidth, sortable: false, resizable: false, hidedlg: true, search: false, fixed: true });
cm = $t.p.subGridModel;
if (cm[0]) {
cm[0].align = $.extend([], cm[0].align || []);
for (i = 0; i < cm[0].name.length; i++) { cm[0].align[i] = cm[0].align[i] || 'left'; }
}
});
},
addSubGridCell: function (pos, iRow) {
var prp = '', ic, sid, icb;
this.each(function () {
prp = this.formatCol(pos, iRow);
sid = this.p.id;
ic = this.p.subGridOptions.plusicon;
icb = $.jgrid.styleUI[(this.p.styleUI || 'jQueryUI')].common;
});
return "
";
},
addSubGrid: function (pos, sind) {
return this.each(function () {
var ts = this;
if (!ts.grid) { return; }
var base = $.jgrid.styleUI[(ts.p.styleUI || 'jQueryUI')].base,
common = $.jgrid.styleUI[(ts.p.styleUI || 'jQueryUI')].common;
//-------------------------
var subGridCell = function (trdiv, cell, pos) {
var tddiv = $("
").html(cell);
$(trdiv).append(tddiv);
};
var subGridXml = function (sjxml, sbid) {
var tddiv, i, sgmap,
dummy = $("
"),
trdiv = $("
");
for (i = 0; i < ts.p.subGridModel[0].name.length; i++) {
tddiv = $("
");
for (var ii in dfop.nodeTools) {
var toolItem = dfop.nodeTools[ii];
ht.push("");
}
ht.push("
");
}
ht.push("
");
if (nd.hasChildren) {
if (nd.isexpand) {
ht.push("
");
if (nd.ChildNodes) {
var l = nd.ChildNodes.length;
for (var k = 0; k < l; k++) {
nd.ChildNodes[k].parent = nd;
buildnode(nd.ChildNodes[k], ht, deep + 1, path + "." + k, k == l - 1);
}
}
ht.push("
");
}
else {
ht.push("
");
if (nd.ChildNodes) {
var l = nd.ChildNodes.length;
for (var k = 0; k < l; k++) {
nd.ChildNodes[k].parent = nd;
buildnode(nd.ChildNodes[k], ht, deep + 1, path + "." + k, k == l - 1);
}
}
ht.push("
");
}
}
ht.push("
");
nd.render = true;
}
function getItem(path) {
var ap = path.split(".");
var t = treenodes;
for (var i = 0; i < ap.length; i++) {
if (i == 0) {
t = t[ap[i]];
}
else {
t = t.ChildNodes[ap[i]];
}
}
return t;
}
function check(item, state, type) {
var pstate = item.checkstate;
if (type == 1) {
item.checkstate = state;
}
else {
var cs = item.ChildNodes;
var l = cs.length;
var ch = true;
for (var i = 0; i < l; i++) {
if ((state == 1 && cs[i].checkstate != 1) || state == 0 && cs[i].checkstate != 0) {
ch = false;
break;
}
}
if (ch) {
item.checkstate = state;
}
else {
item.checkstate = 2;
}
}
if (item.render && pstate != item.checkstate) {
var nid = item.id.replace(/[^\w]/gi, "_");
var et = $("#" + id + "_" + nid + "_cb");
if (et.length == 1) {
et.attr("src", dfop.cbiconpath + dfop.icons[item.checkstate]);
}
}
}
function cascade(fn, item, args) {
if (fn(item, args, 1) != false) {
if (item.ChildNodes != null && item.ChildNodes.length > 0) {
var cs = item.ChildNodes;
for (var i = 0, len = cs.length; i < len; i++) {
cascade(fn, cs[i], args);
}
}
}
}
function bubble(fn, item, args) {
var p = item.parent;
while (p) {
if (fn(p, args, 0) === false) {
break;
}
p = p.parent;
}
}
function nodeclick(e) {
var path = $(this).attr("tpath");
var et = e.target || e.srcElement;
var item = getItem(path);
if (et.tagName == "IMG") {
if ($(et).hasClass("bbit-tree-elbow-plus") || $(et).hasClass("bbit-tree-elbow-end-plus")) {
if ($(this).find('i').hasClass('fa-folder')) {
$(this).find('i').swapClass('fa-folder', 'fa-folder-open');
}
var ul = $(this).next();
if (ul.hasClass("bbit-tree-node-ct")) {
ul.slideDown(200);
}
else {
var deep = path.split(".").length;
if (item.complete) {
item.ChildNodes != null && asnybuild(item.ChildNodes, deep, path, ul, item);
}
else {
$(this).addClass("bbit-tree-node-loading");
asnyloadc(item, true, function (data) {
item.complete = true;
item.ChildNodes = data;
asnybuild(data, deep, path, ul, item);
});
}
}
if ($(et).hasClass("bbit-tree-elbow-plus")) {
$(et).swapClass("bbit-tree-elbow-plus", "bbit-tree-elbow-minus");
}
else {
$(et).swapClass("bbit-tree-elbow-end-plus", "bbit-tree-elbow-end-minus");
}
$(this).swapClass("bbit-tree-node-collapsed", "bbit-tree-node-expanded");
}
else if ($(et).hasClass("bbit-tree-elbow-minus") || $(et).hasClass("bbit-tree-elbow-end-minus")) {
if ($(this).find('i').hasClass('fa-folder-open')) {
$(this).find('i').swapClass('fa-folder-open', 'fa-folder');
}
$(this).next().slideUp(200);
if ($(et).hasClass("bbit-tree-elbow-minus")) {
$(et).swapClass("bbit-tree-elbow-minus", "bbit-tree-elbow-plus");
}
else {
$(et).swapClass("bbit-tree-elbow-end-minus", "bbit-tree-elbow-end-plus");
}
$(this).swapClass("bbit-tree-node-expanded", "bbit-tree-node-collapsed");
}
else if ($(et).hasClass("bbit-tree-node-cb")) {
var s = item.checkstate != 1 ? 1 : 0;
var r = true;
if (dfop.oncheckboxclick) {
r = dfop.oncheckboxclick.call(et, item, s);
}
if (r != false) {
if (dfop.cascadecheck) {
cascade(check, item, s);
bubble(check, item, s);
}
else {
check(item, s, 1);
}
}
}
}
else {
if (dfop.citem) {
var nid = dfop.citem.id.replace(/[^\w]/gi, "_");
$("." + id).removeClass("bbit-tree-selected");
}
dfop.citem = item;
$("." + id).find('div').removeClass("bbit-tree-selected");
$(this).addClass("bbit-tree-selected");
if (dfop.onnodeclick) {
if (!item.expand) {
item.expand = function () { expandnode.call(item); };
}
dfop.onnodeclick.call(this, item);
}
}
}
function expandnode() {
var item = this;
var nid = item.id.replace(/[^\w]/gi, "_");
var img = $("#" + id + "_" + nid + " img.bbit-tree-ec-icon");
if (img.length > 0) {
img.click();
}
}
function asnybuild(nodes, deep, path, ul, pnode) {
var l = nodes.length;
if (l > 0) {
var ht = [];
for (var i = 0; i < l; i++) {
nodes[i].parent = pnode;
buildnode(nodes[i], ht, deep, path + "." + i, i == l - 1);
}
ul.html(ht.join(""));
ht = null;
InitEvent(ul);
}
ul.addClass("bbit-tree-node-ct").css({ "z-index": 0, position: "static", visibility: "visible", top: "auto", left: "auto", display: "" });
ul.prev().removeClass("bbit-tree-node-loading");
}
function asnyloadc(pnode, isAsync, callback) {
if (dfop.url) {
if (pnode && pnode != null)
var param = builparam(pnode);
if (dfop.param != null) {
var param = dfop.param
}
$.ajax({
type: dfop.method,
url: dfop.url,
data: param,
async: isAsync,
dataType: dfop.datatype,
success: callback,
error: function (e) { dialogMsg("服务端未响应。", -1); }
});
}
}
function builparam(node) {
var p = [{ name: "id", value: encodeURIComponent(node.id) }
, { name: "text", value: encodeURIComponent(node.text) }
, { name: "value", value: encodeURIComponent(node.value) }
, { name: "checkstate", value: node.checkstate }];
return p;
}
function bindevent() {
$(this).hover(function () {
$(this).addClass("bbit-tree-node-over");
}, function () {
$(this).removeClass("bbit-tree-node-over");
}).click(nodeclick)
.find("img.bbit-tree-ec-icon").each(function (e) {
if (!$(this).hasClass("bbit-tree-elbow")) {
$(this).hover(function () {
$(this).parent().addClass("bbit-tree-ec-over");
}, function () {
$(this).parent().removeClass("bbit-tree-ec-over");
});
}
});
}
function InitEvent(parent) {
var nodes = $("li.bbit-tree-node>div", parent);
nodes.each(bindevent);
}
function reflash(itemId) {
var nid = itemId.replace(/[^\w-]/gi, "_");
var node = $("#" + id + "_" + nid);
if (node.length > 0) {
node.addClass("bbit-tree-node-loading");
var isend = node.hasClass("bbit-tree-elbow-end") || node.hasClass("bbit-tree-elbow-end-plus") || node.hasClass("bbit-tree-elbow-end-minus");
var path = node.attr("tpath");
var deep = path.split(".").length;
var item = getItem(path);
if (item) {
asnyloadc(item, true, function (data) {
item.complete = true;
item.ChildNodes = data;
item.isexpand = true;
if (data && data.length > 0) {
item.hasChildren = true;
}
else {
item.hasChildren = false;
}
var ht = [];
buildnode(item, ht, deep - 1, path, isend);
ht.shift();
ht.pop();
var li = node.parent();
li.html(ht.join(""));
ht = null;
InitEvent(li);
bindevent.call(li.find(">div"));
});
}
}
}
function getck(items, c, fn) {
for (var i = 0, l = items.length; i < l; i++) {
(items[i].showcheck == true && items[i].checkstate == 1) && c.push(fn(items[i]));
if (items[i].ChildNodes != null && items[i].ChildNodes.length > 0) {
getck(items[i].ChildNodes, c, fn);
}
}
}
function getCkAndHalfCk(items, c, fn) {
for (var i = 0, l = items.length; i < l; i++) {
(items[i].showcheck == true && (items[i].checkstate == 1 || items[i].checkstate == 2)) && c.push(fn(items[i]));
if (items[i].ChildNodes != null && items[i].ChildNodes.length > 0) {
getCkAndHalfCk(items[i].ChildNodes, c, fn);
}
}
}
me[0].t = {
getSelectedNodes: function (gethalfchecknode) {
var s = [];
if (gethalfchecknode) {
getCkAndHalfCk(treenodes, s, function (item) { return item; });
}
else {
getck(treenodes, s, function (item) { return item; });
}
return s;
},
getSelectedValues: function () {
var s = [];
getck(treenodes, s, function (item) { return item.value; });
return s;
},
getCurrentItem: function () {
return dfop.citem;
},
reflash: function (itemOrItemId) {
var id;
if (typeof (itemOrItemId) == "string") {
id = itemOrItemId;
}
else {
id = itemOrItemId.id;
}
reflash(id);
}
};
return me;
};
$.fn.getCheckedNodes = function () {
var $id = $(this);
var _length = $id.attr('id').trim().length + 1;
var value = []
$id.find('.bbit-tree-node-cb').each(function () {
var _src = $(this).attr('src');
_src = _src.substr(_src.lastIndexOf("/") + 1);
if (_src == 'checkbox_1.png' || _src == 'checkbox_2.png') {
var _value = $(this).attr('id').substring(parseInt(_length)).replace(/_/g, "-");
_value = _value.substring(0, _value.length - 3);
value.push(_value)
}
});
return value;
};
$.fn.setCheckedNodes = function (data) {
var $id = $(this);
var id = $id.attr('id').trim();
$.each(data, function (i, item) {
var object = $id.find(('#' + id + '_' + item.replace(/-/g, "_") + '_cb'));
if (object.length != 0) {
object.trigger("click");
}
});
}
$.fn.setCheckedNodeOne = function (data) {
var $id = $(this);
var id = $id.attr('id').trim();
var object = $id.find(('#' + id + '_' + data.replace(/-/g, "_") + '_cb'));
if (object.length != 0) {
object.trigger("click");
}
}
$.fn.setNoCheckedNodes = function (item) {
var $id = $(this);
var id = $id.attr('id').trim();
var object = $id.find(('#' + id + '_' + item.replace(/-/g, "_") + '_cb'));
var _src = object.attr('src');
object.attr('src', _src.replace('checkbox_1.png', 'checkbox_0.png'));
}
$.fn.getTSNs = function (gethalfchecknode) {
if (this[0].t) {
return this[0].t.getSelectedNodes(gethalfchecknode);
}
return null;
};
$.fn.getCurrentNode = function () {
if (this[0].t) {
return this[0].t.getCurrentItem();
}
return null;
};
$.fn.reflash = function (ItemOrItemId) {
if (this[0].t) {
return this[0].t.reflash(ItemOrItemId);
}
};
$.fn.setTreeHeight = function (height) {
var me = $(this);
me.height(height);
}
$.fn.setNodeChecked = function (value) {
var $id = $(this);
var id = $id.attr('id').trim();
$id.find('.bbit-tree-selected').removeClass('bbit-tree-selected');
var object = $id.find(('#' + id + '_' + value.replace(/-/g, "_")));
object.addClass('bbit-tree-selected');
}
})(jQuery);