Merge pull request #14825 from williamdes/issue-14478-export-stream
[phpmyadmin.git] / js / makegrid.js
blob38c5607b1eec2ae207b0ad107a368b3ea3d05a5a
1 /* vim: set expandtab sw=4 ts=4 sts=4: */
2 /**
3  * Create advanced table (resize, reorder, and show/hide columns; and also grid editing).
4  * This function is designed mainly for table DOM generated from browsing a table in the database.
5  * For using this function in other table DOM, you may need to:
6  * - add "draggable" class in the table header <th>, in order to make it resizable, sortable or hidable
7  * - have at least one non-"draggable" header in the table DOM for placing column visibility drop-down arrow
8  * - pass the value "false" for the parameter "enableGridEdit"
9  * - adjust other parameter value, to select which features that will be enabled
10  *
11  * @param t the table DOM element
12  * @param enableResize Optional, if false, column resizing feature will be disabled
13  * @param enableReorder Optional, if false, column reordering feature will be disabled
14  * @param enableVisib Optional, if false, show/hide column feature will be disabled
15  * @param enableGridEdit Optional, if false, grid editing feature will be disabled
16  */
17 function PMA_makegrid (t, enableResize, enableReorder, enableVisib, enableGridEdit) {
18     var g = {
19         /** *********
20          * Constant
21          ***********/
22         minColWidth: 15,
25         /** *********
26          * Variables, assigned with default value, changed later
27          ***********/
28         actionSpan: 5,              // number of colspan in Actions header in a table
29         tableCreateTime: null,      // table creation time, used for saving column order and visibility to server, only available in "Browse tab"
31         // Column reordering variables
32         colOrder: [],      // array of column order
34         // Column visibility variables
35         colVisib: [],      // array of column visibility
36         showAllColText: '',         // string, text for "show all" button under column visibility list
37         visibleHeadersCount: 0,     // number of visible data headers
39         // Table hint variables
40         reorderHint: '',            // string, hint for column reordering
41         sortHint: '',               // string, hint for column sorting
42         markHint: '',               // string, hint for column marking
43         copyHint: '',               // string, hint for copy column name
44         showReorderHint: false,
45         showSortHint: false,
46         showMarkHint: false,
48         // Grid editing
49         isCellEditActive: false,    // true if current focus is in edit cell
50         isEditCellTextEditable: false,  // true if current edit cell is editable in the text input box (not textarea)
51         currentEditCell: null,      // reference to <td> that currently being edited
52         cellEditHint: '',           // hint shown when doing grid edit
53         gotoLinkText: '',           // "Go to link" text
54         wasEditedCellNull: false,   // true if last value of the edited cell was NULL
55         maxTruncatedLen: 0,         // number of characters that can be displayed in a cell
56         saveCellsAtOnce: false,     // $cfg[saveCellsAtOnce]
57         isCellEdited: false,        // true if at least one cell has been edited
58         saveCellWarning: '',        // string, warning text when user want to leave a page with unsaved edited data
59         lastXHR : null,             // last XHR object used in AJAX request
60         isSaving: false,            // true when currently saving edited data, used to handle double posting caused by pressing ENTER in grid edit text box in Chrome browser
61         alertNonUnique: '',         // string, alert shown when saving edited nonunique table
63         // Common hidden inputs
64         token: null,
65         server: null,
66         db: null,
67         table: null,
70         /** **********
71          * Functions
72          ************/
74         /**
75          * Start to resize column. Called when clicking on column separator.
76          *
77          * @param e event
78          * @param obj dragged div object
79          */
80         dragStartRsz: function (e, obj) {
81             var n = $(g.cRsz).find('div').index(obj);    // get the index of separator (i.e., column index)
82             $(obj).addClass('colborder_active');
83             g.colRsz = {
84                 x0: e.pageX,
85                 n: n,
86                 obj: obj,
87                 objLeft: $(obj).position().left,
88                 objWidth: $(g.t).find('th.draggable:visible:eq(' + n + ') span').outerWidth()
89             };
90             $(document.body).css('cursor', 'col-resize').noSelect();
91             if (g.isCellEditActive) {
92                 g.hideEditCell();
93             }
94         },
96         /**
97          * Start to reorder column. Called when clicking on table header.
98          *
99          * @param e event
100          * @param obj table header object
101          */
102         dragStartReorder: function (e, obj) {
103             // prepare the cCpy (column copy) and cPointer (column pointer) from the dragged column
104             $(g.cCpy).text($(obj).text());
105             var objPos = $(obj).position();
106             $(g.cCpy).css({
107                 top: objPos.top + 20,
108                 left: objPos.left,
109                 height: $(obj).height(),
110                 width: $(obj).width()
111             });
112             $(g.cPointer).css({
113                 top: objPos.top
114             });
116             // get the column index, zero-based
117             var n = g.getHeaderIdx(obj);
119             g.colReorder = {
120                 x0: e.pageX,
121                 y0: e.pageY,
122                 n: n,
123                 newn: n,
124                 obj: obj,
125                 objTop: objPos.top,
126                 objLeft: objPos.left
127             };
129             $(document.body).css('cursor', 'move').noSelect();
130             if (g.isCellEditActive) {
131                 g.hideEditCell();
132             }
133         },
135         /**
136          * Handle mousemove event when dragging.
137          *
138          * @param e event
139          */
140         dragMove: function (e) {
141             if (g.colRsz) {
142                 var dx = e.pageX - g.colRsz.x0;
143                 if (g.colRsz.objWidth + dx > g.minColWidth) {
144                     $(g.colRsz.obj).css('left', g.colRsz.objLeft + dx + 'px');
145                 }
146             } else if (g.colReorder) {
147                 // dragged column animation
148                 var dx = e.pageX - g.colReorder.x0;
149                 $(g.cCpy)
150                     .css('left', g.colReorder.objLeft + dx)
151                     .show();
153                 // pointer animation
154                 var hoveredCol = g.getHoveredCol(e);
155                 if (hoveredCol) {
156                     var newn = g.getHeaderIdx(hoveredCol);
157                     g.colReorder.newn = newn;
158                     if (newn !== g.colReorder.n) {
159                         // show the column pointer in the right place
160                         var colPos = $(hoveredCol).position();
161                         var newleft = newn < g.colReorder.n ?
162                             colPos.left :
163                             colPos.left + $(hoveredCol).outerWidth();
164                         $(g.cPointer)
165                             .css({
166                                 left: newleft,
167                                 visibility: 'visible'
168                             });
169                     } else {
170                         // no movement to other column, hide the column pointer
171                         $(g.cPointer).css('visibility', 'hidden');
172                     }
173                 }
174             }
175         },
177         /**
178          * Stop the dragging action.
179          *
180          * @param e event
181          */
182         dragEnd: function (e) {
183             if (g.colRsz) {
184                 var dx = e.pageX - g.colRsz.x0;
185                 var nw = g.colRsz.objWidth + dx;
186                 if (nw < g.minColWidth) {
187                     nw = g.minColWidth;
188                 }
189                 var n = g.colRsz.n;
190                 // do the resizing
191                 g.resize(n, nw);
193                 g.reposRsz();
194                 g.reposDrop();
195                 g.colRsz = false;
196                 $(g.cRsz).find('div').removeClass('colborder_active');
197                 rearrangeStickyColumns($(t).prev('.sticky_columns'), $(t));
198             } else if (g.colReorder) {
199                 // shift columns
200                 if (g.colReorder.newn !== g.colReorder.n) {
201                     g.shiftCol(g.colReorder.n, g.colReorder.newn);
202                     // assign new position
203                     var objPos = $(g.colReorder.obj).position();
204                     g.colReorder.objTop = objPos.top;
205                     g.colReorder.objLeft = objPos.left;
206                     g.colReorder.n = g.colReorder.newn;
207                     // send request to server to remember the column order
208                     if (g.tableCreateTime) {
209                         g.sendColPrefs();
210                     }
211                     g.refreshRestoreButton();
212                 }
214                 // animate new column position
215                 $(g.cCpy).stop(true, true)
216                     .animate({
217                         top: g.colReorder.objTop,
218                         left: g.colReorder.objLeft
219                     }, 'fast')
220                     .fadeOut();
221                 $(g.cPointer).css('visibility', 'hidden');
223                 g.colReorder = false;
224                 rearrangeStickyColumns($(t).prev('.sticky_columns'), $(t));
225             }
226             $(document.body).css('cursor', 'inherit').noSelect(false);
227         },
229         /**
230          * Resize column n to new width "nw"
231          *
232          * @param n zero-based column index
233          * @param nw new width of the column in pixel
234          */
235         resize: function (n, nw) {
236             $(g.t).find('tr').each(function () {
237                 $(this).find('th.draggable:visible:eq(' + n + ') span,' +
238                              'td:visible:eq(' + (g.actionSpan + n) + ') span')
239                     .css('width', nw);
240             });
241         },
243         /**
244          * Reposition column resize bars.
245          */
246         reposRsz: function () {
247             $(g.cRsz).find('div').hide();
248             var $firstRowCols = $(g.t).find('tr:first th.draggable:visible');
249             var $resizeHandles = $(g.cRsz).find('div').removeClass('condition');
250             $(g.t).find('table.pma_table').find('thead th:first').removeClass('before-condition');
251             for (var n = 0, l = $firstRowCols.length; n < l; n++) {
252                 var $col = $($firstRowCols[n]);
253                 var colWidth;
254                 if (navigator.userAgent.toLowerCase().indexOf('safari') !== -1) {
255                     colWidth = $col.outerWidth();
256                 } else {
257                     colWidth = $col.outerWidth(true);
258                 }
259                 $($resizeHandles[n]).css('left', $col.position().left + colWidth)
260                     .show();
261                 if ($col.hasClass('condition')) {
262                     $($resizeHandles[n]).addClass('condition');
263                     if (n > 0) {
264                         $($resizeHandles[n - 1]).addClass('condition');
265                     }
266                 }
267             }
268             if ($($resizeHandles[0]).hasClass('condition')) {
269                 $(g.t).find('thead th:first').addClass('before-condition');
270             }
271             $(g.cRsz).css('height', $(g.t).height());
272         },
274         /**
275          * Shift column from index oldn to newn.
276          *
277          * @param oldn old zero-based column index
278          * @param newn new zero-based column index
279          */
280         shiftCol: function (oldn, newn) {
281             $(g.t).find('tr').each(function () {
282                 if (newn < oldn) {
283                     $(this).find('th.draggable:eq(' + newn + '),' +
284                                  'td:eq(' + (g.actionSpan + newn) + ')')
285                         .before($(this).find('th.draggable:eq(' + oldn + '),' +
286                                                 'td:eq(' + (g.actionSpan + oldn) + ')'));
287                 } else {
288                     $(this).find('th.draggable:eq(' + newn + '),' +
289                                  'td:eq(' + (g.actionSpan + newn) + ')')
290                         .after($(this).find('th.draggable:eq(' + oldn + '),' +
291                                                'td:eq(' + (g.actionSpan + oldn) + ')'));
292                 }
293             });
294             // reposition the column resize bars
295             g.reposRsz();
297             // adjust the column visibility list
298             if (newn < oldn) {
299                 $(g.cList).find('.lDiv div:eq(' + newn + ')')
300                     .before($(g.cList).find('.lDiv div:eq(' + oldn + ')'));
301             } else {
302                 $(g.cList).find('.lDiv div:eq(' + newn + ')')
303                     .after($(g.cList).find('.lDiv div:eq(' + oldn + ')'));
304             }
305             // adjust the colOrder
306             var tmp = g.colOrder[oldn];
307             g.colOrder.splice(oldn, 1);
308             g.colOrder.splice(newn, 0, tmp);
309             // adjust the colVisib
310             if (g.colVisib.length > 0) {
311                 tmp = g.colVisib[oldn];
312                 g.colVisib.splice(oldn, 1);
313                 g.colVisib.splice(newn, 0, tmp);
314             }
315         },
317         /**
318          * Find currently hovered table column's header (excluding actions column).
319          *
320          * @param e event
321          * @return the hovered column's th object or undefined if no hovered column found.
322          */
323         getHoveredCol: function (e) {
324             var hoveredCol;
325             $headers = $(g.t).find('th.draggable:visible');
326             $headers.each(function () {
327                 var left = $(this).offset().left;
328                 var right = left + $(this).outerWidth();
329                 if (left <= e.pageX && e.pageX <= right) {
330                     hoveredCol = this;
331                 }
332             });
333             return hoveredCol;
334         },
336         /**
337          * Get a zero-based index from a <th class="draggable"> tag in a table.
338          *
339          * @param obj table header <th> object
340          * @return zero-based index of the specified table header in the set of table headers (visible or not)
341          */
342         getHeaderIdx: function (obj) {
343             return $(obj).parents('tr').find('th.draggable').index(obj);
344         },
346         /**
347          * Reposition the columns back to normal order.
348          */
349         restoreColOrder: function () {
350             // use insertion sort, since we already have shiftCol function
351             for (var i = 1; i < g.colOrder.length; i++) {
352                 var x = g.colOrder[i];
353                 var j = i - 1;
354                 while (j >= 0 && x < g.colOrder[j]) {
355                     j--;
356                 }
357                 if (j !== i - 1) {
358                     g.shiftCol(i, j + 1);
359                 }
360             }
361             if (g.tableCreateTime) {
362                 // send request to server to remember the column order
363                 g.sendColPrefs();
364             }
365             g.refreshRestoreButton();
366         },
368         /**
369          * Send column preferences (column order and visibility) to the server.
370          */
371         sendColPrefs: function () {
372             if ($(g.t).is('.ajax')) {   // only send preferences if ajax class
373                 var post_params = {
374                     ajax_request: true,
375                     db: g.db,
376                     table: g.table,
377                     token: g.token,
378                     server: g.server,
379                     set_col_prefs: true,
380                     table_create_time: g.tableCreateTime
381                 };
382                 if (g.colOrder.length > 0) {
383                     $.extend(post_params, { col_order: g.colOrder.toString() });
384                 }
385                 if (g.colVisib.length > 0) {
386                     $.extend(post_params, { col_visib: g.colVisib.toString() });
387                 }
388                 $.post('sql.php', post_params, function (data) {
389                     if (data.success !== true) {
390                         var $temp_div = $(document.createElement('div'));
391                         $temp_div.html(data.error);
392                         $temp_div.addClass('error');
393                         PMA_ajaxShowMessage($temp_div, false);
394                     }
395                 });
396             }
397         },
399         /**
400          * Refresh restore button state.
401          * Make restore button disabled if the table is similar with initial state.
402          */
403         refreshRestoreButton: function () {
404             // check if table state is as initial state
405             var isInitial = true;
406             for (var i = 0; i < g.colOrder.length; i++) {
407                 if (g.colOrder[i] !== i) {
408                     isInitial = false;
409                     break;
410                 }
411             }
412             // check if only one visible column left
413             var isOneColumn = g.visibleHeadersCount === 1;
414             // enable or disable restore button
415             if (isInitial || isOneColumn) {
416                 $(g.o).find('div.restore_column').hide();
417             } else {
418                 $(g.o).find('div.restore_column').show();
419             }
420         },
422         /**
423          * Update current hint using the boolean values (showReorderHint, showSortHint, etc.).
424          *
425          */
426         updateHint: function () {
427             var text = '';
428             if (!g.colRsz && !g.colReorder) {     // if not resizing or dragging
429                 if (g.visibleHeadersCount > 1) {
430                     g.showReorderHint = true;
431                 }
432                 if ($(t).find('th.marker').length > 0) {
433                     g.showMarkHint = true;
434                 }
435                 if (g.showSortHint && g.sortHint) {
436                     text += text.length > 0 ? '<br />' : '';
437                     text += '- ' + g.sortHint;
438                 }
439                 if (g.showMultiSortHint && g.strMultiSortHint) {
440                     text += text.length > 0 ? '<br />' : '';
441                     text += '- ' + g.strMultiSortHint;
442                 }
443                 if (g.showMarkHint &&
444                     g.markHint &&
445                     ! g.showSortHint && // we do not show mark hint, when sort hint is shown
446                     g.showReorderHint &&
447                     g.reorderHint
448                 ) {
449                     text += text.length > 0 ? '<br />' : '';
450                     text += '- ' + g.reorderHint;
451                     text += text.length > 0 ? '<br />' : '';
452                     text += '- ' + g.markHint;
453                     text += text.length > 0 ? '<br />' : '';
454                     text += '- ' + g.copyHint;
455                 }
456             }
457             return text;
458         },
460         /**
461          * Toggle column's visibility.
462          * After calling this function and it returns true, afterToggleCol() must be called.
463          *
464          * @return boolean True if the column is toggled successfully.
465          */
466         toggleCol: function (n) {
467             if (g.colVisib[n]) {
468                 // can hide if more than one column is visible
469                 if (g.visibleHeadersCount > 1) {
470                     $(g.t).find('tr').each(function () {
471                         $(this).find('th.draggable:eq(' + n + '),' +
472                                      'td:eq(' + (g.actionSpan + n) + ')')
473                             .hide();
474                     });
475                     g.colVisib[n] = 0;
476                     $(g.cList).find('.lDiv div:eq(' + n + ') input').prop('checked', false);
477                 } else {
478                     // cannot hide, force the checkbox to stay checked
479                     $(g.cList).find('.lDiv div:eq(' + n + ') input').prop('checked', true);
480                     return false;
481                 }
482             } else {    // column n is not visible
483                 $(g.t).find('tr').each(function () {
484                     $(this).find('th.draggable:eq(' + n + '),' +
485                                  'td:eq(' + (g.actionSpan + n) + ')')
486                         .show();
487                 });
488                 g.colVisib[n] = 1;
489                 $(g.cList).find('.lDiv div:eq(' + n + ') input').prop('checked', true);
490             }
491             return true;
492         },
494         /**
495          * This must be called if toggleCol() returns is true.
496          *
497          * This function is separated from toggleCol because, sometimes, we want to toggle
498          * some columns together at one time and do just one adjustment after it, e.g. in showAllColumns().
499          */
500         afterToggleCol: function () {
501             // some adjustments after hiding column
502             g.reposRsz();
503             g.reposDrop();
504             g.sendColPrefs();
506             // check visible first row headers count
507             g.visibleHeadersCount = $(g.t).find('tr:first th.draggable:visible').length;
508             g.refreshRestoreButton();
509         },
511         /**
512          * Show columns' visibility list.
513          *
514          * @param obj The drop down arrow of column visibility list
515          */
516         showColList: function (obj) {
517             // only show when not resizing or reordering
518             if (!g.colRsz && !g.colReorder) {
519                 var pos = $(obj).position();
520                 // check if the list position is too right
521                 if (pos.left + $(g.cList).outerWidth(true) > $(document).width()) {
522                     pos.left = $(document).width() - $(g.cList).outerWidth(true);
523                 }
524                 $(g.cList).css({
525                     left: pos.left,
526                     top: pos.top + $(obj).outerHeight(true)
527                 })
528                     .show();
529                 $(obj).addClass('coldrop-hover');
530             }
531         },
533         /**
534          * Hide columns' visibility list.
535          */
536         hideColList: function () {
537             $(g.cList).hide();
538             $(g.cDrop).find('.coldrop-hover').removeClass('coldrop-hover');
539         },
541         /**
542          * Reposition the column visibility drop-down arrow.
543          */
544         reposDrop: function () {
545             var $th = $(t).find('th:not(.draggable)');
546             for (var i = 0; i < $th.length; i++) {
547                 var $cd = $(g.cDrop).find('div:eq(' + i + ')');   // column drop-down arrow
548                 var pos = $($th[i]).position();
549                 $cd.css({
550                     left: pos.left + $($th[i]).width() - $cd.width(),
551                     top: pos.top
552                 });
553             }
554         },
556         /**
557          * Show all hidden columns.
558          */
559         showAllColumns: function () {
560             for (var i = 0; i < g.colVisib.length; i++) {
561                 if (!g.colVisib[i]) {
562                     g.toggleCol(i);
563                 }
564             }
565             g.afterToggleCol();
566         },
568         /**
569          * Show edit cell, if it can be shown
570          *
571          * @param cell <td> element to be edited
572          */
573         showEditCell: function (cell) {
574             if ($(cell).is('.grid_edit') &&
575                 !g.colRsz && !g.colReorder) {
576                 if (!g.isCellEditActive) {
577                     var $cell = $(cell);
579                     if ('string' === $cell.attr('data-type') ||
580                         'blob' === $cell.attr('data-type') ||
581                         'json' === $cell.attr('data-type')
582                     ) {
583                         g.cEdit = g.cEditTextarea;
584                     } else {
585                         g.cEdit = g.cEditStd;
586                     }
588                     // remove all edit area and hide it
589                     $(g.cEdit).find('.edit_area').empty().hide();
590                     // reposition the cEdit element
591                     $(g.cEdit).css({
592                         top: $cell.position().top,
593                         left: $cell.position().left
594                     })
595                         .show()
596                         .find('.edit_box')
597                         .css({
598                             width: $cell.outerWidth(),
599                             height: $cell.outerHeight()
600                         });
601                     // fill the cell edit with text from <td>
602                     var value = PMA_getCellValue(cell);
603                     if ($cell.attr('data-type') === 'json') {
604                         value = JSON.stringify(JSON.parse(value), null, 4);
605                     }
606                     $(g.cEdit).find('.edit_box').val(value);
608                     g.currentEditCell = cell;
609                     $(g.cEdit).find('.edit_box').focus();
610                     moveCursorToEnd($(g.cEdit).find('.edit_box'));
611                     $(g.cEdit).find('*').prop('disabled', false);
612                 }
613             }
615             function moveCursorToEnd (input) {
616                 var originalValue = input.val();
617                 var originallength = originalValue.length;
618                 input.val('');
619                 input.blur().focus().val(originalValue);
620                 input[0].setSelectionRange(originallength, originallength);
621             }
622         },
624         /**
625          * Remove edit cell and the edit area, if it is shown.
626          *
627          * @param force Optional, force to hide edit cell without saving edited field.
628          * @param data  Optional, data from the POST AJAX request to save the edited field
629          *              or just specify "true", if we want to replace the edited field with the new value.
630          * @param field Optional, the edited <td>. If not specified, the function will
631          *              use currently edited <td> from g.currentEditCell.
632          * @param field Optional, this object contains a boolean named move (true, if called from move* functions)
633          *              and a <td> to which the grid_edit should move
634          */
635         hideEditCell: function (force, data, field, options) {
636             if (g.isCellEditActive && !force) {
637                 // cell is being edited, save or post the edited data
638                 if (options !== undefined) {
639                     g.saveOrPostEditedCell(options);
640                 } else {
641                     g.saveOrPostEditedCell();
642                 }
643                 return;
644             }
646             // cancel any previous request
647             if (g.lastXHR !== null) {
648                 g.lastXHR.abort();
649                 g.lastXHR = null;
650             }
652             if (data) {
653                 if (g.currentEditCell) {    // save value of currently edited cell
654                     // replace current edited field with the new value
655                     var $this_field = $(g.currentEditCell);
656                     var is_null = $this_field.data('value') === null;
657                     if (is_null) {
658                         $this_field.find('span').html('NULL');
659                         $this_field.addClass('null');
660                     } else {
661                         $this_field.removeClass('null');
662                         var value = data.isNeedToRecheck
663                             ? data.truncatableFieldValue
664                             : $this_field.data('value');
666                         // Truncates the text.
667                         $this_field.removeClass('truncated');
668                         if (PMA_commonParams.get('pftext') === 'P' && value.length > g.maxTruncatedLen) {
669                             $this_field.addClass('truncated');
670                             value = value.substring(0, g.maxTruncatedLen) + '...';
671                         }
673                         // Add <br> before carriage return.
674                         new_html = escapeHtml(value);
675                         new_html = new_html.replace(/\n/g, '<br>\n');
677                         // remove decimal places if column type not supported
678                         if (($this_field.attr('data-decimals') === 0) && ($this_field.attr('data-type').indexOf('time') !== -1)) {
679                             new_html = new_html.substring(0, new_html.indexOf('.'));
680                         }
682                         // remove addtional decimal places
683                         if (($this_field.attr('data-decimals') > 0) && ($this_field.attr('data-type').indexOf('time') !== -1)) {
684                             new_html = new_html.substring(0, new_html.length - (6 - $this_field.attr('data-decimals')));
685                         }
687                         var selector = 'span';
688                         if ($this_field.hasClass('hex') && $this_field.find('a').length) {
689                             selector = 'a';
690                         }
692                         // Updates the code keeping highlighting (if any).
693                         var $target = $this_field.find(selector);
694                         if (!PMA_updateCode($target, new_html, value)) {
695                             $target.html(new_html);
696                         }
697                     }
698                     if ($this_field.is('.bit')) {
699                         $this_field.find('span').text($this_field.data('value'));
700                     }
701                 }
702                 if (data.transformations !== undefined) {
703                     $.each(data.transformations, function (cell_index, value) {
704                         var $this_field = $(g.t).find('.to_be_saved:eq(' + cell_index + ')');
705                         $this_field.find('span').html(value);
706                     });
707                 }
708                 if (data.relations !== undefined) {
709                     $.each(data.relations, function (cell_index, value) {
710                         var $this_field = $(g.t).find('.to_be_saved:eq(' + cell_index + ')');
711                         $this_field.find('span').html(value);
712                     });
713                 }
715                 // refresh the grid
716                 g.reposRsz();
717                 g.reposDrop();
718             }
720             // hide the cell editing area
721             $(g.cEdit).hide();
722             $(g.cEdit).find('.edit_box').blur();
723             g.isCellEditActive = false;
724             g.currentEditCell = null;
725             // destroy datepicker in edit area, if exist
726             var $dp = $(g.cEdit).find('.hasDatepicker');
727             if ($dp.length > 0) {
728                 $(document).bind('mousedown', $.datepicker._checkExternalClick);
729                 $dp.datepicker('destroy');
730                 // change the cursor in edit box back to normal
731                 // (the cursor become a hand pointer when we add datepicker)
732                 $(g.cEdit).find('.edit_box').css('cursor', 'inherit');
733             }
734         },
736         /**
737          * Show drop-down edit area when edit cell is focused.
738          */
739         showEditArea: function () {
740             if (!g.isCellEditActive) {   // make sure the edit area has not been shown
741                 g.isCellEditActive = true;
742                 g.isEditCellTextEditable = false;
743                 /**
744                  * @var $td current edited cell
745                  */
746                 var $td = $(g.currentEditCell);
747                 /**
748                  * @var $editArea the editing area
749                  */
750                 var $editArea = $(g.cEdit).find('.edit_area');
751                 /**
752                  * @var where_clause WHERE clause for the edited cell
753                  */
754                 var where_clause = $td.parent('tr').find('.where_clause').val();
755                 /**
756                  * @var field_name  String containing the name of this field.
757                  * @see getFieldName()
758                  */
759                 var field_name = getFieldName($(t), $td);
760                 /**
761                  * @var relation_curr_value String current value of the field (for fields that are foreign keyed).
762                  */
763                 var relation_curr_value = $td.text();
764                 /**
765                  * @var relation_key_or_display_column String relational key if in 'Relational display column' mode,
766                  * relational display column if in 'Relational key' mode (for fields that are foreign keyed).
767                  */
768                 var relation_key_or_display_column = $td.find('a').attr('title');
769                 /**
770                  * @var curr_value String current value of the field (for fields that are of type enum or set).
771                  */
772                 var curr_value = $td.find('span').text();
774                 // empty all edit area, then rebuild it based on $td classes
775                 $editArea.empty();
777                 // remember this instead of testing more than once
778                 var is_null = $td.is('.null');
780                 // add goto link, if this cell contains a link
781                 if ($td.find('a').length > 0) {
782                     var gotoLink = document.createElement('div');
783                     gotoLink.className = 'goto_link';
784                     $(gotoLink).append(g.gotoLinkText + ' ').append($td.find('a').clone());
785                     $editArea.append(gotoLink);
786                 }
788                 g.wasEditedCellNull = false;
789                 if ($td.is(':not(.not_null)')) {
790                     // append a null checkbox
791                     $editArea.append('<div class="null_div"><label>Null:<input type="checkbox"></label></div>');
793                     var $checkbox = $editArea.find('.null_div input');
794                     // check if current <td> is NULL
795                     if (is_null) {
796                         $checkbox.prop('checked', true);
797                         g.wasEditedCellNull = true;
798                     }
800                     // if the select/editor is changed un-check the 'checkbox_null_<field_name>_<row_index>'.
801                     if ($td.is('.enum, .set')) {
802                         $editArea.on('change', 'select', function () {
803                             $checkbox.prop('checked', false);
804                         });
805                     } else if ($td.is('.relation')) {
806                         $editArea.on('change', 'select', function () {
807                             $checkbox.prop('checked', false);
808                         });
809                         $editArea.on('click', '.browse_foreign', function () {
810                             $checkbox.prop('checked', false);
811                         });
812                     } else {
813                         $(g.cEdit).on('keypress change paste', '.edit_box', function () {
814                             $checkbox.prop('checked', false);
815                         });
816                         // Capture ctrl+v (on IE and Chrome)
817                         $(g.cEdit).on('keydown', '.edit_box', function (e) {
818                             if (e.ctrlKey && e.which === 86) {
819                                 $checkbox.prop('checked', false);
820                             }
821                         });
822                         $editArea.on('keydown', 'textarea', function () {
823                             $checkbox.prop('checked', false);
824                         });
825                     }
827                     // if null checkbox is clicked empty the corresponding select/editor.
828                     $checkbox.click(function () {
829                         if ($td.is('.enum')) {
830                             $editArea.find('select').val('');
831                         } else if ($td.is('.set')) {
832                             $editArea.find('select').find('option').each(function () {
833                                 var $option = $(this);
834                                 $option.prop('selected', false);
835                             });
836                         } else if ($td.is('.relation')) {
837                             // if the dropdown is there to select the foreign value
838                             if ($editArea.find('select').length > 0) {
839                                 $editArea.find('select').val('');
840                             }
841                         } else {
842                             $editArea.find('textarea').val('');
843                         }
844                         $(g.cEdit).find('.edit_box').val('');
845                     });
846                 }
848                 // reset the position of the edit_area div after closing datetime picker
849                 $(g.cEdit).find('.edit_area').css({ 'top' :'0','position':'' });
851                 if ($td.is('.relation')) {
852                     // handle relations
853                     $editArea.addClass('edit_area_loading');
855                     // initialize the original data
856                     $td.data('original_data', null);
858                     /**
859                      * @var post_params Object containing parameters for the POST request
860                      */
861                     var post_params = {
862                         'ajax_request' : true,
863                         'get_relational_values' : true,
864                         'server' : g.server,
865                         'db' : g.db,
866                         'table' : g.table,
867                         'column' : field_name,
868                         'curr_value' : relation_curr_value,
869                         'relation_key_or_display_column' : relation_key_or_display_column
870                     };
872                     g.lastXHR = $.post('sql.php', post_params, function (data) {
873                         g.lastXHR = null;
874                         $editArea.removeClass('edit_area_loading');
875                         if ($(data.dropdown).is('select')) {
876                             // save original_data
877                             var value = $(data.dropdown).val();
878                             $td.data('original_data', value);
879                             // update the text input field, in case where the "Relational display column" is checked
880                             $(g.cEdit).find('.edit_box').val(value);
881                         }
883                         $editArea.append(data.dropdown);
884                         $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
886                         // for 'Browse foreign values' options,
887                         // hide the value next to 'Browse foreign values' link
888                         $editArea.find('span.curr_value').hide();
889                         // handle update for new values selected from new window
890                         $editArea.find('span.curr_value').change(function () {
891                             $(g.cEdit).find('.edit_box').val($(this).text());
892                         });
893                     }); // end $.post()
895                     $editArea.show();
896                     $editArea.on('change', 'select', function () {
897                         $(g.cEdit).find('.edit_box').val($(this).val());
898                     });
899                     g.isEditCellTextEditable = true;
900                 } else if ($td.is('.enum')) {
901                     // handle enum fields
902                     $editArea.addClass('edit_area_loading');
904                     /**
905                      * @var post_params Object containing parameters for the POST request
906                      */
907                     var post_params = {
908                         'ajax_request' : true,
909                         'get_enum_values' : true,
910                         'server' : g.server,
911                         'db' : g.db,
912                         'table' : g.table,
913                         'column' : field_name,
914                         'curr_value' : curr_value
915                     };
916                     g.lastXHR = $.post('sql.php', post_params, function (data) {
917                         g.lastXHR = null;
918                         $editArea.removeClass('edit_area_loading');
919                         $editArea.append(data.dropdown);
920                         $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
921                     }); // end $.post()
923                     $editArea.show();
924                     $editArea.on('change', 'select', function () {
925                         $(g.cEdit).find('.edit_box').val($(this).val());
926                     });
927                 } else if ($td.is('.set')) {
928                     // handle set fields
929                     $editArea.addClass('edit_area_loading');
931                     /**
932                      * @var post_params Object containing parameters for the POST request
933                      */
934                     var post_params = {
935                         'ajax_request' : true,
936                         'get_set_values' : true,
937                         'server' : g.server,
938                         'db' : g.db,
939                         'table' : g.table,
940                         'column' : field_name,
941                         'curr_value' : curr_value
942                     };
944                     // if the data is truncated, get the full data
945                     if ($td.is('.truncated')) {
946                         post_params.get_full_values = true;
947                         post_params.where_clause = where_clause;
948                     }
950                     g.lastXHR = $.post('sql.php', post_params, function (data) {
951                         g.lastXHR = null;
952                         $editArea.removeClass('edit_area_loading');
953                         $editArea.append(data.select);
954                         $td.data('original_data', $(data.select).val().join());
955                         $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
956                     }); // end $.post()
958                     $editArea.show();
959                     $editArea.on('change', 'select', function () {
960                         $(g.cEdit).find('.edit_box').val($(this).val());
961                     });
962                 } else if ($td.is('.truncated, .transformed')) {
963                     if ($td.is('.to_be_saved')) {   // cell has been edited
964                         var value = $td.data('value');
965                         $(g.cEdit).find('.edit_box').val(value);
966                         $editArea.append('<textarea></textarea>');
967                         $editArea.find('textarea').val(value);
968                         $editArea
969                             .on('keyup', 'textarea', function () {
970                                 $(g.cEdit).find('.edit_box').val($(this).val());
971                             });
972                         $(g.cEdit).on('keyup', '.edit_box', function () {
973                             $editArea.find('textarea').val($(this).val());
974                         });
975                         $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
976                     } else {
977                         // handle truncated/transformed values values
978                         $editArea.addClass('edit_area_loading');
980                         // initialize the original data
981                         $td.data('original_data', null);
983                         /**
984                          * @var sql_query   String containing the SQL query used to retrieve value of truncated/transformed data
985                          */
986                         var sql_query = 'SELECT `' + field_name + '` FROM `' + g.table + '` WHERE ' + where_clause;
988                         // Make the Ajax call and get the data, wrap it and insert it
989                         g.lastXHR = $.post('sql.php', {
990                             'server' : g.server,
991                             'db' : g.db,
992                             'ajax_request' : true,
993                             'sql_query' : sql_query,
994                             'grid_edit' : true
995                         }, function (data) {
996                             g.lastXHR = null;
997                             $editArea.removeClass('edit_area_loading');
998                             if (typeof data !== 'undefined' && data.success === true) {
999                                 $td.data('original_data', data.value);
1000                                 $(g.cEdit).find('.edit_box').val(data.value);
1001                                 $editArea.append('<textarea rows="15"></textarea>');
1002                                 $editArea.find('textarea').val(data.value);
1003                                 $editArea.on('keyup', 'textarea', function () {
1004                                     $(g.cEdit).find('.edit_box').val($(this).val());
1005                                 });
1006                                 $(g.cEdit).on('keyup', '.edit_box', function () {
1007                                     $editArea.find('textarea').val($(this).val());
1008                                 });
1009                                 $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
1010                                 $editArea.show();
1011                             } else {
1012                                 PMA_ajaxShowMessage(data.error, false);
1013                             }
1014                         }); // end $.post()
1015                     }
1016                     g.isEditCellTextEditable = true;
1017                 } else if ($td.is('.timefield, .datefield, .datetimefield, .timestampfield')) {
1018                     var $input_field = $(g.cEdit).find('.edit_box');
1020                     // remember current datetime value in $input_field, if it is not null
1021                     var datetime_value = !is_null ? $input_field.val() : '';
1023                     var showMillisec = false;
1024                     var showMicrosec = false;
1025                     var timeFormat = 'HH:mm:ss';
1026                     // check for decimal places of seconds
1027                     if (($td.attr('data-decimals') > 0) && ($td.attr('data-type').indexOf('time') !== -1)) {
1028                         if (datetime_value && datetime_value.indexOf('.') === false) {
1029                             datetime_value += '.';
1030                         }
1031                         if ($td.attr('data-decimals') > 3) {
1032                             showMillisec = true;
1033                             showMicrosec = true;
1034                             timeFormat = 'HH:mm:ss.lc';
1036                             if (datetime_value) {
1037                                 datetime_value += '000000';
1038                                 var datetime_value = datetime_value.substring(0, datetime_value.indexOf('.') + 7);
1039                                 $input_field.val(datetime_value);
1040                             }
1041                         } else {
1042                             showMillisec = true;
1043                             timeFormat = 'HH:mm:ss.l';
1045                             if (datetime_value) {
1046                                 datetime_value += '000';
1047                                 var datetime_value = datetime_value.substring(0, datetime_value.indexOf('.') + 4);
1048                                 $input_field.val(datetime_value);
1049                             }
1050                         }
1051                     }
1053                     // add datetime picker
1054                     PMA_addDatepicker($input_field, $td.attr('data-type'), {
1055                         showMillisec: showMillisec,
1056                         showMicrosec: showMicrosec,
1057                         timeFormat: timeFormat
1058                     });
1060                     $input_field.on('keyup', function (e) {
1061                         if (e.which === 13) {
1062                             // post on pressing "Enter"
1063                             e.preventDefault();
1064                             e.stopPropagation();
1065                             g.saveOrPostEditedCell();
1066                         } else if (e.which === 27) {
1067                         } else {
1068                             toggleDatepickerIfInvalid($td, $input_field);
1069                         }
1070                     });
1072                     $input_field.datepicker('show');
1073                     toggleDatepickerIfInvalid($td, $input_field);
1075                     // unbind the mousedown event to prevent the problem of
1076                     // datepicker getting closed, needs to be checked for any
1077                     // change in names when updating
1078                     $(document).off('mousedown', $.datepicker._checkExternalClick);
1080                     // move ui-datepicker-div inside cEdit div
1081                     var datepicker_div = $('#ui-datepicker-div');
1082                     datepicker_div.css({ 'top': 0, 'left': 0, 'position': 'relative' });
1083                     $(g.cEdit).append(datepicker_div);
1085                     // cancel any click on the datepicker element
1086                     $editArea.find('> *').click(function (e) {
1087                         e.stopPropagation();
1088                     });
1090                     g.isEditCellTextEditable = true;
1091                 } else {
1092                     g.isEditCellTextEditable = true;
1093                     // only append edit area hint if there is a null checkbox
1094                     if ($editArea.children().length > 0) {
1095                         $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
1096                     }
1097                 }
1098                 if ($editArea.children().length > 0) {
1099                     $editArea.show();
1100                 }
1101             }
1102         },
1104         /**
1105          * Post the content of edited cell.
1106          *
1107          * @param field Optional, this object contains a boolean named move (true, if called from move* functions)
1108          *              and a <td> to which the grid_edit should move
1109          */
1110         postEditedCell: function (options) {
1111             if (g.isSaving) {
1112                 return;
1113             }
1114             g.isSaving = true;
1115             /**
1116              * @var relation_fields Array containing the name/value pairs of relational fields
1117              */
1118             var relation_fields = {};
1119             /**
1120              * @var relational_display string 'K' if relational key, 'D' if relational display column
1121              */
1122             var relational_display = $(g.o).find('input[name=relational_display]:checked').val();
1123             /**
1124              * @var transform_fields    Array containing the name/value pairs for transformed fields
1125              */
1126             var transform_fields = {};
1127             /**
1128              * @var transformation_fields   Boolean, if there are any transformed fields in the edited cells
1129              */
1130             var transformation_fields = false;
1131             /**
1132              * @var full_sql_query String containing the complete SQL query to update this table
1133              */
1134             var full_sql_query = '';
1135             /**
1136              * @var rel_fields_list  String, url encoded representation of {@link relations_fields}
1137              */
1138             var rel_fields_list = '';
1139             /**
1140              * @var transform_fields_list  String, url encoded representation of {@link transform_fields}
1141              */
1142             var transform_fields_list = '';
1143             /**
1144              * @var where_clause Array containing where clause for updated fields
1145              */
1146             var full_where_clause = [];
1147             /**
1148              * @var is_unique   Boolean, whether the rows in this table is unique or not
1149              */
1150             var is_unique = $(g.t).find('td.edit_row_anchor').is('.nonunique') ? 0 : 1;
1151             /**
1152              * multi edit variables
1153              */
1154             var me_fields_name = [];
1155             var me_fields_type = [];
1156             var me_fields = [];
1157             var me_fields_null = [];
1159             // alert user if edited table is not unique
1160             if (!is_unique) {
1161                 alert(g.alertNonUnique);
1162             }
1164             // loop each edited row
1165             $(g.t).find('td.to_be_saved').parents('tr').each(function () {
1166                 var $tr = $(this);
1167                 var where_clause = $tr.find('.where_clause').val();
1168                 if (typeof where_clause === 'undefined') {
1169                     where_clause = '';
1170                 }
1171                 full_where_clause.push(where_clause);
1172                 var condition_array = JSON.parse($tr.find('.condition_array').val());
1174                 /**
1175                  * multi edit variables, for current row
1176                  * @TODO array indices are still not correct, they should be md5 of field's name
1177                  */
1178                 var fields_name = [];
1179                 var fields_type = [];
1180                 var fields = [];
1181                 var fields_null = [];
1183                 // loop each edited cell in a row
1184                 $tr.find('.to_be_saved').each(function () {
1185                     /**
1186                      * @var $this_field    Object referring to the td that is being edited
1187                      */
1188                     var $this_field = $(this);
1190                     /**
1191                      * @var field_name  String containing the name of this field.
1192                      * @see getFieldName()
1193                      */
1194                     var field_name = getFieldName($(g.t), $this_field);
1196                     /**
1197                      * @var this_field_params   Array temporary storage for the name/value of current field
1198                      */
1199                     var this_field_params = {};
1201                     if ($this_field.is('.transformed')) {
1202                         transformation_fields =  true;
1203                     }
1204                     this_field_params[field_name] = $this_field.data('value');
1206                     /**
1207                      * @var is_null String capturing whether 'checkbox_null_<field_name>_<row_index>' is checked.
1208                      */
1209                     var is_null = this_field_params[field_name] === null;
1211                     fields_name.push(field_name);
1213                     if (is_null) {
1214                         fields_null.push('on');
1215                         fields.push('');
1216                     } else {
1217                         if ($this_field.is('.bit')) {
1218                             fields_type.push('bit');
1219                         } else if ($this_field.hasClass('hex')) {
1220                             fields_type.push('hex');
1221                         }
1222                         fields_null.push('');
1223                         // Convert \n to \r\n to be consistent with form submitted value.
1224                         // The internal browser representation has to be just \n
1225                         // while form submitted value \r\n, see specification:
1226                         // https://www.w3.org/TR/html5/forms.html#the-textarea-element
1227                         fields.push($this_field.data('value').replace(/\n/g, '\r\n'));
1229                         var cell_index = $this_field.index('.to_be_saved');
1230                         if ($this_field.is(':not(.relation, .enum, .set, .bit)')) {
1231                             if ($this_field.is('.transformed')) {
1232                                 transform_fields[cell_index] = {};
1233                                 $.extend(transform_fields[cell_index], this_field_params);
1234                             }
1235                         } else if ($this_field.is('.relation')) {
1236                             relation_fields[cell_index] = {};
1237                             $.extend(relation_fields[cell_index], this_field_params);
1238                         }
1239                     }
1240                     // check if edited field appears in WHERE clause
1241                     if (where_clause.indexOf(PMA_urlencode(field_name)) > -1) {
1242                         var field_str = '`' + g.table + '`.' + '`' + field_name + '`';
1243                         for (var field in condition_array) {
1244                             if (field.indexOf(field_str) > -1) {
1245                                 condition_array[field] = is_null ? 'IS NULL' : '= \'' + this_field_params[field_name].replace(/'/g, '\'\'') + '\'';
1246                                 break;
1247                             }
1248                         }
1249                     }
1250                 }); // end of loop for every edited cells in a row
1252                 // save new_clause
1253                 var new_clause = '';
1254                 for (var field in condition_array) {
1255                     new_clause += field + ' ' + condition_array[field] + ' AND ';
1256                 }
1257                 new_clause = new_clause.substring(0, new_clause.length - 5); // remove the last AND
1258                 $tr.data('new_clause', new_clause);
1259                 // save condition_array
1260                 $tr.find('.condition_array').val(JSON.stringify(condition_array));
1262                 me_fields_name.push(fields_name);
1263                 me_fields_type.push(fields_type);
1264                 me_fields.push(fields);
1265                 me_fields_null.push(fields_null);
1266             }); // end of loop for every edited rows
1268             rel_fields_list = $.param(relation_fields);
1269             transform_fields_list = $.param(transform_fields);
1271             // Make the Ajax post after setting all parameters
1272             /**
1273              * @var post_params Object containing parameters for the POST request
1274              */
1275             var post_params = { 'ajax_request' : true,
1276                 'sql_query' : full_sql_query,
1277                 'server' : g.server,
1278                 'db' : g.db,
1279                 'table' : g.table,
1280                 'clause_is_unique' : is_unique,
1281                 'where_clause' : full_where_clause,
1282                 'fields[multi_edit]' : me_fields,
1283                 'fields_name[multi_edit]' : me_fields_name,
1284                 'fields_type[multi_edit]' : me_fields_type,
1285                 'fields_null[multi_edit]' : me_fields_null,
1286                 'rel_fields_list' : rel_fields_list,
1287                 'do_transformations' : transformation_fields,
1288                 'transform_fields_list' : transform_fields_list,
1289                 'relational_display' : relational_display,
1290                 'goto' : 'sql.php',
1291                 'submit_type' : 'save'
1292             };
1294             if (!g.saveCellsAtOnce) {
1295                 $(g.cEdit).find('*').prop('disabled', true);
1296                 $(g.cEdit).find('.edit_box').addClass('edit_box_posting');
1297             } else {
1298                 $(g.o).find('div.save_edited').addClass('saving_edited_data')
1299                     .find('input').prop('disabled', true);    // disable the save button
1300             }
1302             $.ajax({
1303                 type: 'POST',
1304                 url: 'tbl_replace.php',
1305                 data: post_params,
1306                 success:
1307                     function (data) {
1308                         g.isSaving = false;
1309                         if (!g.saveCellsAtOnce) {
1310                             $(g.cEdit).find('*').prop('disabled', false);
1311                             $(g.cEdit).find('.edit_box').removeClass('edit_box_posting');
1312                         } else {
1313                             $(g.o).find('div.save_edited').removeClass('saving_edited_data')
1314                                 .find('input').prop('disabled', false);  // enable the save button back
1315                         }
1316                         if (typeof data !== 'undefined' && data.success === true) {
1317                             if (typeof options === 'undefined' || ! options.move) {
1318                                 PMA_ajaxShowMessage(data.message);
1319                             }
1321                             // update where_clause related data in each edited row
1322                             $(g.t).find('td.to_be_saved').parents('tr').each(function () {
1323                                 var new_clause = $(this).data('new_clause');
1324                                 var $where_clause = $(this).find('.where_clause');
1325                                 var old_clause = $where_clause.val();
1326                                 var decoded_old_clause = old_clause;
1327                                 var decoded_new_clause = new_clause;
1329                                 $where_clause.val(new_clause);
1330                                 // update Edit, Copy, and Delete links also
1331                                 $(this).find('a').each(function () {
1332                                     $(this).attr('href', $(this).attr('href').replace(old_clause, new_clause));
1333                                     // update delete confirmation in Delete link
1334                                     if ($(this).attr('href').indexOf('DELETE') > -1) {
1335                                         $(this).removeAttr('onclick')
1336                                             .off('click')
1337                                             .on('click', function () {
1338                                                 return confirmLink(this, 'DELETE FROM `' + g.db + '`.`' + g.table + '` WHERE ' +
1339                                                        decoded_new_clause + (is_unique ? '' : ' LIMIT 1'));
1340                                             });
1341                                     }
1342                                 });
1343                                 // update the multi edit checkboxes
1344                                 $(this).find('input[type=checkbox]').each(function () {
1345                                     var $checkbox = $(this);
1346                                     var checkbox_name = $checkbox.attr('name');
1347                                     var checkbox_value = $checkbox.val();
1349                                     $checkbox.attr('name', checkbox_name.replace(old_clause, new_clause));
1350                                     $checkbox.val(checkbox_value.replace(decoded_old_clause, decoded_new_clause));
1351                                 });
1352                             });
1353                             // update the display of executed SQL query command
1354                             if (typeof data.sql_query !== 'undefined') {
1355                                 // extract query box
1356                                 var $result_query = $($.parseHTML(data.sql_query));
1357                                 var sqlOuter = $result_query.find('.sqlOuter').wrap('<p>').parent().html();
1358                                 var tools = $result_query.find('.tools').wrap('<p>').parent().html();
1359                                 // sqlOuter and tools will not be present if 'Show SQL queries' configuration is off
1360                                 if (typeof sqlOuter !== 'undefined' && typeof tools !== 'undefined') {
1361                                     $(g.o).find('.result_query:not(:last)').remove();
1362                                     var $existing_query = $(g.o).find('.result_query');
1363                                     // If two query box exists update query in second else add a second box
1364                                     if ($existing_query.find('div.sqlOuter').length > 1) {
1365                                         $existing_query.children(':nth-child(4)').remove();
1366                                         $existing_query.children(':nth-child(4)').remove();
1367                                         $existing_query.append(sqlOuter + tools);
1368                                     } else {
1369                                         $existing_query.append(sqlOuter + tools);
1370                                     }
1371                                     PMA_highlightSQL($existing_query);
1372                                 }
1373                             }
1374                             // hide and/or update the successfully saved cells
1375                             g.hideEditCell(true, data);
1377                             // remove the "Save edited cells" button
1378                             $(g.o).find('div.save_edited').hide();
1379                             // update saved fields
1380                             $(g.t).find('.to_be_saved')
1381                                 .removeClass('to_be_saved')
1382                                 .data('value', null)
1383                                 .data('original_data', null);
1385                             g.isCellEdited = false;
1386                         } else {
1387                             PMA_ajaxShowMessage(data.error, false);
1388                             if (!g.saveCellsAtOnce) {
1389                                 $(g.t).find('.to_be_saved')
1390                                     .removeClass('to_be_saved');
1391                             }
1392                         }
1393                     }
1394             }).done(function () {
1395                 if (options !== undefined && options.move) {
1396                     g.showEditCell(options.cell);
1397                 }
1398             }); // end $.ajax()
1399         },
1401         /**
1402          * Save edited cell, so it can be posted later.
1403          */
1404         saveEditedCell: function () {
1405             /**
1406              * @var $this_field    Object referring to the td that is being edited
1407              */
1408             var $this_field = $(g.currentEditCell);
1409             var $test_element = ''; // to test the presence of a element
1411             var need_to_post = false;
1413             /**
1414              * @var field_name  String containing the name of this field.
1415              * @see getFieldName()
1416              */
1417             var field_name = getFieldName($(g.t), $this_field);
1419             /**
1420              * @var this_field_params   Array temporary storage for the name/value of current field
1421              */
1422             var this_field_params = {};
1424             /**
1425              * @var is_null String capturing whether 'checkbox_null_<field_name>_<row_index>' is checked.
1426              */
1427             var is_null = $(g.cEdit).find('input:checkbox').is(':checked');
1429             if ($(g.cEdit).find('.edit_area').is('.edit_area_loading')) {
1430                 // the edit area is still loading (retrieving cell data), no need to post
1431                 need_to_post = false;
1432             } else if (is_null) {
1433                 if (!g.wasEditedCellNull) {
1434                     this_field_params[field_name] = null;
1435                     need_to_post = true;
1436                 }
1437             } else {
1438                 if ($this_field.is('.bit')) {
1439                     this_field_params[field_name] = $(g.cEdit).find('.edit_box').val();
1440                 } else if ($this_field.is('.set')) {
1441                     $test_element = $(g.cEdit).find('select');
1442                     this_field_params[field_name] = $test_element.map(function () {
1443                         return $(this).val();
1444                     }).get().join(',');
1445                 } else if ($this_field.is('.relation, .enum')) {
1446                     // for relation and enumeration, take the results from edit box value,
1447                     // because selected value from drop-down, new window or multiple
1448                     // selection list will always be updated to the edit box
1449                     this_field_params[field_name] = $(g.cEdit).find('.edit_box').val();
1450                 } else if ($this_field.hasClass('hex')) {
1451                     if ($(g.cEdit).find('.edit_box').val().match(/^(0x)?[a-f0-9]*$/i) !== null) {
1452                         this_field_params[field_name] = $(g.cEdit).find('.edit_box').val();
1453                     } else {
1454                         var hexError = '<div class="error">' + PMA_messages.strEnterValidHex + '</div>';
1455                         PMA_ajaxShowMessage(hexError, false);
1456                         this_field_params[field_name] = PMA_getCellValue(g.currentEditCell);
1457                     }
1458                 } else {
1459                     this_field_params[field_name] = $(g.cEdit).find('.edit_box').val();
1460                 }
1461                 if (g.wasEditedCellNull || this_field_params[field_name] !== PMA_getCellValue(g.currentEditCell)) {
1462                     need_to_post = true;
1463                 }
1464             }
1466             if (need_to_post) {
1467                 $(g.currentEditCell).addClass('to_be_saved')
1468                     .data('value', this_field_params[field_name]);
1469                 if (g.saveCellsAtOnce) {
1470                     $(g.o).find('div.save_edited').show();
1471                 }
1472                 g.isCellEdited = true;
1473             }
1475             return need_to_post;
1476         },
1478         /**
1479          * Save or post currently edited cell, depending on the "saveCellsAtOnce" configuration.
1480          *
1481          * @param field Optional, this object contains a boolean named move (true, if called from move* functions)
1482          *              and a <td> to which the grid_edit should move
1483          */
1484         saveOrPostEditedCell: function (options) {
1485             var saved = g.saveEditedCell();
1486             // Check if $cfg['SaveCellsAtOnce'] is false
1487             if (!g.saveCellsAtOnce) {
1488                 // Check if need_to_post is true
1489                 if (saved) {
1490                     // Check if this function called from 'move' functions
1491                     if (options !== undefined && options.move) {
1492                         g.postEditedCell(options);
1493                     } else {
1494                         g.postEditedCell();
1495                     }
1496                 // need_to_post is false
1497                 } else {
1498                     // Check if this function called from 'move' functions
1499                     if (options !== undefined && options.move) {
1500                         g.hideEditCell(true);
1501                         g.showEditCell(options.cell);
1502                     // NOT called from 'move' functions
1503                     } else {
1504                         g.hideEditCell(true);
1505                     }
1506                 }
1507             // $cfg['SaveCellsAtOnce'] is true
1508             } else {
1509                 // If need_to_post
1510                 if (saved) {
1511                     // If this function called from 'move' functions
1512                     if (options !== undefined && options.move) {
1513                         g.hideEditCell(true, true, false, options);
1514                         g.showEditCell(options.cell);
1515                     // NOT called from 'move' functions
1516                     } else {
1517                         g.hideEditCell(true, true);
1518                     }
1519                 } else {
1520                     // If this function called from 'move' functions
1521                     if (options !== undefined && options.move) {
1522                         g.hideEditCell(true, false, false, options);
1523                         g.showEditCell(options.cell);
1524                     // NOT called from 'move' functions
1525                     } else {
1526                         g.hideEditCell(true);
1527                     }
1528                 }
1529             }
1530         },
1532         /**
1533          * Initialize column resize feature.
1534          */
1535         initColResize: function () {
1536             // create column resizer div
1537             g.cRsz = document.createElement('div');
1538             g.cRsz.className = 'cRsz';
1540             // get data columns in the first row of the table
1541             var $firstRowCols = $(g.t).find('tr:first th.draggable');
1543             // create column borders
1544             $firstRowCols.each(function () {
1545                 var cb = document.createElement('div'); // column border
1546                 $(cb).addClass('colborder')
1547                     .mousedown(function (e) {
1548                         g.dragStartRsz(e, this);
1549                     });
1550                 $(g.cRsz).append(cb);
1551             });
1552             g.reposRsz();
1554             // attach to global div
1555             $(g.gDiv).prepend(g.cRsz);
1556         },
1558         /**
1559          * Initialize column reordering feature.
1560          */
1561         initColReorder: function () {
1562             g.cCpy = document.createElement('div');     // column copy, to store copy of dragged column header
1563             g.cPointer = document.createElement('div'); // column pointer, used when reordering column
1565             // adjust g.cCpy
1566             g.cCpy.className = 'cCpy';
1567             $(g.cCpy).hide();
1569             // adjust g.cPointer
1570             g.cPointer.className = 'cPointer';
1571             $(g.cPointer).css('visibility', 'hidden');  // set visibility to hidden instead of calling hide() to force browsers to cache the image in cPointer class
1573             // assign column reordering hint
1574             g.reorderHint = PMA_messages.strColOrderHint;
1576             // get data columns in the first row of the table
1577             var $firstRowCols = $(g.t).find('tr:first th.draggable');
1579             // initialize column order
1580             $col_order = $(g.o).find('.col_order');   // check if column order is passed from PHP
1581             if ($col_order.length > 0) {
1582                 g.colOrder = $col_order.val().split(',');
1583                 for (var i = 0; i < g.colOrder.length; i++) {
1584                     g.colOrder[i] = parseInt(g.colOrder[i], 10);
1585                 }
1586             } else {
1587                 g.colOrder = [];
1588                 for (var i = 0; i < $firstRowCols.length; i++) {
1589                     g.colOrder.push(i);
1590                 }
1591             }
1593             // register events
1594             $(g.t).find('th.draggable')
1595                 .mousedown(function (e) {
1596                     $(g.o).addClass('turnOffSelect');
1597                     if (g.visibleHeadersCount > 1) {
1598                         g.dragStartReorder(e, this);
1599                     }
1600                 })
1601                 .mouseenter(function () {
1602                     if (g.visibleHeadersCount > 1) {
1603                         $(this).css('cursor', 'move');
1604                     } else {
1605                         $(this).css('cursor', 'inherit');
1606                     }
1607                 })
1608                 .mouseleave(function () {
1609                     g.showReorderHint = false;
1610                     $(this).tooltip('option', {
1611                         content: g.updateHint()
1612                     });
1613                 })
1614                 .dblclick(function (e) {
1615                     e.preventDefault();
1616                     $('<div/>')
1617                         .prop('title', PMA_messages.strColNameCopyTitle)
1618                         .addClass('modal-copy')
1619                         .text(PMA_messages.strColNameCopyText)
1620                         .append(
1621                             $('<input/>')
1622                                 .prop('readonly', true)
1623                                 .val($(this).data('column'))
1624                         )
1625                         .dialog({
1626                             resizable: false,
1627                             modal: true
1628                         })
1629                         .find('input').focus().select();
1630                 });
1631             $(g.t).find('th.draggable a')
1632                 .dblclick(function (e) {
1633                     e.stopPropagation();
1634                 });
1635             // restore column order when the restore button is clicked
1636             $(g.o).find('div.restore_column').click(function () {
1637                 g.restoreColOrder();
1638             });
1640             // attach to global div
1641             $(g.gDiv).append(g.cPointer);
1642             $(g.gDiv).append(g.cCpy);
1644             // prevent default "dragstart" event when dragging a link
1645             $(g.t).find('th a').on('dragstart', function () {
1646                 return false;
1647             });
1649             // refresh the restore column button state
1650             g.refreshRestoreButton();
1651         },
1653         /**
1654          * Initialize column visibility feature.
1655          */
1656         initColVisib: function () {
1657             g.cDrop = document.createElement('div');    // column drop-down arrows
1658             g.cList = document.createElement('div');    // column visibility list
1660             // adjust g.cDrop
1661             g.cDrop.className = 'cDrop';
1663             // adjust g.cList
1664             g.cList.className = 'cList';
1665             $(g.cList).hide();
1667             // assign column visibility related hints
1668             g.showAllColText = PMA_messages.strShowAllCol;
1670             // get data columns in the first row of the table
1671             var $firstRowCols = $(g.t).find('tr:first th.draggable');
1673             var i;
1674             // initialize column visibility
1675             var $col_visib = $(g.o).find('.col_visib');   // check if column visibility is passed from PHP
1676             if ($col_visib.length > 0) {
1677                 g.colVisib = $col_visib.val().split(',');
1678                 for (i = 0; i < g.colVisib.length; i++) {
1679                     g.colVisib[i] = parseInt(g.colVisib[i], 10);
1680                 }
1681             } else {
1682                 g.colVisib = [];
1683                 for (i = 0; i < $firstRowCols.length; i++) {
1684                     g.colVisib.push(1);
1685                 }
1686             }
1688             // make sure we have more than one column
1689             if ($firstRowCols.length > 1) {
1690                 var $colVisibTh = $(g.t).find('th:not(.draggable)');
1691                 PMA_tooltip(
1692                     $colVisibTh,
1693                     'th',
1694                     PMA_messages.strColVisibHint
1695                 );
1697                 // create column visibility drop-down arrow(s)
1698                 $colVisibTh.each(function () {
1699                     var $th = $(this);
1700                     var cd = document.createElement('div'); // column drop-down arrow
1701                     var pos = $th.position();
1702                     $(cd).addClass('coldrop')
1703                         .click(function () {
1704                             if (g.cList.style.display === 'none') {
1705                                 g.showColList(this);
1706                             } else {
1707                                 g.hideColList();
1708                             }
1709                         });
1710                     $(g.cDrop).append(cd);
1711                 });
1713                 // add column visibility control
1714                 g.cList.innerHTML = '<div class="lDiv"></div>';
1715                 var $listDiv = $(g.cList).find('div');
1717                 var tempClick = function () {
1718                     if (g.toggleCol($(this).index())) {
1719                         g.afterToggleCol();
1720                     }
1721                 };
1723                 for (i = 0; i < $firstRowCols.length; i++) {
1724                     var currHeader = $firstRowCols[i];
1725                     var listElmt = document.createElement('div');
1726                     $(listElmt).text($(currHeader).text())
1727                         .prepend('<input type="checkbox" ' + (g.colVisib[i] ? 'checked="checked" ' : '') + '/>');
1728                     $listDiv.append(listElmt);
1729                     // add event on click
1730                     $(listElmt).click(tempClick);
1731                 }
1732                 // add "show all column" button
1733                 var showAll = document.createElement('div');
1734                 $(showAll).addClass('showAllColBtn')
1735                     .text(g.showAllColText);
1736                 $(g.cList).append(showAll);
1737                 $(showAll).click(function () {
1738                     g.showAllColumns();
1739                 });
1740                 // prepend "show all column" button at top if the list is too long
1741                 if ($firstRowCols.length > 10) {
1742                     var clone = showAll.cloneNode(true);
1743                     $(g.cList).prepend(clone);
1744                     $(clone).click(function () {
1745                         g.showAllColumns();
1746                     });
1747                 }
1748             }
1750             // hide column visibility list if we move outside the list
1751             $(g.t).find('td, th.draggable').mouseenter(function () {
1752                 g.hideColList();
1753             });
1755             // attach to global div
1756             $(g.gDiv).append(g.cDrop);
1757             $(g.gDiv).append(g.cList);
1759             // some adjustment
1760             g.reposDrop();
1761         },
1763         /**
1764          * Move currently Editing Cell to Up
1765          */
1766         moveUp: function (e) {
1767             e.preventDefault();
1768             var $this_field = $(g.currentEditCell);
1769             var field_name = getFieldName($(g.t), $this_field);
1771             var where_clause = $this_field.parents('tr').first().find('.where_clause').val();
1772             if (typeof where_clause === 'undefined') {
1773                 where_clause = '';
1774             }
1775             var found = false;
1776             var $found_row;
1777             var $prev_row;
1778             var j = 0;
1780             $this_field.parents('tr').first().parents('tbody').children().each(function () {
1781                 if ($(this).find('.where_clause').val() === where_clause) {
1782                     found = true;
1783                     $found_row = $(this);
1784                 }
1785                 if (!found) {
1786                     $prev_row = $(this);
1787                 }
1788             });
1790             var new_cell;
1792             if (found && $prev_row) {
1793                 $prev_row.children('td').each(function () {
1794                     if (getFieldName($(g.t), $(this)) === field_name) {
1795                         new_cell = this;
1796                     }
1797                 });
1798             }
1800             if (new_cell) {
1801                 g.hideEditCell(false, false, false, { move : true, cell : new_cell });
1802             }
1803         },
1805         /**
1806          * Move currently Editing Cell to Down
1807          */
1808         moveDown: function (e) {
1809             e.preventDefault();
1811             var $this_field = $(g.currentEditCell);
1812             var field_name = getFieldName($(g.t), $this_field);
1814             var where_clause = $this_field.parents('tr').first().find('.where_clause').val();
1815             if (typeof where_clause === 'undefined') {
1816                 where_clause = '';
1817             }
1818             var found = false;
1819             var $found_row;
1820             var $next_row;
1821             var j = 0;
1822             var next_row_found = false;
1823             $this_field.parents('tr').first().parents('tbody').children().each(function () {
1824                 if ($(this).find('.where_clause').val() === where_clause) {
1825                     found = true;
1826                     $found_row = $(this);
1827                 }
1828                 if (found) {
1829                     if (j >= 1 && ! next_row_found) {
1830                         $next_row = $(this);
1831                         next_row_found = true;
1832                     } else {
1833                         j++;
1834                     }
1835                 }
1836             });
1838             var new_cell;
1839             if (found && $next_row) {
1840                 $next_row.children('td').each(function () {
1841                     if (getFieldName($(g.t), $(this)) === field_name) {
1842                         new_cell = this;
1843                     }
1844                 });
1845             }
1847             if (new_cell) {
1848                 g.hideEditCell(false, false, false, { move : true, cell : new_cell });
1849             }
1850         },
1852         /**
1853          * Move currently Editing Cell to Left
1854          */
1855         moveLeft: function (e) {
1856             e.preventDefault();
1858             var $this_field = $(g.currentEditCell);
1859             var field_name = getFieldName($(g.t), $this_field);
1861             var where_clause = $this_field.parents('tr').first().find('.where_clause').val();
1862             if (typeof where_clause === 'undefined') {
1863                 where_clause = '';
1864             }
1865             var found = false;
1866             var $found_row;
1867             var j = 0;
1868             $this_field.parents('tr').first().parents('tbody').children().each(function () {
1869                 if ($(this).find('.where_clause').val() === where_clause) {
1870                     found = true;
1871                     $found_row = $(this);
1872                 }
1873             });
1875             var left_cell;
1876             var cell_found = false;
1877             if (found) {
1878                 $found_row.children('td.grid_edit').each(function () {
1879                     if (getFieldName($(g.t), $(this)) === field_name) {
1880                         cell_found = true;
1881                     }
1882                     if (!cell_found) {
1883                         left_cell = this;
1884                     }
1885                 });
1886             }
1888             if (left_cell) {
1889                 g.hideEditCell(false, false, false, { move : true, cell : left_cell });
1890             }
1891         },
1893         /**
1894          * Move currently Editing Cell to Right
1895          */
1896         moveRight: function (e) {
1897             e.preventDefault();
1899             var $this_field = $(g.currentEditCell);
1900             var field_name = getFieldName($(g.t), $this_field);
1902             var where_clause = $this_field.parents('tr').first().find('.where_clause').val();
1903             if (typeof where_clause === 'undefined') {
1904                 where_clause = '';
1905             }
1906             var found = false;
1907             var $found_row;
1908             var j = 0;
1909             $this_field.parents('tr').first().parents('tbody').children().each(function () {
1910                 if ($(this).find('.where_clause').val() === where_clause) {
1911                     found = true;
1912                     $found_row = $(this);
1913                 }
1914             });
1916             var right_cell;
1917             var cell_found = false;
1918             var next_cell_found = false;
1919             if (found) {
1920                 $found_row.children('td.grid_edit').each(function () {
1921                     if (getFieldName($(g.t), $(this)) === field_name) {
1922                         cell_found = true;
1923                     }
1924                     if (cell_found) {
1925                         if (j >= 1 && ! next_cell_found) {
1926                             right_cell = this;
1927                             next_cell_found = true;
1928                         } else {
1929                             j++;
1930                         }
1931                     }
1932                 });
1933             }
1935             if (right_cell) {
1936                 g.hideEditCell(false, false, false, { move : true, cell : right_cell });
1937             }
1938         },
1940         /**
1941          * Initialize grid editing feature.
1942          */
1943         initGridEdit: function () {
1944             function startGridEditing (e, cell) {
1945                 if (g.isCellEditActive) {
1946                     g.saveOrPostEditedCell();
1947                 } else {
1948                     g.showEditCell(cell);
1949                 }
1950                 e.stopPropagation();
1951             }
1953             function handleCtrlNavigation (e) {
1954                 if ((e.ctrlKey && e.which === 38) || (e.altKey && e.which === 38)) {
1955                     g.moveUp(e);
1956                 } else if ((e.ctrlKey && e.which === 40)  || (e.altKey && e.which === 40)) {
1957                     g.moveDown(e);
1958                 } else if ((e.ctrlKey && e.which === 37) || (e.altKey && e.which === 37)) {
1959                     g.moveLeft(e);
1960                 } else if ((e.ctrlKey && e.which === 39)  || (e.altKey && e.which === 39)) {
1961                     g.moveRight(e);
1962                 }
1963             }
1965             // create cell edit wrapper element
1966             g.cEditStd = document.createElement('div');
1967             g.cEdit = g.cEditStd;
1968             g.cEditTextarea = document.createElement('div');
1970             // adjust g.cEditStd
1971             g.cEditStd.className = 'cEdit';
1972             $(g.cEditStd).html('<input class="edit_box" rows="1" /><div class="edit_area" />');
1973             $(g.cEditStd).hide();
1975             // adjust g.cEdit
1976             g.cEditTextarea.className = 'cEdit';
1977             $(g.cEditTextarea).html('<textarea class="edit_box" rows="1" ></textarea><div class="edit_area" />');
1978             $(g.cEditTextarea).hide();
1980             // assign cell editing hint
1981             g.cellEditHint = PMA_messages.strCellEditHint;
1982             g.saveCellWarning = PMA_messages.strSaveCellWarning;
1983             g.alertNonUnique = PMA_messages.strAlertNonUnique;
1984             g.gotoLinkText = PMA_messages.strGoToLink;
1986             // initialize cell editing configuration
1987             g.saveCellsAtOnce = $(g.o).find('.save_cells_at_once').val();
1988             g.maxTruncatedLen = PMA_commonParams.get('LimitChars');
1990             // register events
1991             $(g.t).find('td.data.click1')
1992                 .click(function (e) {
1993                     startGridEditing(e, this);
1994                     // prevent default action when clicking on "link" in a table
1995                     if ($(e.target).is('.grid_edit a')) {
1996                         e.preventDefault();
1997                     }
1998                 });
2000             $(g.t).find('td.data.click2')
2001                 .click(function (e) {
2002                     var $cell = $(this);
2003                     // In the case of relational link, We want single click on the link
2004                     // to goto the link and double click to start grid-editing.
2005                     var $link = $(e.target);
2006                     if ($link.is('.grid_edit.relation a')) {
2007                         e.preventDefault();
2008                         // get the click count and increase
2009                         var clicks = $cell.data('clicks');
2010                         clicks = (typeof clicks === 'undefined') ? 1 : clicks + 1;
2012                         if (clicks === 1) {
2013                             // if there are no previous clicks,
2014                             // start the single click timer
2015                             var timer = setTimeout(function () {
2016                                 // temporarily remove ajax class so the page loader will not handle it,
2017                                 // submit and then add it back
2018                                 $link.removeClass('ajax');
2019                                 AJAX.requestHandler.call($link[0]);
2020                                 $link.addClass('ajax');
2021                                 $cell.data('clicks', 0);
2022                             }, 700);
2023                             $cell.data('clicks', clicks);
2024                             $cell.data('timer', timer);
2025                         } else {
2026                             // this is a double click, cancel the single click timer
2027                             // and make the click count 0
2028                             clearTimeout($cell.data('timer'));
2029                             $cell.data('clicks', 0);
2030                             // start grid-editing
2031                             startGridEditing(e, this);
2032                         }
2033                     }
2034                 })
2035                 .dblclick(function (e) {
2036                     if ($(e.target).is('.grid_edit a')) {
2037                         e.preventDefault();
2038                     } else {
2039                         startGridEditing(e, this);
2040                     }
2041                 });
2043             $(g.cEditStd).on('keydown', 'input.edit_box, select', handleCtrlNavigation);
2045             $(g.cEditStd).find('.edit_box').focus(function () {
2046                 g.showEditArea();
2047             });
2048             $(g.cEditStd).on('keydown', '.edit_box, select', function (e) {
2049                 if (e.which === 13) {
2050                     // post on pressing "Enter"
2051                     e.preventDefault();
2052                     g.saveOrPostEditedCell();
2053                 }
2054             });
2055             $(g.cEditStd).keydown(function (e) {
2056                 if (!g.isEditCellTextEditable) {
2057                     // prevent text editing
2058                     e.preventDefault();
2059                 }
2060             });
2062             $(g.cEditTextarea).on('keydown', 'textarea.edit_box, select', handleCtrlNavigation);
2064             $(g.cEditTextarea).find('.edit_box').focus(function () {
2065                 g.showEditArea();
2066             });
2067             $(g.cEditTextarea).on('keydown', '.edit_box, select', function (e) {
2068                 if (e.which === 13 && !e.shiftKey) {
2069                     // post on pressing "Enter"
2070                     e.preventDefault();
2071                     g.saveOrPostEditedCell();
2072                 }
2073             });
2074             $(g.cEditTextarea).keydown(function (e) {
2075                 if (!g.isEditCellTextEditable) {
2076                     // prevent text editing
2077                     e.preventDefault();
2078                 }
2079             });
2080             $('html').click(function (e) {
2081                 // hide edit cell if the click is not fromDat edit area
2082                 if ($(e.target).parents().index($(g.cEdit)) === -1 &&
2083                     !$(e.target).parents('.ui-datepicker-header').length &&
2084                     !$('.browse_foreign_modal.ui-dialog:visible').length &&
2085                     !$(e.target).closest('.dismissable').length
2086                 ) {
2087                     g.hideEditCell();
2088                 }
2089             }).keydown(function (e) {
2090                 if (e.which === 27 && g.isCellEditActive) {
2091                     // cancel on pressing "Esc"
2092                     g.hideEditCell(true);
2093                 }
2094             });
2095             $(g.o).find('div.save_edited').click(function () {
2096                 g.hideEditCell();
2097                 g.postEditedCell();
2098             });
2099             $(window).on('beforeunload', function () {
2100                 if (g.isCellEdited) {
2101                     return g.saveCellWarning;
2102                 }
2103             });
2105             // attach to global div
2106             $(g.gDiv).append(g.cEditStd);
2107             $(g.gDiv).append(g.cEditTextarea);
2109             // add hint for grid editing feature when hovering "Edit" link in each table row
2110             if (PMA_messages.strGridEditFeatureHint !== undefined) {
2111                 PMA_tooltip(
2112                     $(g.t).find('.edit_row_anchor a'),
2113                     'a',
2114                     PMA_messages.strGridEditFeatureHint
2115                 );
2116             }
2117         }
2118     };
2120     /** ****************
2121      * Initialize grid
2122      ******************/
2124     // wrap all truncated data cells with span indicating the original length
2125     // todo update the original length after a grid edit
2126     $(t).find('td.data.truncated:not(:has(span))')
2127         .wrapInner(function () {
2128             return '<span title="' + PMA_messages.strOriginalLength + ' ' +
2129                 $(this).data('originallength') + '"></span>';
2130         });
2132     // wrap remaining cells, except actions cell, with span
2133     $(t).find('th, td:not(:has(span))')
2134         .wrapInner('<span />');
2136     // create grid elements
2137     g.gDiv = document.createElement('div');     // create global div
2139     // initialize the table variable
2140     g.t = t;
2142     // enclosing .sqlqueryresults div
2143     g.o = $(t).parents('.sqlqueryresults');
2145     // get data columns in the first row of the table
2146     var $firstRowCols = $(t).find('tr:first th.draggable');
2148     // initialize visible headers count
2149     g.visibleHeadersCount = $firstRowCols.filter(':visible').length;
2151     // assign first column (actions) span
2152     if (! $(t).find('tr:first th:first').hasClass('draggable')) {  // action header exist
2153         g.actionSpan = $(t).find('tr:first th:first').prop('colspan');
2154     } else {
2155         g.actionSpan = 0;
2156     }
2158     // assign table create time
2159     // table_create_time will only available if we are in "Browse" tab
2160     g.tableCreateTime = $(g.o).find('.table_create_time').val();
2162     // assign the hints
2163     g.sortHint = PMA_messages.strSortHint;
2164     g.strMultiSortHint = PMA_messages.strMultiSortHint;
2165     g.markHint = PMA_messages.strColMarkHint;
2166     g.copyHint = PMA_messages.strColNameCopyHint;
2168     // assign common hidden inputs
2169     var $common_hidden_inputs = $(g.o).find('div.common_hidden_inputs');
2170     g.server = $common_hidden_inputs.find('input[name=server]').val();
2171     g.db = $common_hidden_inputs.find('input[name=db]').val();
2172     g.table = $common_hidden_inputs.find('input[name=table]').val();
2174     // add table class
2175     $(t).addClass('pma_table');
2177     // add relative position to global div so that resize handlers are correctly positioned
2178     $(g.gDiv).css('position', 'relative');
2180     // link the global div
2181     $(t).before(g.gDiv);
2182     $(g.gDiv).append(t);
2184     // FEATURES
2185     enableResize    = enableResize === undefined ? true : enableResize;
2186     enableReorder   = enableReorder === undefined ? true : enableReorder;
2187     enableVisib     = enableVisib === undefined ? true : enableVisib;
2188     enableGridEdit  = enableGridEdit === undefined ? true : enableGridEdit;
2189     if (enableResize) {
2190         g.initColResize();
2191     }
2192     // disable reordering for result from EXPLAIN or SHOW syntax, which do not have a table navigation panel
2193     if (enableReorder &&
2194         $(g.o).find('table.navigation').length > 0) {
2195         g.initColReorder();
2196     }
2197     if (enableVisib) {
2198         g.initColVisib();
2199     }
2200     // make sure we have the ajax class
2201     if (enableGridEdit &&
2202         $(t).is('.ajax')) {
2203         g.initGridEdit();
2204     }
2206     // create tooltip for each <th> with draggable class
2207     PMA_tooltip(
2208         $(t).find('th.draggable'),
2209         'th',
2210         g.updateHint()
2211     );
2213     // register events for hint tooltip (anchors inside draggable th)
2214     $(t).find('th.draggable a')
2215         .mouseenter(function () {
2216             g.showSortHint = true;
2217             g.showMultiSortHint = true;
2218             $(t).find('th.draggable').tooltip('option', {
2219                 content: g.updateHint()
2220             });
2221         })
2222         .mouseleave(function () {
2223             g.showSortHint = false;
2224             g.showMultiSortHint = false;
2225             $(t).find('th.draggable').tooltip('option', {
2226                 content: g.updateHint()
2227             });
2228         });
2230     // register events for dragging-related feature
2231     if (enableResize || enableReorder) {
2232         $(document).mousemove(function (e) {
2233             g.dragMove(e);
2234         });
2235         $(document).mouseup(function (e) {
2236             $(g.o).removeClass('turnOffSelect');
2237             g.dragEnd(e);
2238         });
2239     }
2241     // some adjustment
2242     $(t).removeClass('data');
2243     $(g.gDiv).addClass('data');
2247  * jQuery plugin to cancel selection in HTML code.
2248  */
2249 (function ($) {
2250     $.fn.noSelect = function (p) { // no select plugin by Paulo P.Marinas
2251         var prevent = (p === null) ? true : p;
2252         var is_msie = navigator.userAgent.indexOf('MSIE') > -1 || !!window.navigator.userAgent.match(/Trident.*rv\:11\./);
2253         var is_firefox = navigator.userAgent.indexOf('Firefox') > -1;
2254         var is_safari = navigator.userAgent.indexOf('Safari') > -1;
2255         var is_opera = navigator.userAgent.indexOf('Presto') > -1;
2256         if (prevent) {
2257             return this.each(function () {
2258                 if (is_msie || is_safari) {
2259                     $(this).on('selectstart', false);
2260                 } else if (is_firefox) {
2261                     $(this).css('MozUserSelect', 'none');
2262                     $('body').trigger('focus');
2263                 } else if (is_opera) {
2264                     $(this).on('mousedown', false);
2265                 } else {
2266                     $(this).attr('unselectable', 'on');
2267                 }
2268             });
2269         } else {
2270             return this.each(function () {
2271                 if (is_msie || is_safari) {
2272                     $(this).off('selectstart');
2273                 } else if (is_firefox) {
2274                     $(this).css('MozUserSelect', 'inherit');
2275                 } else if (is_opera) {
2276                     $(this).off('mousedown');
2277                 } else {
2278                     $(this).removeAttr('unselectable');
2279                 }
2280             });
2281         }
2282     }; // end noSelect
2283 }(jQuery));