Translated using Weblate (Polish)
[phpmyadmin.git] / js / makegrid.js
blob9099f01bdb496ad982c0c2dad467271af7a4b235
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             } else if (g.colReorder) {
198                 // shift columns
199                 if (g.colReorder.newn != g.colReorder.n) {
200                     g.shiftCol(g.colReorder.n, g.colReorder.newn);
201                     // assign new position
202                     var objPos = $(g.colReorder.obj).position();
203                     g.colReorder.objTop = objPos.top;
204                     g.colReorder.objLeft = objPos.left;
205                     g.colReorder.n = g.colReorder.newn;
206                     // send request to server to remember the column order
207                     if (g.tableCreateTime) {
208                         g.sendColPrefs();
209                     }
210                     g.refreshRestoreButton();
211                 }
213                 // animate new column position
214                 $(g.cCpy).stop(true, true)
215                     .animate({
216                         top: g.colReorder.objTop,
217                         left: g.colReorder.objLeft
218                     }, 'fast')
219                     .fadeOut();
220                 $(g.cPointer).css('visibility', 'hidden');
222                 g.colReorder = false;
223             }
224             $(document.body).css('cursor', 'inherit').noSelect(false);
225         },
227         /**
228          * Resize column n to new width "nw"
229          *
230          * @param n zero-based column index
231          * @param nw new width of the column in pixel
232          */
233         resize: function (n, nw) {
234             $(g.t).find('tr').each(function () {
235                 $(this).find('th.draggable:visible:eq(' + n + ') span,' +
236                              'td:visible:eq(' + (g.actionSpan + n) + ') span')
237                        .css('width', nw);
238             });
239         },
241         /**
242          * Reposition column resize bars.
243          */
244         reposRsz: function () {
245             $(g.cRsz).find('div').hide();
246             var $firstRowCols = $(g.t).find('tr:first th.draggable:visible');
247             var $resizeHandles = $(g.cRsz).find('div').removeClass('condition');
248             $('table.pma_table').find('thead th:first').removeClass('before-condition');
249             for (var n = 0, l = $firstRowCols.length; n < l; n++) {
250                 var $col = $($firstRowCols[n]);
251                 $($resizeHandles[n]).css('left', $col.position().left + $col.outerWidth(true))
252                    .show();
253                 if ($col.hasClass('condition')) {
254                     $($resizeHandles[n]).addClass('condition');
255                     if (n > 0) {
256                         $($resizeHandles[n - 1]).addClass('condition');
257                     }
258                 }
259             }
260             if ($($resizeHandles[0]).hasClass('condition')) {
261                 $('table.pma_table').find('thead th:first').addClass('before-condition');
262             }
263             $(g.cRsz).css('height', $(g.t).height());
264         },
266         /**
267          * Shift column from index oldn to newn.
268          *
269          * @param oldn old zero-based column index
270          * @param newn new zero-based column index
271          */
272         shiftCol: function (oldn, newn) {
273             $(g.t).find('tr').each(function () {
274                 if (newn < oldn) {
275                     $(this).find('th.draggable:eq(' + newn + '),' +
276                                  'td:eq(' + (g.actionSpan + newn) + ')')
277                            .before($(this).find('th.draggable:eq(' + oldn + '),' +
278                                                 'td:eq(' + (g.actionSpan + oldn) + ')'));
279                 } else {
280                     $(this).find('th.draggable:eq(' + newn + '),' +
281                                  'td:eq(' + (g.actionSpan + newn) + ')')
282                            .after($(this).find('th.draggable:eq(' + oldn + '),' +
283                                                'td:eq(' + (g.actionSpan + oldn) + ')'));
284                 }
285             });
286             // reposition the column resize bars
287             g.reposRsz();
289             // adjust the column visibility list
290             if (newn < oldn) {
291                 $(g.cList).find('.lDiv div:eq(' + newn + ')')
292                           .before($(g.cList).find('.lDiv div:eq(' + oldn + ')'));
293             } else {
294                 $(g.cList).find('.lDiv div:eq(' + newn + ')')
295                           .after($(g.cList).find('.lDiv div:eq(' + oldn + ')'));
296             }
297             // adjust the colOrder
298             var tmp = g.colOrder[oldn];
299             g.colOrder.splice(oldn, 1);
300             g.colOrder.splice(newn, 0, tmp);
301             // adjust the colVisib
302             if (g.colVisib.length > 0) {
303                 tmp = g.colVisib[oldn];
304                 g.colVisib.splice(oldn, 1);
305                 g.colVisib.splice(newn, 0, tmp);
306             }
307         },
309         /**
310          * Find currently hovered table column's header (excluding actions column).
311          *
312          * @param e event
313          * @return the hovered column's th object or undefined if no hovered column found.
314          */
315         getHoveredCol: function (e) {
316             var hoveredCol;
317             $headers = $(g.t).find('th.draggable:visible');
318             $headers.each(function () {
319                 var left = $(this).offset().left;
320                 var right = left + $(this).outerWidth();
321                 if (left <= e.pageX && e.pageX <= right) {
322                     hoveredCol = this;
323                 }
324             });
325             return hoveredCol;
326         },
328         /**
329          * Get a zero-based index from a <th class="draggable"> tag in a table.
330          *
331          * @param obj table header <th> object
332          * @return zero-based index of the specified table header in the set of table headers (visible or not)
333          */
334         getHeaderIdx: function (obj) {
335             return $(obj).parents('tr').find('th.draggable').index(obj);
336         },
338         /**
339          * Reposition the columns back to normal order.
340          */
341         restoreColOrder: function () {
342             // use insertion sort, since we already have shiftCol function
343             for (var i = 1; i < g.colOrder.length; i++) {
344                 var x = g.colOrder[i];
345                 var j = i - 1;
346                 while (j >= 0 && x < g.colOrder[j]) {
347                     j--;
348                 }
349                 if (j != i - 1) {
350                     g.shiftCol(i, j + 1);
351                 }
352             }
353             if (g.tableCreateTime) {
354                 // send request to server to remember the column order
355                 g.sendColPrefs();
356             }
357             g.refreshRestoreButton();
358         },
360         /**
361          * Send column preferences (column order and visibility) to the server.
362          */
363         sendColPrefs: function () {
364             if ($(g.t).is('.ajax')) {   // only send preferences if ajax class
365                 var post_params = {
366                     ajax_request: true,
367                     db: g.db,
368                     table: g.table,
369                     token: g.token,
370                     server: g.server,
371                     set_col_prefs: true,
372                     table_create_time: g.tableCreateTime
373                 };
374                 if (g.colOrder.length > 0) {
375                     $.extend(post_params, {col_order: g.colOrder.toString()});
376                 }
377                 if (g.colVisib.length > 0) {
378                     $.extend(post_params, {col_visib: g.colVisib.toString()});
379                 }
380                 $.post('sql.php', post_params, function (data) {
381                     if (data.success !== true) {
382                         var $temp_div = $(document.createElement('div'));
383                         $temp_div.html(data.error);
384                         $temp_div.addClass("error");
385                         PMA_ajaxShowMessage($temp_div, false);
386                     }
387                 });
388             }
389         },
391         /**
392          * Refresh restore button state.
393          * Make restore button disabled if the table is similar with initial state.
394          */
395         refreshRestoreButton: function () {
396             // check if table state is as initial state
397             var isInitial = true;
398             for (var i = 0; i < g.colOrder.length; i++) {
399                 if (g.colOrder[i] != i) {
400                     isInitial = false;
401                     break;
402                 }
403             }
404             // check if only one visible column left
405             var isOneColumn = g.visibleHeadersCount == 1;
406             // enable or disable restore button
407             if (isInitial || isOneColumn) {
408                 $('div.restore_column').hide();
409             } else {
410                 $('div.restore_column').show();
411             }
412         },
414         /**
415          * Update current hint using the boolean values (showReorderHint, showSortHint, etc.).
416          *
417          */
418         updateHint: function () {
419             var text = '';
420             if (!g.colRsz && !g.colReorder) {     // if not resizing or dragging
421                 if (g.visibleHeadersCount > 1) {
422                     g.showReorderHint = true;
423                 }
424                 if ($(t).find('th.marker').length > 0) {
425                     g.showMarkHint = true;
426                 }
428                 if (g.showReorderHint && g.reorderHint) {
429                     text += g.reorderHint;
430                 }
431                 if (g.showSortHint && g.sortHint) {
432                     text += text.length > 0 ? '<br />' : '';
433                     text += g.sortHint;
434                 }
435                 if (g.showMarkHint && g.markHint &&
436                     !g.showSortHint      // we do not show mark hint, when sort hint is shown
437                 ) {
438                     text += text.length > 0 ? '<br />' : '';
439                     text += g.markHint;
440                     text += text.length > 0 ? '<br />' : '';
441                     text += g.copyHint;
442                 }
443             }
444             return text;
445         },
447         /**
448          * Toggle column's visibility.
449          * After calling this function and it returns true, afterToggleCol() must be called.
450          *
451          * @return boolean True if the column is toggled successfully.
452          */
453         toggleCol: function (n) {
454             if (g.colVisib[n]) {
455                 // can hide if more than one column is visible
456                 if (g.visibleHeadersCount > 1) {
457                     $(g.t).find('tr').each(function () {
458                         $(this).find('th.draggable:eq(' + n + '),' +
459                                      'td:eq(' + (g.actionSpan + n) + ')')
460                                .hide();
461                     });
462                     g.colVisib[n] = 0;
463                     $(g.cList).find('.lDiv div:eq(' + n + ') input').prop('checked', false);
464                 } else {
465                     // cannot hide, force the checkbox to stay checked
466                     $(g.cList).find('.lDiv div:eq(' + n + ') input').prop('checked', true);
467                     return false;
468                 }
469             } else {    // column n is not visible
470                 $(g.t).find('tr').each(function () {
471                     $(this).find('th.draggable:eq(' + n + '),' +
472                                  'td:eq(' + (g.actionSpan + n) + ')')
473                            .show();
474                 });
475                 g.colVisib[n] = 1;
476                 $(g.cList).find('.lDiv div:eq(' + n + ') input').prop('checked', true);
477             }
478             return true;
479         },
481         /**
482          * This must be called if toggleCol() returns is true.
483          *
484          * This function is separated from toggleCol because, sometimes, we want to toggle
485          * some columns together at one time and do just one adjustment after it, e.g. in showAllColumns().
486          */
487         afterToggleCol: function () {
488             // some adjustments after hiding column
489             g.reposRsz();
490             g.reposDrop();
491             g.sendColPrefs();
493             // check visible first row headers count
494             g.visibleHeadersCount = $(g.t).find('tr:first th.draggable:visible').length;
495             g.refreshRestoreButton();
496         },
498         /**
499          * Show columns' visibility list.
500          *
501          * @param obj The drop down arrow of column visibility list
502          */
503         showColList: function (obj) {
504             // only show when not resizing or reordering
505             if (!g.colRsz && !g.colReorder) {
506                 var pos = $(obj).position();
507                 // check if the list position is too right
508                 if (pos.left + $(g.cList).outerWidth(true) > $(document).width()) {
509                     pos.left = $(document).width() - $(g.cList).outerWidth(true);
510                 }
511                 $(g.cList).css({
512                         left: pos.left,
513                         top: pos.top + $(obj).outerHeight(true)
514                     })
515                     .show();
516                 $(obj).addClass('coldrop-hover');
517             }
518         },
520         /**
521          * Hide columns' visibility list.
522          */
523         hideColList: function () {
524             $(g.cList).hide();
525             $(g.cDrop).find('.coldrop-hover').removeClass('coldrop-hover');
526         },
528         /**
529          * Reposition the column visibility drop-down arrow.
530          */
531         reposDrop: function () {
532             var $th = $(t).find('th:not(.draggable)');
533             for (var i = 0; i < $th.length; i++) {
534                 var $cd = $(g.cDrop).find('div:eq(' + i + ')');   // column drop-down arrow
535                 var pos = $($th[i]).position();
536                 $cd.css({
537                         left: pos.left + $($th[i]).width() - $cd.width(),
538                         top: pos.top
539                     });
540             }
541         },
543         /**
544          * Show all hidden columns.
545          */
546         showAllColumns: function () {
547             for (var i = 0; i < g.colVisib.length; i++) {
548                 if (!g.colVisib[i]) {
549                     g.toggleCol(i);
550                 }
551             }
552             g.afterToggleCol();
553         },
555         /**
556          * Show edit cell, if it can be shown
557          *
558          * @param cell <td> element to be edited
559          */
560         showEditCell: function (cell) {
561             if ($(cell).is('.grid_edit') &&
562                 !g.colRsz && !g.colReorder)
563             {
564                 if (!g.isCellEditActive) {
565                     var $cell = $(cell);
566                     // remove all edit area and hide it
567                     $(g.cEdit).find('.edit_area').empty().hide();
568                     // reposition the cEdit element
569                     $(g.cEdit).css({
570                             top: $cell.position().top,
571                             left: $cell.position().left
572                         })
573                         .show()
574                         .find('.edit_box')
575                         .css({
576                             width: $cell.outerWidth(),
577                             height: $cell.outerHeight()
578                         });
579                     // fill the cell edit with text from <td>
580                     var value = PMA_getCellValue(cell);
581                     $(g.cEdit).find('.edit_box').val(value);
583                     g.currentEditCell = cell;
584                     $(g.cEdit).find('.edit_box').focus();
585                     $(g.cEdit).find('*').removeProp('disabled');
586                 }
587             }
588         },
590         /**
591          * Remove edit cell and the edit area, if it is shown.
592          *
593          * @param force Optional, force to hide edit cell without saving edited field.
594          * @param data  Optional, data from the POST AJAX request to save the edited field
595          *              or just specify "true", if we want to replace the edited field with the new value.
596          * @param field Optional, the edited <td>. If not specified, the function will
597          *              use currently edited <td> from g.currentEditCell.
598          */
599         hideEditCell: function (force, data, field) {
600             if (g.isCellEditActive && !force) {
601                 // cell is being edited, save or post the edited data
602                 g.saveOrPostEditedCell();
603                 return;
604             }
606             // cancel any previous request
607             if (g.lastXHR !== null) {
608                 g.lastXHR.abort();
609                 g.lastXHR = null;
610             }
612             if (data) {
613                 if (g.currentEditCell) {    // save value of currently edited cell
614                     // replace current edited field with the new value
615                     var $this_field = $(g.currentEditCell);
616                     var is_null = $this_field.data('value') === null;
617                     if (is_null) {
618                         $this_field.find('span').html('NULL');
619                         $this_field.addClass('null');
620                     } else {
621                         $this_field.removeClass('null');
622                         var new_html = data.isNeedToRecheck
623                             ? data.truncatableFieldValue
624                             : $this_field.data('value');
625                         if ($this_field.is('.truncated')) {
626                             if (new_html.length > g.maxTruncatedLen) {
627                                 new_html = new_html.substring(0, g.maxTruncatedLen) + '...';
628                             }
629                         }
630                         $this_field.find('span').text(new_html);
631                     }
632                 }
633                 if (data.transformations !== undefined) {
634                     $.each(data.transformations, function (cell_index, value) {
635                         var $this_field = $(g.t).find('.to_be_saved:eq(' + cell_index + ')');
636                         $this_field.find('span').html(value);
637                     });
638                 }
639                 if (data.relations !== undefined) {
640                     $.each(data.relations, function (cell_index, value) {
641                         var $this_field = $(g.t).find('.to_be_saved:eq(' + cell_index + ')');
642                         $this_field.find('span').html(value);
643                     });
644                 }
646                 // refresh the grid
647                 g.reposRsz();
648                 g.reposDrop();
649             }
651             // hide the cell editing area
652             $(g.cEdit).hide();
653             $(g.cEdit).find('.edit_box').blur();
654             g.isCellEditActive = false;
655             g.currentEditCell = null;
656             // destroy datepicker in edit area, if exist
657             var $dp = $(g.cEdit).find('.hasDatepicker');
658             if ($dp.length > 0) {
659                 $dp.datepicker('destroy');
660                 // change the cursor in edit box back to normal
661                 // (the cursor become a hand pointer when we add datepicker)
662                 $(g.cEdit).find('.edit_box').css('cursor', 'inherit');
663             }
664         },
666         /**
667          * Show drop-down edit area when edit cell is focused.
668          */
669         showEditArea: function () {
670             if (!g.isCellEditActive) {   // make sure the edit area has not been shown
671                 g.isCellEditActive = true;
672                 g.isEditCellTextEditable = false;
673                 /**
674                  * @var $td current edited cell
675                  */
676                 var $td = $(g.currentEditCell);
677                 /**
678                  * @var $editArea the editing area
679                  */
680                 var $editArea = $(g.cEdit).find('.edit_area');
681                 /**
682                  * @var where_clause WHERE clause for the edited cell
683                  */
684                 var where_clause = $td.parent('tr').find('.where_clause').val();
685                 /**
686                  * @var field_name  String containing the name of this field.
687                  * @see getFieldName()
688                  */
689                 var field_name = getFieldName($td);
690                 /**
691                  * @var relation_curr_value String current value of the field (for fields that are foreign keyed).
692                  */
693                 var relation_curr_value = $td.text();
694                 /**
695                  * @var relation_key_or_display_column String relational key if in 'Relational display column' mode,
696                  * relational display column if in 'Relational key' mode (for fields that are foreign keyed).
697                  */
698                 var relation_key_or_display_column = $td.find('a').attr('title');
699                 /**
700                  * @var curr_value String current value of the field (for fields that are of type enum or set).
701                  */
702                 var curr_value = $td.find('span').text();
704                 // empty all edit area, then rebuild it based on $td classes
705                 $editArea.empty();
707                 // add show data row link if the data resulted by 'browse distinct values' in table structure
708                 if ($td.find('input').hasClass('data_browse_link')) {
709                     var showDataRowLink = document.createElement('div');
710                     showDataRowLink.className = 'goto_link';
711                     $(showDataRowLink).append("<a href='" + $td.find('.data_browse_link').val() + "'>" + g.showDataRowLinkText + "</a>");
712                     $editArea.append(showDataRowLink);
713                 }
715                 // add goto link, if this cell contains a link
716                 if ($td.find('a').length > 0) {
717                     var gotoLink = document.createElement('div');
718                     gotoLink.className = 'goto_link';
719                     $(gotoLink).append(g.gotoLinkText + ': ').append($td.find('a').clone());
720                     $editArea.append(gotoLink);
721                 }
723                 g.wasEditedCellNull = false;
724                 if ($td.is(':not(.not_null)')) {
725                     // append a null checkbox
726                     $editArea.append('<div class="null_div">Null :<input type="checkbox"></div>');
727                     var $checkbox = $editArea.find('.null_div input');
728                     // check if current <td> is NULL
729                     if ($td.is('.null')) {
730                         $checkbox.prop('checked', true);
731                         g.wasEditedCellNull = true;
732                     }
734                     // if the select/editor is changed un-check the 'checkbox_null_<field_name>_<row_index>'.
735                     if ($td.is('.enum, .set')) {
736                         $editArea.find('select').live('change', function (e) {
737                             $checkbox.prop('checked', false);
738                         });
739                     } else if ($td.is('.relation')) {
740                         $editArea.find('select').live('change', function (e) {
741                             $checkbox.prop('checked', false);
742                         });
743                         $editArea.find('.browse_foreign').live('click', function (e) {
744                             $checkbox.prop('checked', false);
745                         });
746                     } else {
747                         $(g.cEdit).find('.edit_box').live('keypress change', function (e) {
748                             $checkbox.prop('checked', false);
749                         });
750                         // Capture ctrl+v (on IE and Chrome)
751                         $(g.cEdit).find('.edit_box').live('keydown', function (e) {
752                             if (e.ctrlKey && e.which == 86) {
753                                 $checkbox.prop('checked', false);
754                             }
755                         });
756                         $editArea.find('textarea').live('keydown', function (e) {
757                             $checkbox.prop('checked', false);
758                         });
759                     }
761                     // if null checkbox is clicked empty the corresponding select/editor.
762                     $checkbox.click(function (e) {
763                         if ($td.is('.enum')) {
764                             $editArea.find('select').val('');
765                         } else if ($td.is('.set')) {
766                             $editArea.find('select').find('option').each(function () {
767                                 var $option = $(this);
768                                 $option.prop('selected', false);
769                             });
770                         } else if ($td.is('.relation')) {
771                             // if the dropdown is there to select the foreign value
772                             if ($editArea.find('select').length > 0) {
773                                 $editArea.find('select').val('');
774                             }
775                         } else {
776                             $editArea.find('textarea').val('');
777                         }
778                         $(g.cEdit).find('.edit_box').val('');
779                     });
780                 }
782                 if ($td.is('.relation')) {
783                     //handle relations
784                     $editArea.addClass('edit_area_loading');
786                     // initialize the original data
787                     $td.data('original_data', null);
789                     /**
790                      * @var post_params Object containing parameters for the POST request
791                      */
792                     var post_params = {
793                         'ajax_request' : true,
794                         'get_relational_values' : true,
795                         'server' : g.server,
796                         'db' : g.db,
797                         'table' : g.table,
798                         'column' : field_name,
799                         'token' : g.token,
800                         'curr_value' : relation_curr_value,
801                         'relation_key_or_display_column' : relation_key_or_display_column
802                     };
804                     g.lastXHR = $.post('sql.php', post_params, function (data) {
805                         g.lastXHR = null;
806                         $editArea.removeClass('edit_area_loading');
807                         if ($(data.dropdown).is('select')) {
808                             // save original_data
809                             var value = $(data.dropdown).val();
810                             $td.data('original_data', value);
811                             // update the text input field, in case where the "Relational display column" is checked
812                             $(g.cEdit).find('.edit_box').val(value);
813                         }
815                         $editArea.append(data.dropdown);
816                         $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
818                         // for 'Browse foreign values' options,
819                         // hide the value next to 'Browse foreign values' link
820                         $editArea.find('span.curr_value').hide();
821                         // handle update for new values selected from new window
822                         $editArea.find('span.curr_value').change(function () {
823                             $(g.cEdit).find('.edit_box').val($(this).text());
824                         });
825                     }); // end $.post()
827                     $editArea.show();
828                     $editArea.find('select').live('change', function (e) {
829                         $(g.cEdit).find('.edit_box').val($(this).val());
830                     });
831                     g.isEditCellTextEditable = true;
832                 }
833                 else if ($td.is('.enum')) {
834                     //handle enum fields
835                     $editArea.addClass('edit_area_loading');
837                     /**
838                      * @var post_params Object containing parameters for the POST request
839                      */
840                     var post_params = {
841                         'ajax_request' : true,
842                         'get_enum_values' : true,
843                         'server' : g.server,
844                         'db' : g.db,
845                         'table' : g.table,
846                         'column' : field_name,
847                         'token' : g.token,
848                         'curr_value' : curr_value
849                     };
850                     g.lastXHR = $.post('sql.php', post_params, function (data) {
851                         g.lastXHR = null;
852                         $editArea.removeClass('edit_area_loading');
853                         $editArea.append(data.dropdown);
854                         $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
855                     }); // end $.post()
857                     $editArea.show();
858                     $editArea.find('select').live('change', function (e) {
859                         $(g.cEdit).find('.edit_box').val($(this).val());
860                     });
861                 }
862                 else if ($td.is('.set')) {
863                     //handle set fields
864                     $editArea.addClass('edit_area_loading');
866                     /**
867                      * @var post_params Object containing parameters for the POST request
868                      */
869                     var post_params = {
870                         'ajax_request' : true,
871                         'get_set_values' : true,
872                         'server' : g.server,
873                         'db' : g.db,
874                         'table' : g.table,
875                         'column' : field_name,
876                         'token' : g.token,
877                         'curr_value' : curr_value
878                     };
880                     g.lastXHR = $.post('sql.php', post_params, function (data) {
881                         g.lastXHR = null;
882                         $editArea.removeClass('edit_area_loading');
883                         $editArea.append(data.select);
884                         $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
885                     }); // end $.post()
887                     $editArea.show();
888                     $editArea.find('select').live('change', function (e) {
889                         $(g.cEdit).find('.edit_box').val($(this).val());
890                     });
891                 }
892                 else if ($td.is('.truncated, .transformed')) {
893                     if ($td.is('.to_be_saved')) {   // cell has been edited
894                         var value = $td.data('value');
895                         $(g.cEdit).find('.edit_box').val(value);
896                         $editArea.append('<textarea></textarea>');
897                         $editArea.find('textarea')
898                             .val(value)
899                             .live('keyup', function (e) {
900                                 $(g.cEdit).find('.edit_box').val($(this).val());
901                             });
902                         $(g.cEdit).find('.edit_box').live('keyup', function (e) {
903                             $editArea.find('textarea').val($(this).val());
904                         });
905                         $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
906                     } else {
907                         //handle truncated/transformed values values
908                         $editArea.addClass('edit_area_loading');
910                         // initialize the original data
911                         $td.data('original_data', null);
913                         /**
914                          * @var sql_query   String containing the SQL query used to retrieve value of truncated/transformed data
915                          */
916                         var sql_query = 'SELECT `' + field_name + '` FROM `' + g.table + '` WHERE ' + PMA_urldecode(where_clause);
918                         // Make the Ajax call and get the data, wrap it and insert it
919                         g.lastXHR = $.post('sql.php', {
920                             'token' : g.token,
921                             'server' : g.server,
922                             'db' : g.db,
923                             'ajax_request' : true,
924                             'sql_query' : sql_query,
925                             'grid_edit' : true
926                         }, function (data) {
927                             g.lastXHR = null;
928                             $editArea.removeClass('edit_area_loading');
929                             if (data.success === true) {
930                                 if ($td.is('.truncated')) {
931                                     // get the truncated data length
932                                     g.maxTruncatedLen = $(g.currentEditCell).text().length - 3;
933                                 }
935                                 $td.data('original_data', data.value);
936                                 $(g.cEdit).find('.edit_box').val(data.value);
937                                 $editArea.append('<textarea></textarea>');
938                                 $editArea.find('textarea')
939                                     .val(data.value)
940                                     .live('keyup', function (e) {
941                                         $(g.cEdit).find('.edit_box').val($(this).val());
942                                     });
943                                 $(g.cEdit).find('.edit_box').live('keyup', function (e) {
944                                     $editArea.find('textarea').val($(this).val());
945                                 });
946                                 $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
947                             } else {
948                                 PMA_ajaxShowMessage(data.error, false);
949                             }
950                         }); // end $.post()
951                         $editArea.show();
952                     }
953                     g.isEditCellTextEditable = true;
954                 } else if ($td.is('.datefield, .datetimefield, .timestampfield')) {
955                     var $input_field = $(g.cEdit).find('.edit_box');
957                     // remember current datetime value in $input_field, if it is not null
958                     var is_null = $td.is('.null');
959                     var current_datetime_value = !is_null ? $input_field.val() : '';
961                     var showTimeOption = true;
962                     if ($td.is('.datefield')) {
963                         showTimeOption = false;
964                     }
965                     PMA_addDatepicker($editArea, {
966                         altField: $input_field,
967                         showTimepicker: showTimeOption,
968                         onSelect: function (dateText, inst) {
969                             // remove null checkbox if it exists
970                             $(g.cEdit).find('.null_div input[type=checkbox]').prop('checked', false);
971                         }
972                     });
974                     // cancel any click on the datepicker element
975                     $editArea.find('> *').click(function (e) {
976                         e.stopPropagation();
977                     });
979                     // force to restore modified $input_field value after adding datepicker
980                     // (after adding a datepicker, the input field doesn't display the time anymore, only the date)
981                     if (is_null
982                         || current_datetime_value == '0000-00-00'
983                         || current_datetime_value == '0000-00-00 00:00:00.000000'
984                     ) {
985                         $input_field.val(current_datetime_value);
986                     } else {
987                         var date;
988                         if (current_datetime_value.match(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{6}$/)) {
989                             date = new Date(current_datetime_value.substring(0, 10));
990                             var hour = current_datetime_value.substring(11, 13);
991                             var min = current_datetime_value.substring(14, 16);
992                             var sec = current_datetime_value.substring(17, 19);
993                             var milli = current_datetime_value.substring(20, 23);
994                             var micro = current_datetime_value.substring(23);
995                             date.setHours(hour, min, sec, milli);
996                             date.setMicroseconds(micro);
997                         } else {
998                             date = new Date(current_datetime_value);
999                         }
1000                         $editArea.datetimepicker('setDate', date);
1001                     }
1002                     $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
1004                     // remove {cursor: 'pointer'} added inside
1005                     // jquery-ui-timepicker-addon.js
1006                     $input_field.css('cursor', '');
1007                     // make the cell editable, so one can can bypass the timepicker
1008                     // and enter date/time value manually
1009                     g.isEditCellTextEditable = true;
1010                 } else {
1011                     g.isEditCellTextEditable = true;
1012                     // only append edit area hint if there is a null checkbox
1013                     if ($editArea.children().length > 0) {
1014                         $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
1015                     }
1016                 }
1017                 if ($editArea.children().length > 0) {
1018                     $editArea.show();
1019                 }
1020             }
1021         },
1023         /**
1024          * Post the content of edited cell.
1025          */
1026         postEditedCell: function () {
1027             if (g.isSaving) {
1028                 return;
1029             }
1030             g.isSaving = true;
1032             /**
1033              * @var relation_fields Array containing the name/value pairs of relational fields
1034              */
1035             var relation_fields = {};
1036             /**
1037              * @var relational_display string 'K' if relational key, 'D' if relational display column
1038              */
1039             var relational_display = $("#relational_display_K").prop('checked') ? 'K' : 'D';
1040             /**
1041              * @var transform_fields    Array containing the name/value pairs for transformed fields
1042              */
1043             var transform_fields = {};
1044             /**
1045              * @var transformation_fields   Boolean, if there are any transformed fields in the edited cells
1046              */
1047             var transformation_fields = false;
1048             /**
1049              * @var full_sql_query String containing the complete SQL query to update this table
1050              */
1051             var full_sql_query = '';
1052             /**
1053              * @var rel_fields_list  String, url encoded representation of {@link relations_fields}
1054              */
1055             var rel_fields_list = '';
1056             /**
1057              * @var transform_fields_list  String, url encoded representation of {@link transform_fields}
1058              */
1059             var transform_fields_list = '';
1060             /**
1061              * @var where_clause Array containing where clause for updated fields
1062              */
1063             var full_where_clause = [];
1064             /**
1065              * @var is_unique   Boolean, whether the rows in this table is unique or not
1066              */
1067             var is_unique = $('td.edit_row_anchor').is('.nonunique') ? 0 : 1;
1068             /**
1069              * multi edit variables
1070              */
1071             var me_fields_name = [];
1072             var me_fields = [];
1073             var me_fields_null = [];
1075             // alert user if edited table is not unique
1076             if (!is_unique) {
1077                 alert(g.alertNonUnique);
1078             }
1080             // loop each edited row
1081             $('td.to_be_saved').parents('tr').each(function () {
1082                 var $tr = $(this);
1083                 var where_clause = $tr.find('.where_clause').val();
1084                 full_where_clause.push(PMA_urldecode(where_clause));
1085                 var condition_array = jQuery.parseJSON($tr.find('.condition_array').val());
1087                 /**
1088                  * multi edit variables, for current row
1089                  * @TODO array indices are still not correct, they should be md5 of field's name
1090                  */
1091                 var fields_name = [];
1092                 var fields = [];
1093                 var fields_null = [];
1095                 // loop each edited cell in a row
1096                 $tr.find('.to_be_saved').each(function () {
1097                     /**
1098                      * @var $this_field    Object referring to the td that is being edited
1099                      */
1100                     var $this_field = $(this);
1102                     /**
1103                      * @var field_name  String containing the name of this field.
1104                      * @see getFieldName()
1105                      */
1106                     var field_name = getFieldName($this_field);
1108                     /**
1109                      * @var this_field_params   Array temporary storage for the name/value of current field
1110                      */
1111                     var this_field_params = {};
1113                     if ($this_field.is('.transformed')) {
1114                         transformation_fields =  true;
1115                     }
1116                     this_field_params[field_name] = $this_field.data('value');
1118                     /**
1119                      * @var is_null String capturing whether 'checkbox_null_<field_name>_<row_index>' is checked.
1120                      */
1121                     var is_null = this_field_params[field_name] === null;
1123                     fields_name.push(field_name);
1125                     if (is_null) {
1126                         fields_null.push('on');
1127                         fields.push('');
1128                     } else {
1129                         fields_null.push('');
1130                         fields.push($this_field.data('value'));
1132                         var cell_index = $this_field.index('.to_be_saved');
1133                         if ($this_field.is(":not(.relation, .enum, .set, .bit)")) {
1134                             if ($this_field.is('.transformed')) {
1135                                 transform_fields[cell_index] = {};
1136                                 $.extend(transform_fields[cell_index], this_field_params);
1137                             }
1138                         } else if ($this_field.is('.relation')) {
1139                             relation_fields[cell_index] = {};
1140                             $.extend(relation_fields[cell_index], this_field_params);
1141                         }
1142                     }
1143                     // check if edited field appears in WHERE clause
1144                     if (where_clause.indexOf(PMA_urlencode(field_name)) > -1) {
1145                         var field_str = '`' + g.table + '`.' + '`' + field_name + '`';
1146                         for (var field in condition_array) {
1147                             if (field.indexOf(field_str) > -1) {
1148                                 condition_array[field] = is_null ? 'IS NULL' : "= '" + this_field_params[field_name].replace(/'/g, "''") + "'";
1149                                 break;
1150                             }
1151                         }
1152                     }
1154                 }); // end of loop for every edited cells in a row
1156                 // save new_clause
1157                 var new_clause = '';
1158                 for (var field in condition_array) {
1159                     new_clause += field + ' ' + condition_array[field] + ' AND ';
1160                 }
1161                 new_clause = new_clause.substring(0, new_clause.length - 5); // remove the last AND
1162                 new_clause = PMA_urlencode(new_clause);
1163                 $tr.data('new_clause', new_clause);
1164                 // save condition_array
1165                 $tr.find('.condition_array').val(JSON.stringify(condition_array));
1167                 me_fields_name.push(fields_name);
1168                 me_fields.push(fields);
1169                 me_fields_null.push(fields_null);
1171             }); // end of loop for every edited rows
1173             rel_fields_list = $.param(relation_fields);
1174             transform_fields_list = $.param(transform_fields);
1176             // Make the Ajax post after setting all parameters
1177             /**
1178              * @var post_params Object containing parameters for the POST request
1179              */
1180             var post_params = {'ajax_request' : true,
1181                             'sql_query' : full_sql_query,
1182                             'token' : g.token,
1183                             'server' : g.server,
1184                             'db' : g.db,
1185                             'table' : g.table,
1186                             'clause_is_unique' : is_unique,
1187                             'where_clause' : full_where_clause,
1188                             'fields[multi_edit]' : me_fields,
1189                             'fields_name[multi_edit]' : me_fields_name,
1190                             'fields_null[multi_edit]' : me_fields_null,
1191                             'rel_fields_list' : rel_fields_list,
1192                             'do_transformations' : transformation_fields,
1193                             'transform_fields_list' : transform_fields_list,
1194                             'relational_display' : relational_display,
1195                             'goto' : 'sql.php',
1196                             'submit_type' : 'save'
1197                           };
1199             if (!g.saveCellsAtOnce) {
1200                 $(g.cEdit).find('*').prop('disabled', true);
1201                 $(g.cEdit).find('.edit_box').addClass('edit_box_posting');
1202             } else {
1203                 $('div.save_edited').addClass('saving_edited_data')
1204                     .find('input').prop('disabled', true);    // disable the save button
1205             }
1207             $.ajax({
1208                 type: 'POST',
1209                 url: 'tbl_replace.php',
1210                 data: post_params,
1211                 success:
1212                     function (data) {
1213                         g.isSaving = false;
1214                         if (!g.saveCellsAtOnce) {
1215                             $(g.cEdit).find('*').removeProp('disabled');
1216                             $(g.cEdit).find('.edit_box').removeClass('edit_box_posting');
1217                         } else {
1218                             $('div.save_edited').removeClass('saving_edited_data')
1219                                 .find('input').removeProp('disabled');  // enable the save button back
1220                         }
1221                         if (data.success === true) {
1222                             PMA_ajaxShowMessage(data.message);
1224                             // update where_clause related data in each edited row
1225                             $('td.to_be_saved').parents('tr').each(function () {
1226                                 var new_clause = $(this).data('new_clause');
1227                                 var $where_clause = $(this).find('.where_clause');
1228                                 var old_clause = $where_clause.val();
1229                                 var decoded_old_clause = PMA_urldecode(old_clause);
1230                                 var decoded_new_clause = PMA_urldecode(new_clause);
1232                                 $where_clause.val(new_clause);
1233                                 // update Edit, Copy, and Delete links also
1234                                 $(this).find('a').each(function () {
1235                                     $(this).attr('href', $(this).attr('href').replace(old_clause, new_clause));
1236                                     // update delete confirmation in Delete link
1237                                     if ($(this).attr('href').indexOf('DELETE') > -1) {
1238                                         $(this).removeAttr('onclick')
1239                                             .unbind('click')
1240                                             .bind('click', function () {
1241                                                 return confirmLink(this, 'DELETE FROM `' + g.db + '`.`' + g.table + '` WHERE ' +
1242                                                        decoded_new_clause + (is_unique ? '' : ' LIMIT 1'));
1243                                             });
1244                                     }
1245                                 });
1246                                 // update the multi edit checkboxes
1247                                 $(this).find('input[type=checkbox]').each(function () {
1248                                     var $checkbox = $(this);
1249                                     var checkbox_name = $checkbox.attr('name');
1250                                     var checkbox_value = $checkbox.val();
1252                                     $checkbox.attr('name', checkbox_name.replace(old_clause, new_clause));
1253                                     $checkbox.val(checkbox_value.replace(decoded_old_clause, decoded_new_clause));
1254                                 });
1255                             });
1256                             // update the display of executed SQL query command
1257                             $('#result_query').remove();
1258                             if (typeof data.sql_query != 'undefined') {
1259                                 // display feedback
1260                                 $('#sqlqueryresults').prepend(data.sql_query);
1261                             }
1262                             // hide and/or update the successfully saved cells
1263                             g.hideEditCell(true, data);
1265                             // remove the "Save edited cells" button
1266                             $('div.save_edited').hide();
1267                             // update saved fields
1268                             $(g.t).find('.to_be_saved')
1269                                 .removeClass('to_be_saved')
1270                                 .data('value', null)
1271                                 .data('original_data', null);
1273                             g.isCellEdited = false;
1274                         } else {
1275                             PMA_ajaxShowMessage(data.error, false);
1276                         }
1277                     }
1278             }); // end $.ajax()
1279         },
1281         /**
1282          * Save edited cell, so it can be posted later.
1283          */
1284         saveEditedCell: function () {
1285             /**
1286              * @var $this_field    Object referring to the td that is being edited
1287              */
1288             var $this_field = $(g.currentEditCell);
1289             var $test_element = ''; // to test the presence of a element
1291             var need_to_post = false;
1293             /**
1294              * @var field_name  String containing the name of this field.
1295              * @see getFieldName()
1296              */
1297             var field_name = getFieldName($this_field);
1299             /**
1300              * @var this_field_params   Array temporary storage for the name/value of current field
1301              */
1302             var this_field_params = {};
1304             /**
1305              * @var is_null String capturing whether 'checkbox_null_<field_name>_<row_index>' is checked.
1306              */
1307             var is_null = $(g.cEdit).find('input:checkbox').is(':checked');
1308             var value;
1310             if ($(g.cEdit).find('.edit_area').is('.edit_area_loading')) {
1311                 // the edit area is still loading (retrieving cell data), no need to post
1312                 need_to_post = false;
1313             } else if (is_null) {
1314                 if (!g.wasEditedCellNull) {
1315                     this_field_params[field_name] = null;
1316                     need_to_post = true;
1317                 }
1318             } else {
1319                 if ($this_field.is('.bit')) {
1320                     this_field_params[field_name] = '0b' + $(g.cEdit).find('.edit_box').val();
1321                 } else if ($this_field.is('.set')) {
1322                     $test_element = $(g.cEdit).find('select');
1323                     this_field_params[field_name] = $test_element.map(function () {
1324                         return $(this).val();
1325                     }).get().join(",");
1326                 } else if ($this_field.is('.relation, .enum')) {
1327                     // for relation and enumeration, take the results from edit box value,
1328                     // because selected value from drop-down, new window or multiple
1329                     // selection list will always be updated to the edit box
1330                     this_field_params[field_name] = $(g.cEdit).find('.edit_box').val();
1331                 } else {
1332                     this_field_params[field_name] = $(g.cEdit).find('.edit_box').val();
1333                 }
1334                 if (g.wasEditedCellNull || this_field_params[field_name] != PMA_getCellValue(g.currentEditCell)) {
1335                     need_to_post = true;
1336                 }
1337             }
1339             if (need_to_post) {
1340                 $(g.currentEditCell).addClass('to_be_saved')
1341                     .data('value', this_field_params[field_name]);
1342                 if (g.saveCellsAtOnce) {
1343                     $('div.save_edited').show();
1344                 }
1345                 g.isCellEdited = true;
1346             }
1348             return need_to_post;
1349         },
1351         /**
1352          * Save or post currently edited cell, depending on the "saveCellsAtOnce" configuration.
1353          */
1354         saveOrPostEditedCell: function () {
1355             var saved = g.saveEditedCell();
1356             if (!g.saveCellsAtOnce) {
1357                 if (saved) {
1358                     g.postEditedCell();
1359                 } else {
1360                     g.hideEditCell(true);
1361                 }
1362             } else {
1363                 if (saved) {
1364                     g.hideEditCell(true, true);
1365                 } else {
1366                     g.hideEditCell(true);
1367                 }
1368             }
1369         },
1371         /**
1372          * Initialize column resize feature.
1373          */
1374         initColResize: function () {
1375             // create column resizer div
1376             g.cRsz = document.createElement('div');
1377             g.cRsz.className = 'cRsz';
1379             // get data columns in the first row of the table
1380             var $firstRowCols = $(g.t).find('tr:first th.draggable');
1382             // create column borders
1383             $firstRowCols.each(function () {
1384                 var cb = document.createElement('div'); // column border
1385                 $(cb).addClass('colborder')
1386                     .mousedown(function (e) {
1387                         g.dragStartRsz(e, this);
1388                     });
1389                 $(g.cRsz).append(cb);
1390             });
1391             g.reposRsz();
1393             // attach to global div
1394             $(g.gDiv).prepend(g.cRsz);
1395         },
1397         /**
1398          * Initialize column reordering feature.
1399          */
1400         initColReorder: function () {
1401             g.cCpy = document.createElement('div');     // column copy, to store copy of dragged column header
1402             g.cPointer = document.createElement('div'); // column pointer, used when reordering column
1404             // adjust g.cCpy
1405             g.cCpy.className = 'cCpy';
1406             $(g.cCpy).hide();
1408             // adjust g.cPointer
1409             g.cPointer.className = 'cPointer';
1410             $(g.cPointer).css('visibility', 'hidden');  // set visibility to hidden instead of calling hide() to force browsers to cache the image in cPointer class
1412             // assign column reordering hint
1413             g.reorderHint = PMA_messages.strColOrderHint;
1415             // get data columns in the first row of the table
1416             var $firstRowCols = $(g.t).find('tr:first th.draggable');
1418             // initialize column order
1419             $col_order = $('#col_order');   // check if column order is passed from PHP
1420             if ($col_order.length > 0) {
1421                 g.colOrder = $col_order.val().split(',');
1422                 for (var i = 0; i < g.colOrder.length; i++) {
1423                     g.colOrder[i] = parseInt(g.colOrder[i], 10);
1424                 }
1425             } else {
1426                 g.colOrder = [];
1427                 for (var i = 0; i < $firstRowCols.length; i++) {
1428                     g.colOrder.push(i);
1429                 }
1430             }
1432             // register events
1433             $(t).find('th.draggable')
1434                 .mousedown(function (e) {
1435                     if (g.visibleHeadersCount > 1) {
1436                         g.dragStartReorder(e, this);
1437                     }
1438                 })
1439                 .mouseenter(function (e) {
1440                     if (g.visibleHeadersCount > 1) {
1441                         $(this).css('cursor', 'move');
1442                     } else {
1443                         $(this).css('cursor', 'inherit');
1444                     }
1445                 })
1446                 .mouseleave(function (e) {
1447                     g.showReorderHint = false;
1448                     $(this).tooltip("option", {
1449                         content: g.updateHint()
1450                     });
1451                 })
1452                 .dblclick(function (e) {
1453                     e.preventDefault();
1454                     $("<div/>")
1455                     .prop("title", PMA_messages.strColNameCopyTitle)
1456                     .addClass("modal-copy")
1457                     .text(PMA_messages.strColNameCopyText)
1458                     .append(
1459                         $("<input/>")
1460                         .prop("readonly", true)
1461                         .val($(this).data("column"))
1462                         )
1463                     .dialog({
1464                         resizable: false,
1465                         modal: true
1466                     })
1467                     .find("input").focus().select();
1468                 });
1469             // restore column order when the restore button is clicked
1470             $('div.restore_column').click(function () {
1471                 g.restoreColOrder();
1472             });
1474             // attach to global div
1475             $(g.gDiv).append(g.cPointer);
1476             $(g.gDiv).append(g.cCpy);
1478             // prevent default "dragstart" event when dragging a link
1479             $(t).find('th a').bind('dragstart', function () {
1480                 return false;
1481             });
1483             // refresh the restore column button state
1484             g.refreshRestoreButton();
1485         },
1487         /**
1488          * Initialize column visibility feature.
1489          */
1490         initColVisib: function () {
1491             g.cDrop = document.createElement('div');    // column drop-down arrows
1492             g.cList = document.createElement('div');    // column visibility list
1494             // adjust g.cDrop
1495             g.cDrop.className = 'cDrop';
1497             // adjust g.cList
1498             g.cList.className = 'cList';
1499             $(g.cList).hide();
1501             // assign column visibility related hints
1502             g.showAllColText = PMA_messages.strShowAllCol;
1504             // get data columns in the first row of the table
1505             var $firstRowCols = $(g.t).find('tr:first th.draggable');
1507             // initialize column visibility
1508             var $col_visib = $('#col_visib');   // check if column visibility is passed from PHP
1509             if ($col_visib.length > 0) {
1510                 g.colVisib = $col_visib.val().split(',');
1511                 for (var i = 0; i < g.colVisib.length; i++) {
1512                     g.colVisib[i] = parseInt(g.colVisib[i], 10);
1513                 }
1514             } else {
1515                 g.colVisib = [];
1516                 for (var i = 0; i < $firstRowCols.length; i++) {
1517                     g.colVisib.push(1);
1518                 }
1519             }
1521             // make sure we have more than one column
1522             if ($firstRowCols.length > 1) {
1523                 var $colVisibTh = $(g.t).find('th:not(.draggable)');
1524                 PMA_tooltip(
1525                     $colVisibTh,
1526                     'th',
1527                     PMA_messages.strColVisibHint
1528                 );
1530                 // create column visibility drop-down arrow(s)
1531                 $colVisibTh.each(function () {
1532                         var $th = $(this);
1533                         var cd = document.createElement('div'); // column drop-down arrow
1534                         var pos = $th.position();
1535                         $(cd).addClass('coldrop')
1536                             .click(function () {
1537                                 if (g.cList.style.display == 'none') {
1538                                     g.showColList(this);
1539                                 } else {
1540                                     g.hideColList();
1541                                 }
1542                             });
1543                         $(g.cDrop).append(cd);
1544                     });
1546                 // add column visibility control
1547                 g.cList.innerHTML = '<div class="lDiv"></div>';
1548                 var $listDiv = $(g.cList).find('div');
1549                 for (var i = 0; i < $firstRowCols.length; i++) {
1550                     var currHeader = $firstRowCols[i];
1551                     var listElmt = document.createElement('div');
1552                     $(listElmt).text($(currHeader).text())
1553                         .prepend('<input type="checkbox" ' + (g.colVisib[i] ? 'checked="checked" ' : '') + '/>');
1554                     $listDiv.append(listElmt);
1555                     // add event on click
1556                     $(listElmt).click(function () {
1557                         if (g.toggleCol($(this).index())) {
1558                             g.afterToggleCol();
1559                         }
1560                     });
1561                 }
1562                 // add "show all column" button
1563                 var showAll = document.createElement('div');
1564                 $(showAll).addClass('showAllColBtn')
1565                     .text(g.showAllColText);
1566                 $(g.cList).append(showAll);
1567                 $(showAll).click(function () {
1568                     g.showAllColumns();
1569                 });
1570                 // prepend "show all column" button at top if the list is too long
1571                 if ($firstRowCols.length > 10) {
1572                     var clone = showAll.cloneNode(true);
1573                     $(g.cList).prepend(clone);
1574                     $(clone).click(function () {
1575                         g.showAllColumns();
1576                     });
1577                 }
1578             }
1580             // hide column visibility list if we move outside the list
1581             $(t).find('td, th.draggable').mouseenter(function () {
1582                 g.hideColList();
1583             });
1585             // attach to global div
1586             $(g.gDiv).append(g.cDrop);
1587             $(g.gDiv).append(g.cList);
1589             // some adjustment
1590             g.reposDrop();
1591         },
1593         /**
1594          * Initialize grid editing feature.
1595          */
1596         initGridEdit: function () {
1598             function startGridEditing(e, cell) {
1599                 if (g.isCellEditActive) {
1600                     g.saveOrPostEditedCell();
1601                 } else {
1602                     g.showEditCell(cell);
1603                 }
1604                 e.stopPropagation();
1605             }
1607             // create cell edit wrapper element
1608             g.cEdit = document.createElement('div');
1610             // adjust g.cEdit
1611             g.cEdit.className = 'cEdit';
1612             $(g.cEdit).html('<textarea class="edit_box" rows="1" ></textarea><div class="edit_area" />');
1613             $(g.cEdit).hide();
1615             // assign cell editing hint
1616             g.cellEditHint = PMA_messages.strCellEditHint;
1617             g.saveCellWarning = PMA_messages.strSaveCellWarning;
1618             g.alertNonUnique = PMA_messages.strAlertNonUnique;
1619             g.gotoLinkText = PMA_messages.strGoToLink;
1620             g.showDataRowLinkText = PMA_messages.strShowDataRowLink;
1622             // initialize cell editing configuration
1623             g.saveCellsAtOnce = $('#save_cells_at_once').val();
1625             // register events
1626             $(t).find('td.data.click1')
1627                 .click(function (e) {
1628                     startGridEditing(e, this);
1629                     // prevent default action when clicking on "link" in a table
1630                     if ($(e.target).is('.grid_edit a')) {
1631                         e.preventDefault();
1632                     }
1633                 });
1635             $(t).find('td.data.click2')
1636                 .click(function (e) {
1637                     $cell = $(this);
1638                     // In the case of relational link, We want single click on the link
1639                     // to goto the link and double click to start grid-editing.
1640                     var $link = $(e.target);
1641                     if ($link.is('.grid_edit.relation a')) {
1642                         e.preventDefault();
1643                         // get the click count and increase
1644                         var clicks = $cell.data('clicks');
1645                         clicks = (typeof clicks === 'undefined') ? 1 : clicks + 1;
1647                         if (clicks == 1) {
1648                             // if there are no previous clicks,
1649                             // start the single click timer
1650                             timer = setTimeout(function () {
1651                                 // temporarily remove ajax class so the page loader will not handle it,
1652                                 // submit and then add it back
1653                                 $link.removeClass('ajax');
1654                                 AJAX.requestHandler.call($link[0]);
1655                                 $link.addClass('ajax');
1656                                 $cell.data('clicks', 0);
1657                             }, 700);
1658                             $cell.data('clicks', clicks);
1659                             $cell.data('timer', timer);
1660                         } else {
1661                             // this is a double click, cancel the single click timer
1662                             // and make the click count 0
1663                             clearTimeout($cell.data('timer'));
1664                             $cell.data('clicks', 0);
1665                             // start grid-editing
1666                             startGridEditing(e, this);
1667                         }
1668                     }
1669                 })
1670                 .dblclick(function (e) {
1671                     if ($(e.target).is('.grid_edit a')) {
1672                         e.preventDefault();
1673                     } else {
1674                         startGridEditing(e, this);
1675                     }
1676                 });
1678             $(g.cEdit).find('.edit_box').focus(function (e) {
1679                 g.showEditArea();
1680             });
1681             $(g.cEdit).find('.edit_box, select').live('keydown', function (e) {
1682                 if (e.which == 13) {
1683                     // post on pressing "Enter"
1684                     e.preventDefault();
1685                     g.saveOrPostEditedCell();
1686                 }
1687             });
1688             $(g.cEdit).keydown(function (e) {
1689                 if (!g.isEditCellTextEditable) {
1690                     // prevent text editing
1691                     e.preventDefault();
1692                 }
1693             });
1694             $('html').click(function (e) {
1695                 // hide edit cell if the click is not from g.cEdit
1696                 if ($(e.target).parents().index(g.cEdit) == -1) {
1697                     g.hideEditCell();
1698                 }
1699             }).keydown(function (e) {
1700                 if (e.which == 27 && g.isCellEditActive) {
1702                     // cancel on pressing "Esc"
1703                     g.hideEditCell(true);
1704                 }
1705             });
1706             $('div.save_edited').click(function () {
1707                 g.hideEditCell();
1708                 g.postEditedCell();
1709             });
1710             $(window).bind('beforeunload', function (e) {
1711                 if (g.isCellEdited) {
1712                     return g.saveCellWarning;
1713                 }
1714             });
1716             // attach to global div
1717             $(g.gDiv).append(g.cEdit);
1719             // add hint for grid editing feature when hovering "Edit" link in each table row
1720             if (PMA_messages.strGridEditFeatureHint !== undefined) {
1721                 PMA_tooltip(
1722                     $(g.t).find('.edit_row_anchor a'),
1723                     'a',
1724                     PMA_messages.strGridEditFeatureHint
1725                 );
1726             }
1727         }
1728     };
1730     /******************
1731      * Initialize grid
1732      ******************/
1734     // wrap all data cells, except actions cell, with span
1735     $(t).find('th, td:not(:has(span))')
1736         .wrapInner('<span />');
1738     // create grid elements
1739     g.gDiv = document.createElement('div');     // create global div
1741     // initialize the table variable
1742     g.t = t;
1744     // get data columns in the first row of the table
1745     var $firstRowCols = $(t).find('tr:first th.draggable');
1747     // initialize visible headers count
1748     g.visibleHeadersCount = $firstRowCols.filter(':visible').length;
1750     // assign first column (actions) span
1751     if (! $(t).find('tr:first th:first').hasClass('draggable')) {  // action header exist
1752         g.actionSpan = $(t).find('tr:first th:first').prop('colspan');
1753     } else {
1754         g.actionSpan = 0;
1755     }
1757     // assign table create time
1758     // #table_create_time will only available if we are in "Browse" tab
1759     g.tableCreateTime = $('#table_create_time').val();
1761     // assign the hints
1762     g.sortHint = PMA_messages.strSortHint;
1763     g.markHint = PMA_messages.strColMarkHint;
1764     g.copyHint = PMA_messages.strColNameCopyHint;
1766     // assign common hidden inputs
1767     var $common_hidden_inputs = $('div.common_hidden_inputs');
1768     g.token = $common_hidden_inputs.find('input[name=token]').val();
1769     g.server = $common_hidden_inputs.find('input[name=server]').val();
1770     g.db = $common_hidden_inputs.find('input[name=db]').val();
1771     g.table = $common_hidden_inputs.find('input[name=table]').val();
1773     // add table class
1774     $(t).addClass('pma_table');
1776     // add relative position to global div so that resize handlers are correctly positioned
1777     $(g.gDiv).css('position', 'relative');
1779     // link the global div
1780     $(t).before(g.gDiv);
1781     $(g.gDiv).append(t);
1783     // FEATURES
1784     enableResize    = enableResize === undefined ? true : enableResize;
1785     enableReorder   = enableReorder === undefined ? true : enableReorder;
1786     enableVisib     = enableVisib === undefined ? true : enableVisib;
1787     enableGridEdit  = enableGridEdit === undefined ? true : enableGridEdit;
1788     if (enableResize) {
1789         g.initColResize();
1790     }
1791     if (enableReorder &&
1792         $('table.navigation').length > 0)    // disable reordering for result from EXPLAIN or SHOW syntax, which do not have a table navigation panel
1793     {
1794         g.initColReorder();
1795     }
1796     if (enableVisib) {
1797         g.initColVisib();
1798     }
1799     if (enableGridEdit &&
1800         $(t).is('.ajax'))   // make sure we have the ajax class
1801     {
1802         g.initGridEdit();
1803     }
1805     // create tooltip for each <th> with draggable class
1806     PMA_tooltip(
1807             $(t).find("th.draggable"),
1808             'th',
1809             g.updateHint()
1810     );
1812     // register events for hint tooltip (anchors inside draggable th)
1813     $(t).find('th.draggable a')
1814         .mouseenter(function (e) {
1815             g.showSortHint = true;
1816             $(t).find("th.draggable").tooltip("option", {
1817                 content: g.updateHint()
1818             });
1819         })
1820         .mouseleave(function (e) {
1821             g.showSortHint = false;
1822             $(t).find("th.draggable").tooltip("option", {
1823                 content: g.updateHint()
1824             });
1825         });
1827     // register events for dragging-related feature
1828     if (enableResize || enableReorder) {
1829         $(document).mousemove(function (e) {
1830             g.dragMove(e);
1831         });
1832         $(document).mouseup(function (e) {
1833             g.dragEnd(e);
1834         });
1835     }
1837     // some adjustment
1838     $(t).removeClass('data');
1839     $(g.gDiv).addClass('data');