Translated using Weblate.
[phpmyadmin.git] / js / makegrid.js
blob95f84cd14d0d2cada97218c7692af45d0f791f68
1 /**
2  * Create advanced table (resize, reorder, and show/hide columns; and also grid editing).
3  * This function is designed mainly for table DOM generated from browsing a table in the database.
4  * For using this function in other table DOM, you may need to:
5  * - add "draggable" class in the table header <th>, in order to make it resizable, sortable or hidable
6  * - have at least one non-"draggable" header in the table DOM for placing column visibility drop-down arrow
7  * - pass the value "false" for the parameter "enableGridEdit"
8  * - adjust other parameter value, to select which features that will be enabled
9  *
10  * @param t the table DOM element
11  * @param enableResize Optional, if false, column resizing feature will be disabled
12  * @param enableReorder Optional, if false, column reordering feature will be disabled
13  * @param enableVisib Optional, if false, show/hide column feature will be disabled
14  * @param enableGridEdit Optional, if false, grid editing feature will be disabled
15  */
16 function PMA_makegrid(t, enableResize, enableReorder, enableVisib, enableGridEdit) {
17     var g = {
18         /***********
19          * Constant
20          ***********/
21         minColWidth: 15,
24         /***********
25          * Variables, assigned with default value, changed later
26          ***********/
27         actionSpan: 5,              // number of colspan in Actions header in a table
28         tableCreateTime: null,      // table creation time, used for saving column order and visibility to server, only available in "Browse tab"
30         // Column reordering variables
31         colOrder: new Array(),      // array of column order
33         // Column visibility variables
34         colVisib: new Array(),      // array of column visibility
35         showAllColText: '',         // string, text for "show all" button under column visibility list
36         visibleHeadersCount: 0,     // number of visible data headers
38         // Table hint variables
39         qtip: null,                 // qtip API
40         reorderHint: '',            // string, hint for column reordering
41         sortHint: '',               // string, hint for column sorting
42         markHint: '',               // string, hint for column marking
43         colVisibHint: '',           // string, hint for column visibility drop-down
44         showReorderHint: false,
45         showSortHint: false,
46         showMarkHint: false,
47         showColVisibHint: false,
49         // Grid editing
50         isCellEditActive: false,    // true if current focus is in edit cell
51         isEditCellTextEditable: false,  // true if current edit cell is editable in the text input box (not textarea)
52         currentEditCell: null,      // reference to <td> that currently being edited
53         cellEditHint: '',           // hint shown when doing grid edit
54         gotoLinkText: '',           // "Go to link" text
55         wasEditedCellNull: false,   // true if last value of the edited cell was NULL
56         maxTruncatedLen: 0,         // number of characters that can be displayed in a cell
57         saveCellsAtOnce: false,     // $cfg[saveCellsAtOnce]
58         isCellEdited: false,        // true if at least one cell has been edited
59         saveCellWarning: '',        // string, warning text when user want to leave a page with unsaved edited data
60         lastXHR : null,             // last XHR object used in AJAX request
61         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
62         alertNonUnique: '',         // string, alert shown when saving edited nonunique table
64         // Common hidden inputs
65         token: null,
66         server: null,
67         db: null,
68         table: null,
71         /************
72          * Functions
73          ************/
75         /**
76          * Start to resize column. Called when clicking on column separator.
77          *
78          * @param e event
79          * @param obj dragged div object
80          */
81         dragStartRsz: function(e, obj) {
82             var n = $(g.cRsz).find('div').index(obj);    // get the index of separator (i.e., column index)
83             $(obj).addClass('colborder_active');
84             g.colRsz = {
85                 x0: e.pageX,
86                 n: n,
87                 obj: obj,
88                 objLeft: $(obj).position().left,
89                 objWidth: $(g.t).find('th.draggable:visible:eq(' + n + ') span').outerWidth()
90             };
91             $('body').css('cursor', 'col-resize');
92             $('body').noSelect();
93             if (g.isCellEditActive) {
94                 g.hideEditCell();
95             }
96         },
98         /**
99          * Start to reorder column. Called when clicking on table header.
100          *
101          * @param e event
102          * @param obj table header object
103          */
104         dragStartReorder: function(e, obj) {
105             // prepare the cCpy (column copy) and cPointer (column pointer) from the dragged column
106             $(g.cCpy).text($(obj).text());
107             var objPos = $(obj).position();
108             $(g.cCpy).css({
109                 top: objPos.top + 20,
110                 left: objPos.left,
111                 height: $(obj).height(),
112                 width: $(obj).width()
113             });
114             $(g.cPointer).css({
115                 top: objPos.top
116             });
118             // get the column index, zero-based
119             var n = g.getHeaderIdx(obj);
121             g.colReorder = {
122                 x0: e.pageX,
123                 y0: e.pageY,
124                 n: n,
125                 newn: n,
126                 obj: obj,
127                 objTop: objPos.top,
128                 objLeft: objPos.left
129             };
130             g.hideHint();
131             $('body').css('cursor', 'move');
132             $('body').noSelect();
133             if (g.isCellEditActive) {
134                 g.hideEditCell();
135             }
136         },
138         /**
139          * Handle mousemove event when dragging.
140          *
141          * @param e event
142          */
143         dragMove: function(e) {
144             if (g.colRsz) {
145                 var dx = e.pageX - g.colRsz.x0;
146                 if (g.colRsz.objWidth + dx > g.minColWidth) {
147                     $(g.colRsz.obj).css('left', g.colRsz.objLeft + dx + 'px');
148                 }
149             } else if (g.colReorder) {
150                 // dragged column animation
151                 var dx = e.pageX - g.colReorder.x0;
152                 $(g.cCpy)
153                     .css('left', g.colReorder.objLeft + dx)
154                     .show();
156                 // pointer animation
157                 var hoveredCol = g.getHoveredCol(e);
158                 if (hoveredCol) {
159                     var newn = g.getHeaderIdx(hoveredCol);
160                     g.colReorder.newn = newn;
161                     if (newn != g.colReorder.n) {
162                         // show the column pointer in the right place
163                         var colPos = $(hoveredCol).position();
164                         var newleft = newn < g.colReorder.n ?
165                                       colPos.left :
166                                       colPos.left + $(hoveredCol).outerWidth();
167                         $(g.cPointer)
168                             .css({
169                                 left: newleft,
170                                 visibility: 'visible'
171                             });
172                     } else {
173                         // no movement to other column, hide the column pointer
174                         $(g.cPointer).css('visibility', 'hidden');
175                     }
176                 }
177             }
178         },
180         /**
181          * Stop the dragging action.
182          *
183          * @param e event
184          */
185         dragEnd: function(e) {
186             if (g.colRsz) {
187                 var dx = e.pageX - g.colRsz.x0;
188                 var nw = g.colRsz.objWidth + dx;
189                 if (nw < g.minColWidth) {
190                     nw = g.minColWidth;
191                 }
192                 var n = g.colRsz.n;
193                 // do the resizing
194                 g.resize(n, nw);
196                 g.reposRsz();
197                 g.reposDrop();
198                 g.colRsz = false;
199                 $(g.cRsz).find('div').removeClass('colborder_active');
200             } else if (g.colReorder) {
201                 // shift columns
202                 if (g.colReorder.newn != g.colReorder.n) {
203                     g.shiftCol(g.colReorder.n, g.colReorder.newn);
204                     // assign new position
205                     var objPos = $(g.colReorder.obj).position();
206                     g.colReorder.objTop = objPos.top;
207                     g.colReorder.objLeft = objPos.left;
208                     g.colReorder.n = g.colReorder.newn;
209                     // send request to server to remember the column order
210                     if (g.tableCreateTime) {
211                         g.sendColPrefs();
212                     }
213                     g.refreshRestoreButton();
214                 }
216                 // animate new column position
217                 $(g.cCpy).stop(true, true)
218                     .animate({
219                         top: g.colReorder.objTop,
220                         left: g.colReorder.objLeft
221                     }, 'fast')
222                     .fadeOut();
223                 $(g.cPointer).css('visibility', 'hidden');
225                 g.colReorder = false;
226             }
227             $('body').css('cursor', 'inherit');
228             $('body').noSelect(false);
229         },
231         /**
232          * Resize column n to new width "nw"
233          *
234          * @param n zero-based column index
235          * @param nw new width of the column in pixel
236          */
237         resize: function(n, nw) {
238             $(g.t).find('tr').each(function() {
239                 $(this).find('th.draggable:visible:eq(' + n + ') span,' +
240                              'td:visible:eq(' + (g.actionSpan + n) + ') span')
241                        .css('width', nw);
242             });
243         },
245         /**
246          * Reposition column resize bars.
247          */
248         reposRsz: function() {
249             $(g.cRsz).find('div').hide();
250             var $firstRowCols = $(g.t).find('tr:first th.draggable:visible');
251             var $resizeHandles = $(g.cRsz).find('div').removeClass('condition');
252             $('.pma_table').find('thead th:first').removeClass('before-condition');
253             for (var n = 0; n < $firstRowCols.length; n++) {
254                 var $col = $($firstRowCols[n]);
255                 $($resizeHandles[n]).css('left', $col.position().left + $col.outerWidth(true))
256                    .show();
257                 if ($($firstRowCols[n]).hasClass('condition')) {
258                     $($resizeHandles[n]).addClass('condition');
259                     if (n > 0) {
260                         $($resizeHandles[n-1]).addClass('condition');
261                     }
262                 }
263             }
264             if ($($resizeHandles[0]).hasClass('condition')) {
265                 $('.pma_table').find('thead th:first').addClass('before-condition');
266             }
267             $(g.cRsz).css('height', $(g.t).height());
268         },
270         /**
271          * Shift column from index oldn to newn.
272          *
273          * @param oldn old zero-based column index
274          * @param newn new zero-based column index
275          */
276         shiftCol: function(oldn, newn) {
277             $(g.t).find('tr').each(function() {
278                 if (newn < oldn) {
279                     $(this).find('th.draggable:eq(' + newn + '),' +
280                                  'td:eq(' + (g.actionSpan + newn) + ')')
281                            .before($(this).find('th.draggable:eq(' + oldn + '),' +
282                                                 'td:eq(' + (g.actionSpan + oldn) + ')'));
283                 } else {
284                     $(this).find('th.draggable:eq(' + newn + '),' +
285                                  'td:eq(' + (g.actionSpan + newn) + ')')
286                            .after($(this).find('th.draggable:eq(' + oldn + '),' +
287                                                'td:eq(' + (g.actionSpan + oldn) + ')'));
288                 }
289             });
290             // reposition the column resize bars
291             g.reposRsz();
293             // adjust the column visibility list
294             if (newn < oldn) {
295                 $(g.cList).find('.lDiv div:eq(' + newn + ')')
296                           .before($(g.cList).find('.lDiv div:eq(' + oldn + ')'));
297             } else {
298                 $(g.cList).find('.lDiv div:eq(' + newn + ')')
299                           .after($(g.cList).find('.lDiv div:eq(' + oldn + ')'));
300             }
301             // adjust the colOrder
302             var tmp = g.colOrder[oldn];
303             g.colOrder.splice(oldn, 1);
304             g.colOrder.splice(newn, 0, tmp);
305             // adjust the colVisib
306             if (g.colVisib.length > 0) {
307                 var tmp = g.colVisib[oldn];
308                 g.colVisib.splice(oldn, 1);
309                 g.colVisib.splice(newn, 0, tmp);
310             }
311         },
313         /**
314          * Find currently hovered table column's header (excluding actions column).
315          *
316          * @param e event
317          * @return the hovered column's th object or undefined if no hovered column found.
318          */
319         getHoveredCol: function(e) {
320             var hoveredCol;
321             $headers = $(g.t).find('th.draggable:visible');
322             $headers.each(function() {
323                 var left = $(this).offset().left;
324                 var right = left + $(this).outerWidth();
325                 if (left <= e.pageX && e.pageX <= right) {
326                     hoveredCol = this;
327                 }
328             });
329             return hoveredCol;
330         },
332         /**
333          * Get a zero-based index from a <th class="draggable"> tag in a table.
334          *
335          * @param obj table header <th> object
336          * @return zero-based index of the specified table header in the set of table headers (visible or not)
337          */
338         getHeaderIdx: function(obj) {
339             return $(obj).parents('tr').find('th.draggable').index(obj);
340         },
342         /**
343          * Reposition the columns back to normal order.
344          */
345         restoreColOrder: function() {
346             // use insertion sort, since we already have shiftCol function
347             for (var i = 1; i < g.colOrder.length; i++) {
348                 var x = g.colOrder[i];
349                 var j = i - 1;
350                 while (j >= 0 && x < g.colOrder[j]) {
351                     j--;
352                 }
353                 if (j != i - 1) {
354                     g.shiftCol(i, j + 1);
355                 }
356             }
357             if (g.tableCreateTime) {
358                 // send request to server to remember the column order
359                 g.sendColPrefs();
360             }
361             g.refreshRestoreButton();
362         },
364         /**
365          * Send column preferences (column order and visibility) to the server.
366          */
367         sendColPrefs: function() {
368             if ($(g.t).is('.ajax')) {   // only send preferences if AjaxEnable is true
369                 var post_params = {
370                     ajax_request: true,
371                     db: g.db,
372                     table: g.table,
373                     token: g.token,
374                     server: g.server,
375                     set_col_prefs: true,
376                     table_create_time: g.tableCreateTime
377                 };
378                 if (g.colOrder.length > 0) {
379                     $.extend(post_params, { col_order: g.colOrder.toString() });
380                 }
381                 if (g.colVisib.length > 0) {
382                     $.extend(post_params, { col_visib: g.colVisib.toString() });
383                 }
384                 $.post('sql.php', post_params, function(data) {
385                     if (data.success != true) {
386                         var $temp_div = $(document.createElement('div'));
387                         $temp_div.html(data.error);
388                         $temp_div.addClass("error");
389                         PMA_ajaxShowMessage($temp_div, false);
390                     }
391                 });
392             }
393         },
395         /**
396          * Refresh restore button state.
397          * Make restore button disabled if the table is similar with initial state.
398          */
399         refreshRestoreButton: function() {
400             // check if table state is as initial state
401             var isInitial = true;
402             for (var i = 0; i < g.colOrder.length; i++) {
403                 if (g.colOrder[i] != i) {
404                     isInitial = false;
405                     break;
406                 }
407             }
408             // check if only one visible column left
409             var isOneColumn = g.visibleHeadersCount == 1;
410             // enable or disable restore button
411             if (isInitial || isOneColumn) {
412                 $('.restore_column').hide();
413             } else {
414                 $('.restore_column').show();
415             }
416         },
418         /**
419          * Update current hint using the boolean values (showReorderHint, showSortHint, etc.).
420          * It will hide the hint if all the boolean values is false.
421          *
422          * @param e event
423          */
424         updateHint: function(e) {
425             if (!g.colRsz && !g.colReorder) {     // if not resizing or dragging
426                 var text = '';
427                 if (g.showReorderHint && g.reorderHint) {
428                     text += g.reorderHint;
429                 }
430                 if (g.showSortHint && g.sortHint) {
431                     text += text.length > 0 ? '<br />' : '';
432                     text += g.sortHint;
433                 }
434                 if (g.showMarkHint && g.markHint &&
435                     !g.showSortHint      // we do not show mark hint, when sort hint is shown
436                 ) {
437                     text += text.length > 0 ? '<br />' : '';
438                     text += g.markHint;
439                 }
440                 if (g.showColVisibHint && g.colVisibHint) {
441                     text += text.length > 0 ? '<br />' : '';
442                     text += g.colVisibHint;
443                 }
445                 // hide the hint if no text and the event is mouseenter
446                 if (g.qtip) {
447                     g.qtip.disable(!text && e.type == 'mouseenter');
448                     g.qtip.updateContent(text, false);
449                 }
450             } else {
451                 g.hideHint();
452             }
453         },
455         hideHint: function() {
456             if (g.qtip) {
457                 g.qtip.hide();
458                 g.qtip.disable(true);
459             }
460         },
462         /**
463          * Toggle column's visibility.
464          * After calling this function and it returns true, afterToggleCol() must be called.
465          *
466          * @return boolean True if the column is toggled successfully.
467          */
468         toggleCol: function(n) {
469             if (g.colVisib[n]) {
470                 // can hide if more than one column is visible
471                 if (g.visibleHeadersCount > 1) {
472                     $(g.t).find('tr').each(function() {
473                         $(this).find('th.draggable:eq(' + n + '),' +
474                                      'td:eq(' + (g.actionSpan + n) + ')')
475                                .hide();
476                     });
477                     g.colVisib[n] = 0;
478                     $(g.cList).find('.lDiv div:eq(' + n + ') input').removeAttr('checked');
479                 } else {
480                     // cannot hide, force the checkbox to stay checked
481                     $(g.cList).find('.lDiv div:eq(' + n + ') input').attr('checked', 'checked');
482                     return false;
483                 }
484             } else {    // column n is not visible
485                 $(g.t).find('tr').each(function() {
486                     $(this).find('th.draggable:eq(' + n + '),' +
487                                  'td:eq(' + (g.actionSpan + n) + ')')
488                            .show();
489                 });
490                 g.colVisib[n] = 1;
491                 $(g.cList).find('.lDiv div:eq(' + n + ') input').attr('checked', 'checked');
492             }
493             return true;
494         },
496         /**
497          * This must be called if toggleCol() returns is true.
498          *
499          * This function is separated from toggleCol because, sometimes, we want to toggle
500          * some columns together at one time and do just one adjustment after it, e.g. in showAllColumns().
501          */
502         afterToggleCol: function() {
503             // some adjustments after hiding column
504             g.reposRsz();
505             g.reposDrop();
506             g.sendColPrefs();
508             // check visible first row headers count
509             g.visibleHeadersCount = $(g.t).find('tr:first th.draggable:visible').length;
510             g.refreshRestoreButton();
511         },
513         /**
514          * Show columns' visibility list.
515          *
516          * @param obj The drop down arrow of column visibility list
517          */
518         showColList: function(obj) {
519             // only show when not resizing or reordering
520             if (!g.colRsz && !g.colReorder) {
521                 var pos = $(obj).position();
522                 // check if the list position is too right
523                 if (pos.left + $(g.cList).outerWidth(true) > $(document).width()) {
524                     pos.left = $(document).width() - $(g.cList).outerWidth(true);
525                 }
526                 $(g.cList).css({
527                         left: pos.left,
528                         top: pos.top + $(obj).outerHeight(true)
529                     })
530                     .show();
531                 $(obj).addClass('coldrop-hover');
532             }
533         },
535         /**
536          * Hide columns' visibility list.
537          */
538         hideColList: function() {
539             $(g.cList).hide();
540             $(g.cDrop).find('.coldrop-hover').removeClass('coldrop-hover');
541         },
543         /**
544          * Reposition the column visibility drop-down arrow.
545          */
546         reposDrop: function() {
547             var $th = $(t).find('th:not(.draggable)');
548             for (var i = 0; i < $th.length; i++) {
549                 var $cd = $(g.cDrop).find('div:eq(' + i + ')');   // column drop-down arrow
550                 var pos = $($th[i]).position();
551                 $cd.css({
552                         left: pos.left + $($th[i]).width() - $cd.width(),
553                         top: pos.top
554                     });
555             }
556         },
558         /**
559          * Show all hidden columns.
560          */
561         showAllColumns: function() {
562             for (var i = 0; i < g.colVisib.length; i++) {
563                 if (!g.colVisib[i]) {
564                     g.toggleCol(i);
565                 }
566             }
567             g.afterToggleCol();
568         },
570         /**
571          * Show edit cell, if it can be shown
572          *
573          * @param cell <td> element to be edited
574          */
575         showEditCell: function(cell) {
576             if ($(cell).is('.grid_edit') &&
577                 !g.colRsz && !g.colReorder)
578             {
579                 if (!g.isCellEditActive) {
580                     var $cell = $(cell);
581                     // remove all edit area and hide it
582                     $(g.cEdit).find('.edit_area').empty().hide();
583                     // reposition the cEdit element
584                     $(g.cEdit).css({
585                             top: $cell.position().top,
586                             left: $cell.position().left
587                         })
588                         .show()
589                         .find('.edit_box')
590                         .css({
591                             width: $cell.outerWidth(),
592                             height: $cell.outerHeight()
593                         });
594                     // fill the cell edit with text from <td>
595                     var value = PMA_getCellValue(cell);
596                     $(g.cEdit).find('.edit_box').val(value);
598                     g.currentEditCell = cell;
599                     $(g.cEdit).find('.edit_box').focus();
600                     $(g.cEdit).find('*').removeAttr('disabled');
601                 }
602             }
603         },
605         /**
606          * Remove edit cell and the edit area, if it is shown.
607          *
608          * @param force Optional, force to hide edit cell without saving edited field.
609          * @param data  Optional, data from the POST AJAX request to save the edited field
610          *              or just specify "true", if we want to replace the edited field with the new value.
611          * @param field Optional, the edited <td>. If not specified, the function will
612          *              use currently edited <td> from g.currentEditCell.
613          */
614         hideEditCell: function(force, data, field) {
615             if (g.isCellEditActive && !force) {
616                 // cell is being edited, save or post the edited data
617                 g.saveOrPostEditedCell();
618                 return;
619             }
621             // cancel any previous request
622             if (g.lastXHR != null) {
623                 g.lastXHR.abort();
624                 g.lastXHR = null;
625             }
627             if (data) {
628                 if (g.currentEditCell) {    // save value of currently edited cell
629                     // replace current edited field with the new value
630                     var $this_field = $(g.currentEditCell);
631                     var is_null = $this_field.data('value') == null;
632                     if (is_null) {
633                         $this_field.find('span').html('NULL');
634                         $this_field.addClass('null');
635                     } else {
636                         $this_field.removeClass('null');
637                         var new_html = $this_field.data('value');
638                         if ($this_field.is('.truncated')) {
639                             if (new_html.length > g.maxTruncatedLen) {
640                                 new_html = new_html.substring(0, g.maxTruncatedLen) + '...';
641                             }
642                         }
643                         $this_field.find('span').text(new_html);
644                     }
645                 }
646                 if (data.transformations != undefined) {
647                     $.each(data.transformations, function(cell_index, value) {
648                         var $this_field = $(g.t).find('.to_be_saved:eq(' + cell_index + ')');
649                         $this_field.find('span').html(value);
650                     });
651                 }
652                 if (data.relations != undefined) {
653                     $.each(data.relations, function(cell_index, value) {
654                         var $this_field = $(g.t).find('.to_be_saved:eq(' + cell_index + ')');
655                         $this_field.find('span').html(value);
656                     });
657                 }
659                 // refresh the grid
660                 g.reposRsz();
661                 g.reposDrop();
662             }
664             // hide the cell editing area
665             $(g.cEdit).hide();
666             $(g.cEdit).find('.edit_box').blur();
667             g.isCellEditActive = false;
668             g.currentEditCell = null;
669             // destroy datepicker in edit area, if exist
670             var $dp = $(g.cEdit).find('.hasDatepicker');
671             if ($dp.length > 0) {
672                 $dp.datepicker('destroy');
673                 // change the cursor in edit box back to normal
674                 // (the cursor become a hand pointer when we add datepicker)
675                 $(g.cEdit).find('.edit_box').css('cursor', 'inherit');
676             }
677         },
679         /**
680          * Show drop-down edit area when edit cell is focused.
681          */
682         showEditArea: function() {
683             if (!g.isCellEditActive) {   // make sure the edit area has not been shown
684                 g.isCellEditActive = true;
685                 g.isEditCellTextEditable = false;
686                 /**
687                  * @var $td current edited cell
688                  */
689                 var $td = $(g.currentEditCell);
690                 /**
691                  * @var $editArea the editing area
692                  */
693                 var $editArea = $(g.cEdit).find('.edit_area');
694                 /**
695                  * @var where_clause WHERE clause for the edited cell
696                  */
697                 var where_clause = $td.parent('tr').find('.where_clause').val();
698                 /**
699                  * @var field_name  String containing the name of this field.
700                  * @see getFieldName()
701                  */
702                 var field_name = getFieldName($td);
703                 /**
704                  * @var relation_curr_value String current value of the field (for fields that are foreign keyed).
705                  */
706                 var relation_curr_value = $td.text();
707                 /**
708                  * @var relation_key_or_display_column String relational key if in 'Relational display column' mode,
709                  * relational display column if in 'Relational key' mode (for fields that are foreign keyed).
710                  */
711                 var relation_key_or_display_column = $td.find('a').attr('title');
712                 /**
713                  * @var curr_value String current value of the field (for fields that are of type enum or set).
714                  */
715                 var curr_value = $td.find('span').text();
717                 // empty all edit area, then rebuild it based on $td classes
718                 $editArea.empty();
720                 // add goto link, if this cell contains a link
721                 if ($td.find('a').length > 0) {
722                     var gotoLink = document.createElement('div');
723                     gotoLink.className = 'goto_link';
724                     $(gotoLink).append(g.gotoLinkText + ': ')
725                         .append($td.find('a').clone());
726                     $editArea.append(gotoLink);
727                 }
729                 g.wasEditedCellNull = false;
730                 if ($td.is(':not(.not_null)')) {
731                     // append a null checkbox
732                     $editArea.append('<div class="null_div">Null :<input type="checkbox"></div>');
733                     var $checkbox = $editArea.find('.null_div input');
734                     // check if current <td> is NULL
735                     if ($td.is('.null')) {
736                         $checkbox.attr('checked', true);
737                         g.wasEditedCellNull = true;
738                     }
740                     // if the select/editor is changed un-check the 'checkbox_null_<field_name>_<row_index>'.
741                     if ($td.is('.enum, .set')) {
742                         $editArea.find('select').live('change', function(e) {
743                             $checkbox.attr('checked', false);
744                         });
745                     } else if ($td.is('.relation')) {
746                         $editArea.find('select').live('change', function(e) {
747                             $checkbox.attr('checked', false);
748                         });
749                         $editArea.find('.browse_foreign').live('click', function(e) {
750                             $checkbox.attr('checked', false);
751                         });
752                     } else {
753                         $(g.cEdit).find('.edit_box').live('keypress change', function(e) {
754                             $checkbox.attr('checked', false);
755                         });
756                         // Capture ctrl+v (on IE and Chrome)
757                         $(g.cEdit).find('.edit_box').live('keydown', function(e) {
758                             if (e.ctrlKey && e.which == 86) {
759                                 $checkbox.prop('checked', false);
760                             }
761                         });
762                         $editArea.find('textarea').live('keydown', function(e) {
763                             $checkbox.attr('checked', false);
764                         });
765                     }
767                     // if null checkbox is clicked empty the corresponding select/editor.
768                     $checkbox.click(function(e) {
769                         if ($td.is('.enum')) {
770                             $editArea.find('select').attr('value', '');
771                         } else if ($td.is('.set')) {
772                             $editArea.find('select').find('option').each(function() {
773                                 var $option = $(this);
774                                 $option.attr('selected', false);
775                             });
776                         } else if ($td.is('.relation')) {
777                             // if the dropdown is there to select the foreign value
778                             if ($editArea.find('select').length > 0) {
779                                 $editArea.find('select').attr('value', '');
780                             }
781                         } else {
782                             $editArea.find('textarea').val('');
783                         }
784                         $(g.cEdit).find('.edit_box').val('');
785                     });
786                 }
788                 if ($td.is('.relation')) {
789                     //handle relations
790                     $editArea.addClass('edit_area_loading');
792                     // initialize the original data
793                     $td.data('original_data', null);
795                     /**
796                      * @var post_params Object containing parameters for the POST request
797                      */
798                     var post_params = {
799                         'ajax_request' : true,
800                         'get_relational_values' : true,
801                         'server' : g.server,
802                         'db' : g.db,
803                         'table' : g.table,
804                         'column' : field_name,
805                         'token' : g.token,
806                         'curr_value' : relation_curr_value,
807                         'relation_key_or_display_column' : relation_key_or_display_column
808                     };
810                     g.lastXHR = $.post('sql.php', post_params, function(data) {
811                         g.lastXHR = null;
812                         $editArea.removeClass('edit_area_loading');
813                         if ($(data.dropdown).is('select')) {
814                             // save original_data
815                             var value = $(data.dropdown).val();
816                             $td.data('original_data', value);
817                             // update the text input field, in case where the "Relational display column" is checked
818                             $(g.cEdit).find('.edit_box').val(value);
819                         }
821                         $editArea.append(data.dropdown);
822                         $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
823                     }); // end $.post()
825                     $editArea.show();
826                     $editArea.find('select').live('change', function(e) {
827                         $(g.cEdit).find('.edit_box').val($(this).val());
828                     });
829                 }
830                 else if($td.is('.enum')) {
831                     //handle enum fields
832                     $editArea.addClass('edit_area_loading');
834                     /**
835                      * @var post_params Object containing parameters for the POST request
836                      */
837                     var post_params = {
838                             'ajax_request' : true,
839                             'get_enum_values' : true,
840                             'server' : g.server,
841                             'db' : g.db,
842                             'table' : g.table,
843                             'column' : field_name,
844                             'token' : g.token,
845                             'curr_value' : curr_value
846                     };
847                     g.lastXHR = $.post('sql.php', post_params, function(data) {
848                         g.lastXHR = null;
849                         $editArea.removeClass('edit_area_loading');
850                         $editArea.append(data.dropdown);
851                         $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
852                     }); // end $.post()
854                     $editArea.show();
855                     $editArea.find('select').live('change', function(e) {
856                         $(g.cEdit).find('.edit_box').val($(this).val());
857                     });
858                 }
859                 else if($td.is('.set')) {
860                     //handle set fields
861                     $editArea.addClass('edit_area_loading');
863                     /**
864                      * @var post_params Object containing parameters for the POST request
865                      */
866                     var post_params = {
867                             'ajax_request' : true,
868                             'get_set_values' : true,
869                             'server' : g.server,
870                             'db' : g.db,
871                             'table' : g.table,
872                             'column' : field_name,
873                             'token' : g.token,
874                             'curr_value' : curr_value
875                     };
877                     g.lastXHR = $.post('sql.php', post_params, function(data) {
878                         g.lastXHR = null;
879                         $editArea.removeClass('edit_area_loading');
880                         $editArea.append(data.select);
881                         $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
882                     }); // end $.post()
884                     $editArea.show();
885                     $editArea.find('select').live('change', function(e) {
886                         $(g.cEdit).find('.edit_box').val($(this).val());
887                     });
888                 }
889                 else if($td.is('.truncated, .transformed')) {
890                     if ($td.is('.to_be_saved')) {   // cell has been edited
891                         var value = $td.data('value');
892                         $(g.cEdit).find('.edit_box').val(value);
893                         $editArea.append('<textarea></textarea>');
894                         $editArea.find('textarea')
895                             .val(value)
896                             .live('keyup', function(e) {
897                                 $(g.cEdit).find('.edit_box').val($(this).val());
898                             });
899                         $(g.cEdit).find('.edit_box').live('keyup', function(e) {
900                             $editArea.find('textarea').val($(this).val());
901                         });
902                         $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
903                     } else {
904                         //handle truncated/transformed values values
905                         $editArea.addClass('edit_area_loading');
907                         // initialize the original data
908                         $td.data('original_data', null);
910                         /**
911                          * @var sql_query   String containing the SQL query used to retrieve value of truncated/transformed data
912                          */
913                         var sql_query = 'SELECT `' + field_name + '` FROM `' + g.table + '` WHERE ' + PMA_urldecode(where_clause);
915                         // Make the Ajax call and get the data, wrap it and insert it
916                         g.lastXHR = $.post('sql.php', {
917                             'token' : g.token,
918                             'server' : g.server,
919                             'db' : g.db,
920                             'ajax_request' : true,
921                             'sql_query' : sql_query,
922                             'grid_edit' : true
923                         }, function(data) {
924                             g.lastXHR = null;
925                             $editArea.removeClass('edit_area_loading');
926                             if(data.success == true) {
927                                 if ($td.is('.truncated')) {
928                                     // get the truncated data length
929                                     g.maxTruncatedLen = $(g.currentEditCell).text().length - 3;
930                                 }
932                                 $td.data('original_data', data.value);
933                                 $(g.cEdit).find('.edit_box').val(data.value);
934                                 $editArea.append('<textarea></textarea>');
935                                 $editArea.find('textarea')
936                                     .val(data.value)
937                                     .live('keyup', function(e) {
938                                         $(g.cEdit).find('.edit_box').val($(this).val());
939                                     });
940                                 $(g.cEdit).find('.edit_box').live('keyup', function(e) {
941                                     $editArea.find('textarea').val($(this).val());
942                                 });
943                                 $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
944                             }
945                             else {
946                                 PMA_ajaxShowMessage(data.error, false);
947                             }
948                         }); // end $.post()
949                         $editArea.show();
950                     }
951                     g.isEditCellTextEditable = true;
952                 } else if ($td.is('.datefield, .datetimefield, .timestampfield')) {
953                     var $input_field = $(g.cEdit).find('.edit_box');
954                     
955                     // remember current datetime value in $input_field, if it is not null
956                     var is_null = $td.is('.null');
957                     var current_datetime_value = !is_null ? $input_field.val() : '';
958                     
959                     var showTimeOption = true;
960                     if ($td.is('.datefield')) {
961                         showTimeOption = false;
962                     }
963                     PMA_addDatepicker($editArea, {
964                         altField: $input_field,
965                         showTimepicker: showTimeOption,
966                         onSelect: function(dateText, inst) {
967                             // remove null checkbox if it exists
968                             $(g.cEdit).find('.null_div input[type=checkbox]').attr('checked', false);
969                         }
970                     });
971                     
972                     // cancel any click on the datepicker element
973                     $editArea.find('> *').click(function(e) {
974                         e.stopPropagation();
975                     });
976                     
977                     // force to restore modified $input_field value after adding datepicker
978                     // (after adding a datepicker, the input field doesn't display the time anymore, only the date)
979                     if (is_null 
980                         || current_datetime_value == '0000-00-00' 
981                         || current_datetime_value == '0000-00-00 00:00:00'
982                     ) {
983                         $input_field.val(current_datetime_value);
984                     } else {
985                         $editArea.datetimepicker('setDate', current_datetime_value);                        
986                     }
987                     $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
989                     // remove {cursor: 'pointer'} added inside timepicker.js
990                     $input_field.css('cursor', '');
991                     // make the cell editable, so one can can bypass the timepicker
992                     // and enter date/time value manually
993                     g.isEditCellTextEditable = true;
994                 } else {
995                     g.isEditCellTextEditable = true;
996                     // only append edit area hint if there is a null checkbox
997                     if ($editArea.children().length > 0) {
998                         $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
999                     }
1000                 }
1001                 if ($editArea.children().length > 0) {
1002                     $editArea.show();
1003                 }
1004             }
1005         },
1007         /**
1008          * Post the content of edited cell.
1009          */
1010         postEditedCell: function() {
1011             if (g.isSaving) {
1012                 return;
1013             }
1014             g.isSaving = true;
1016             /**
1017              * @var relation_fields Array containing the name/value pairs of relational fields
1018              */
1019             var relation_fields = {};
1020             /**
1021              * @var relational_display string 'K' if relational key, 'D' if relational display column
1022              */
1023             var relational_display = $("#relational_display_K").attr('checked') ? 'K' : 'D';
1024             /**
1025              * @var transform_fields    Array containing the name/value pairs for transformed fields
1026              */
1027             var transform_fields = {};
1028             /**
1029              * @var transformation_fields   Boolean, if there are any transformed fields in the edited cells
1030              */
1031             var transformation_fields = false;
1032             /**
1033              * @var full_sql_query String containing the complete SQL query to update this table
1034              */
1035             var full_sql_query = '';
1036             /**
1037              * @var rel_fields_list  String, url encoded representation of {@link relations_fields}
1038              */
1039             var rel_fields_list = '';
1040             /**
1041              * @var transform_fields_list  String, url encoded representation of {@link transform_fields}
1042              */
1043             var transform_fields_list = '';
1044             /**
1045              * @var where_clause Array containing where clause for updated fields
1046              */
1047             var full_where_clause = Array();
1048             /**
1049              * @var is_unique   Boolean, whether the rows in this table is unique or not
1050              */
1051             var is_unique = $('.edit_row_anchor').is('.nonunique') ? 0 : 1;
1052             /**
1053              * multi edit variables
1054              */
1055             var me_fields_name = Array();
1056             var me_fields = Array();
1057             var me_fields_null = Array();
1059             // alert user if edited table is not unique
1060             if (!is_unique) {
1061                 alert(g.alertNonUnique);
1062             }
1064             // loop each edited row
1065             $('.to_be_saved').parents('tr').each(function() {
1066                 var $tr = $(this);
1067                 var where_clause = $tr.find('.where_clause').val();
1068                 full_where_clause.push(PMA_urldecode(where_clause));
1069                 var condition_array = jQuery.parseJSON($tr.find('.condition_array').val());
1071                 /**
1072                  * multi edit variables, for current row
1073                  * @TODO array indices are still not correct, they should be md5 of field's name
1074                  */
1075                 var fields_name = Array();
1076                 var fields = Array();
1077                 var fields_null = Array();
1079                 // loop each edited cell in a row
1080                 $tr.find('.to_be_saved').each(function() {
1081                     /**
1082                      * @var $this_field    Object referring to the td that is being edited
1083                      */
1084                     var $this_field = $(this);
1086                     /**
1087                      * @var field_name  String containing the name of this field.
1088                      * @see getFieldName()
1089                      */
1090                     var field_name = getFieldName($this_field);
1092                     /**
1093                      * @var this_field_params   Array temporary storage for the name/value of current field
1094                      */
1095                     var this_field_params = {};
1097                     if($this_field.is('.transformed')) {
1098                         transformation_fields =  true;
1099                     }
1100                     this_field_params[field_name] = $this_field.data('value');
1102                     /**
1103                      * @var is_null String capturing whether 'checkbox_null_<field_name>_<row_index>' is checked.
1104                      */
1105                     var is_null = this_field_params[field_name] === null;
1107                     fields_name.push(field_name);
1109                     if (is_null) {
1110                         fields_null.push('on');
1111                         fields.push('');
1112                     } else {
1113                         fields_null.push('');
1114                         fields.push($this_field.data('value'));
1116                         var cell_index = $this_field.index('.to_be_saved');
1117                         if($this_field.is(":not(.relation, .enum, .set, .bit)")) {
1118                             if($this_field.is('.transformed')) {
1119                                 transform_fields[cell_index] = {};
1120                                 $.extend(transform_fields[cell_index], this_field_params);
1121                             }
1122                         } else if($this_field.is('.relation')) {
1123                             relation_fields[cell_index] = {};
1124                             $.extend(relation_fields[cell_index], this_field_params);
1125                         }
1126                     }
1127                     // check if edited field appears in WHERE clause
1128                     if (where_clause.indexOf(PMA_urlencode(field_name)) > -1) {
1129                         var field_str = '`' + g.table + '`.' + '`' + field_name + '`';
1130                         for (var field in condition_array) {
1131                             if (field.indexOf(field_str) > -1) {
1132                                 condition_array[field] = is_null ? 'IS NULL' : "= '" + this_field_params[field_name].replace(/'/g,"''") + "'";
1133                                 break;
1134                             }
1135                         }
1136                     }
1138                 }); // end of loop for every edited cells in a row
1140                 // save new_clause
1141                 var new_clause = '';
1142                 for (var field in condition_array) {
1143                     new_clause += field + ' ' + condition_array[field] + ' AND ';
1144                 }
1145                 new_clause = new_clause.substring(0, new_clause.length - 5); // remove the last AND
1146                 new_clause = PMA_urlencode(new_clause);
1147                 $tr.data('new_clause', new_clause);
1148                 // save condition_array
1149                 $tr.find('.condition_array').val(JSON.stringify(condition_array));
1151                 me_fields_name.push(fields_name);
1152                 me_fields.push(fields);
1153                 me_fields_null.push(fields_null);
1155             }); // end of loop for every edited rows
1157             rel_fields_list = $.param(relation_fields);
1158             transform_fields_list = $.param(transform_fields);
1160             // Make the Ajax post after setting all parameters
1161             /**
1162              * @var post_params Object containing parameters for the POST request
1163              */
1164             var post_params = {'ajax_request' : true,
1165                             'sql_query' : full_sql_query,
1166                             'token' : g.token,
1167                             'server' : g.server,
1168                             'db' : g.db,
1169                             'table' : g.table,
1170                             'clause_is_unique' : is_unique,
1171                             'where_clause' : full_where_clause,
1172                             'fields[multi_edit]' : me_fields,
1173                             'fields_name[multi_edit]' : me_fields_name,
1174                             'fields_null[multi_edit]' : me_fields_null,
1175                             'rel_fields_list' : rel_fields_list,
1176                             'do_transformations' : transformation_fields,
1177                             'transform_fields_list' : transform_fields_list,
1178                             'relational_display' : relational_display,
1179                             'goto' : 'sql.php',
1180                             'submit_type' : 'save'
1181                           };
1183             if (!g.saveCellsAtOnce) {
1184                 $(g.cEdit).find('*').attr('disabled', 'disabled');
1185                 var $editArea = $(g.cEdit).find('.edit_area');
1186                 $(g.cEdit).find('.edit_box').addClass('edit_box_posting');
1187             } else {
1188                 $('.save_edited').addClass('saving_edited_data')
1189                     .find('input').attr('disabled', 'disabled');    // disable the save button
1190             }
1192             $.ajax({
1193                 type: 'POST',
1194                 url: 'tbl_replace.php',
1195                 data: post_params,
1196                 success:
1197                     function(data) {
1198                         g.isSaving = false;
1199                         if (!g.saveCellsAtOnce) {
1200                             $(g.cEdit).find('*').removeAttr('disabled');
1201                             $(g.cEdit).find('.edit_box').removeClass('edit_box_posting');
1202                         } else {
1203                             $('.save_edited').removeClass('saving_edited_data')
1204                                 .find('input').removeAttr('disabled');  // enable the save button back
1205                         }
1206                         if(data.success == true) {
1207                             PMA_ajaxShowMessage(data.message);
1208                             // update where_clause related data in each edited row
1209                             $('.to_be_saved').parents('tr').each(function() {
1210                                 var new_clause = $(this).data('new_clause');
1211                                 var $where_clause = $(this).find('.where_clause');
1212                                 var old_clause = $where_clause.attr('value');
1213                                 var decoded_old_clause = PMA_urldecode(old_clause);
1214                                 var decoded_new_clause = PMA_urldecode(new_clause);
1216                                 $where_clause.attr('value', new_clause);
1217                                 // update Edit, Copy, and Delete links also
1218                                 $(this).find('a').each(function() {
1219                                     $(this).attr('href', $(this).attr('href').replace(old_clause, new_clause));
1220                                     // update delete confirmation in Delete link
1221                                     if ($(this).attr('href').indexOf('DELETE') > -1) {
1222                                         $(this).removeAttr('onclick')
1223                                             .unbind('click')
1224                                             .bind('click', function() {
1225                                                 return confirmLink(this, 'DELETE FROM `' + g.db + '`.`' + g.table + '` WHERE ' +
1226                                                        decoded_new_clause + (is_unique ? '' : ' LIMIT 1'));
1227                                             });
1228                                     }
1229                                 });
1230                                 // update the multi edit checkboxes
1231                                 $(this).find('input[type=checkbox]').each(function() {
1232                                     var $checkbox = $(this);
1233                                     var checkbox_name = $checkbox.attr('name');
1234                                     var checkbox_value = $checkbox.attr('value');
1236                                     $checkbox.attr('name', checkbox_name.replace(old_clause, new_clause));
1237                                     $checkbox.attr('value', checkbox_value.replace(decoded_old_clause, decoded_new_clause));
1238                                 });
1239                             });
1240                             // update the display of executed SQL query command
1241                             $('#result_query').remove();
1242                             if (typeof data.sql_query != 'undefined') {
1243                                 // display feedback
1244                                 $('#sqlqueryresults').prepend(data.sql_query);
1245                             }
1246                             // hide and/or update the successfully saved cells
1247                             g.hideEditCell(true, data);
1249                             // remove the "Save edited cells" button
1250                             $('.save_edited').hide();
1251                             // update saved fields
1252                             $(g.t).find('.to_be_saved')
1253                                 .removeClass('to_be_saved')
1254                                 .data('value', null)
1255                                 .data('original_data', null);
1257                             g.isCellEdited = false;
1258                         } else {
1259                             PMA_ajaxShowMessage(data.error, false);
1260                         }
1261                     }
1262             }); // end $.ajax()
1263         },
1265         /**
1266          * Save edited cell, so it can be posted later.
1267          */
1268         saveEditedCell: function() {
1269             /**
1270              * @var $this_field    Object referring to the td that is being edited
1271              */
1272             var $this_field = $(g.currentEditCell);
1273             var $test_element = ''; // to test the presence of a element
1275             var need_to_post = false;
1277             /**
1278              * @var field_name  String containing the name of this field.
1279              * @see getFieldName()
1280              */
1281             var field_name = getFieldName($this_field);
1283             /**
1284              * @var this_field_params   Array temporary storage for the name/value of current field
1285              */
1286             var this_field_params = {};
1288             /**
1289              * @var is_null String capturing whether 'checkbox_null_<field_name>_<row_index>' is checked.
1290              */
1291             var is_null = $(g.cEdit).find('input:checkbox').is(':checked');
1292             var value;
1294             if ($(g.cEdit).find('.edit_area').is('.edit_area_loading')) {
1295                 // the edit area is still loading (retrieving cell data), no need to post
1296                 need_to_post = false;
1297             } else if (is_null) {
1298                 if (!g.wasEditedCellNull) {
1299                     this_field_params[field_name] = null;
1300                     need_to_post = true;
1301                 }
1302             } else {
1303                 if ($this_field.is('.bit')) {
1304                     this_field_params[field_name] = '0b' + $(g.cEdit).find('.edit_box').val();
1305                 } else if ($this_field.is('.set')) {
1306                     $test_element = $(g.cEdit).find('select');
1307                     this_field_params[field_name] = $test_element.map(function(){
1308                         return $(this).val();
1309                     }).get().join(",");
1310                 } else if ($this_field.is('.relation, .enum')) {
1311                     // results from a drop-down
1312                     $test_element = $(g.cEdit).find('select');
1313                     if ($test_element.length != 0) {
1314                         this_field_params[field_name] = $test_element.val();
1315                     }
1317                     // results from Browse foreign value
1318                     $test_element = $(g.cEdit).find('span.curr_value');
1319                     if ($test_element.length != 0) {
1320                         this_field_params[field_name] = $test_element.text();
1321                     }
1322                 } else {
1323                     this_field_params[field_name] = $(g.cEdit).find('.edit_box').val();
1324                 }
1325                 if (g.wasEditedCellNull || this_field_params[field_name] != PMA_getCellValue(g.currentEditCell)) {
1326                     need_to_post = true;
1327                 }
1328             }
1330             if (need_to_post) {
1331                 $(g.currentEditCell).addClass('to_be_saved')
1332                     .data('value', this_field_params[field_name]);
1333                 if (g.saveCellsAtOnce) {
1334                     $('.save_edited').show();
1335                 }
1336                 g.isCellEdited = true;
1337             }
1339             return need_to_post;
1340         },
1342         /**
1343          * Save or post currently edited cell, depending on the "saveCellsAtOnce" configuration.
1344          */
1345         saveOrPostEditedCell: function() {
1346             var saved = g.saveEditedCell();
1347             if (!g.saveCellsAtOnce) {
1348                 if (saved) {
1349                     g.postEditedCell();
1350                 } else {
1351                     g.hideEditCell(true);
1352                 }
1353             } else {
1354                 if (saved) {
1355                     g.hideEditCell(true, true);
1356                 } else {
1357                     g.hideEditCell(true);
1358                 }
1359             }
1360         },
1362         /**
1363          * Initialize column resize feature.
1364          */
1365         initColResize: function() {
1366             // create column resizer div
1367             g.cRsz = document.createElement('div');
1368             g.cRsz.className = 'cRsz';
1370             // get data columns in the first row of the table
1371             var $firstRowCols = $(g.t).find('tr:first th.draggable');
1373             // create column borders
1374             $firstRowCols.each(function() {
1375                 var cb = document.createElement('div'); // column border
1376                 $(cb).addClass('colborder')
1377                     .mousedown(function(e) {
1378                         g.dragStartRsz(e, this);
1379                     });
1380                 $(g.cRsz).append(cb);
1381             });
1382             g.reposRsz();
1384             // attach to global div
1385             $(g.gDiv).prepend(g.cRsz);
1386         },
1388         /**
1389          * Initialize column reordering feature.
1390          */
1391         initColReorder: function() {
1392             g.cCpy = document.createElement('div');     // column copy, to store copy of dragged column header
1393             g.cPointer = document.createElement('div'); // column pointer, used when reordering column
1395             // adjust g.cCpy
1396             g.cCpy.className = 'cCpy';
1397             $(g.cCpy).hide();
1399             // adjust g.cPointer
1400             g.cPointer.className = 'cPointer';
1401             $(g.cPointer).css('visibility', 'hidden');  // set visibility to hidden instead of calling hide() to force browsers to cache the image in cPointer class
1403             // assign column reordering hint
1404             g.reorderHint = PMA_messages['strColOrderHint'];
1406             // get data columns in the first row of the table
1407             var $firstRowCols = $(g.t).find('tr:first th.draggable');
1409             // initialize column order
1410             $col_order = $('#col_order');   // check if column order is passed from PHP
1411             if ($col_order.length > 0) {
1412                 g.colOrder = $col_order.val().split(',');
1413                 for (var i = 0; i < g.colOrder.length; i++) {
1414                     g.colOrder[i] = parseInt(g.colOrder[i]);
1415                 }
1416             } else {
1417                 g.colOrder = new Array();
1418                 for (var i = 0; i < $firstRowCols.length; i++) {
1419                     g.colOrder.push(i);
1420                 }
1421             }
1423             // register events
1424             $(t).find('th.draggable')
1425                 .mousedown(function(e) {
1426                     if (g.visibleHeadersCount > 1) {
1427                         g.dragStartReorder(e, this);
1428                     }
1429                 })
1430                 .mouseenter(function(e) {
1431                     if (g.visibleHeadersCount > 1) {
1432                         g.showReorderHint = true;
1433                         $(this).css('cursor', 'move');
1434                     } else {
1435                         $(this).css('cursor', 'inherit');
1436                     }
1437                 })
1438                 .mouseleave(function(e) {
1439                     g.showReorderHint = false;
1440                 });
1441             // restore column order when the restore button is clicked
1442             $('.restore_column').click(function() {
1443                 g.restoreColOrder();
1444             });
1446             // attach to global div
1447             $(g.gDiv).append(g.cPointer);
1448             $(g.gDiv).append(g.cCpy);
1450             // prevent default "dragstart" event when dragging a link
1451             $(t).find('th a').bind('dragstart', function() {
1452                 return false;
1453             });
1455             // refresh the restore column button state
1456             g.refreshRestoreButton();
1457         },
1459         /**
1460          * Initialize column visibility feature.
1461          */
1462         initColVisib: function() {
1463             g.cDrop = document.createElement('div');    // column drop-down arrows
1464             g.cList = document.createElement('div');    // column visibility list
1466             // adjust g.cDrop
1467             g.cDrop.className = 'cDrop';
1469             // adjust g.cList
1470             g.cList.className = 'cList';
1471             $(g.cList).hide();
1473             // assign column visibility related hints
1474             g.colVisibHint = PMA_messages['strColVisibHint'];
1475             g.showAllColText = PMA_messages['strShowAllCol'];
1477             // get data columns in the first row of the table
1478             var $firstRowCols = $(g.t).find('tr:first th.draggable');
1480             // initialize column visibility
1481             var $col_visib = $('#col_visib');   // check if column visibility is passed from PHP
1482             if ($col_visib.length > 0) {
1483                 g.colVisib = $col_visib.val().split(',');
1484                 for (var i = 0; i < g.colVisib.length; i++) {
1485                     g.colVisib[i] = parseInt(g.colVisib[i]);
1486                 }
1487             } else {
1488                 g.colVisib = new Array();
1489                 for (var i = 0; i < $firstRowCols.length; i++) {
1490                     g.colVisib.push(1);
1491                 }
1492             }
1494             // make sure we have more than one column
1495             if ($firstRowCols.length > 1) {
1496                 var $colVisibTh = $(g.t).find('th:not(.draggable)');
1497                 PMA_createqTip($colVisibTh);
1499                 // create column visibility drop-down arrow(s)
1500                 $colVisibTh.each(function() {
1501                         var $th = $(this);
1502                         var cd = document.createElement('div'); // column drop-down arrow
1503                         var pos = $th.position();
1504                         $(cd).addClass('coldrop')
1505                             .click(function() {
1506                                 if (g.cList.style.display == 'none') {
1507                                     g.showColList(this);
1508                                 } else {
1509                                     g.hideColList();
1510                                 }
1511                             });
1512                         $(g.cDrop).append(cd);
1513                     })
1514                     .mouseenter(function(e) {
1515                         g.showColVisibHint = true;
1516                     })
1517                     .mouseleave(function(e) {
1518                         g.showColVisibHint = false;
1519                     });
1521                 // add column visibility control
1522                 g.cList.innerHTML = '<div class="lDiv"></div>';
1523                 var $listDiv = $(g.cList).find('div');
1524                 for (var i = 0; i < $firstRowCols.length; i++) {
1525                     var currHeader = $firstRowCols[i];
1526                     var listElmt = document.createElement('div');
1527                     $(listElmt).text($(currHeader).text())
1528                         .prepend('<input type="checkbox" ' + (g.colVisib[i] ? 'checked="checked" ' : '') + '/>');
1529                     $listDiv.append(listElmt);
1530                     // add event on click
1531                     $(listElmt).click(function() {
1532                         if ( g.toggleCol($(this).index()) ) {
1533                             g.afterToggleCol();
1534                         }
1535                     });
1536                 }
1537                 // add "show all column" button
1538                 var showAll = document.createElement('div');
1539                 $(showAll).addClass('showAllColBtn')
1540                     .text(g.showAllColText);
1541                 $(g.cList).append(showAll);
1542                 $(showAll).click(function() {
1543                     g.showAllColumns();
1544                 });
1545                 // prepend "show all column" button at top if the list is too long
1546                 if ($firstRowCols.length > 10) {
1547                     var clone = showAll.cloneNode(true);
1548                     $(g.cList).prepend(clone);
1549                     $(clone).click(function() {
1550                         g.showAllColumns();
1551                     });
1552                 }
1553             }
1555             // hide column visibility list if we move outside the list
1556             $(t).find('td, th.draggable').mouseenter(function() {
1557                 g.hideColList();
1558             });
1560             // attach to global div
1561             $(g.gDiv).append(g.cDrop);
1562             $(g.gDiv).append(g.cList);
1564             // some adjustment
1565             g.reposDrop();
1566         },
1568         /**
1569          * Initialize grid editing feature.
1570          */
1571         initGridEdit: function() {
1572             // create cell edit wrapper element
1573             g.cEdit = document.createElement('div');
1575             // adjust g.cEdit
1576             g.cEdit.className = 'cEdit';
1577             $(g.cEdit).html('<textarea class="edit_box" rows="1" ></textarea><div class="edit_area" />');
1578             $(g.cEdit).hide();
1580             // assign cell editing hint
1581             g.cellEditHint = PMA_messages['strCellEditHint'];
1582             g.saveCellWarning = PMA_messages['strSaveCellWarning'];
1583             g.alertNonUnique = PMA_messages['strAlertNonUnique'];
1584             g.gotoLinkText = PMA_messages['strGoToLink'];
1586             // initialize cell editing configuration
1587             g.saveCellsAtOnce = $('#save_cells_at_once').val();
1589             // register events
1590             $(t).find('td.data')
1591                 .click(function(e) {
1592                     if (g.isCellEditActive) {
1593                         g.saveOrPostEditedCell();
1594                         e.stopPropagation();
1595                     } else {
1596                         g.showEditCell(this);
1597                         e.stopPropagation();
1598                     }
1599                     // prevent default action when clicking on "link" in a table
1600                     if ($(e.target).is('.grid_edit a')) {
1601                         e.preventDefault();
1602                     }
1603                 });
1604             $(g.cEdit).find('.edit_box').focus(function(e) {
1605                 g.showEditArea();
1606             });
1607             $(g.cEdit).find('.edit_box, select').live('keydown', function(e) {
1608                 if (e.which == 13) {
1609                     // post on pressing "Enter"
1610                     e.preventDefault();
1611                     g.saveOrPostEditedCell();
1612                 }
1613             });
1614             $(g.cEdit).keydown(function(e) {
1615                 if (!g.isEditCellTextEditable) {
1616                     // prevent text editing
1617                     e.preventDefault();
1618                 }
1619             });
1620             $('html').click(function(e) {
1621                 // hide edit cell if the click is not from g.cEdit
1622                 if ($(e.target).parents().index(g.cEdit) == -1) {
1623                     g.hideEditCell();
1624                 }
1625             });
1626             $('html').keydown(function(e) {
1627                 if (e.which == 27 && g.isCellEditActive) {
1629                     // cancel on pressing "Esc"
1630                     g.hideEditCell(true);
1631                 }
1632             });
1633             $('.save_edited').click(function() {
1634                 g.hideEditCell();
1635                 g.postEditedCell();
1636             });
1637             $(window).bind('beforeunload', function(e) {
1638                 if (g.isCellEdited) {
1639                     return g.saveCellWarning;
1640                 }
1641             });
1643             // attach to global div
1644             $(g.gDiv).append(g.cEdit);
1646             // add hint for grid editing feature when hovering "Edit" link in each table row
1647             PMA_createqTip($(g.t).find('.edit_row_anchor a'), PMA_messages['strGridEditFeatureHint']);
1648         }
1649     };
1651     /******************
1652      * Initialize grid
1653      ******************/
1655     // wrap all data cells, except actions cell, with span
1656     $(t).find('th, td:not(:has(span))')
1657         .wrapInner('<span />');
1659     // create grid elements
1660     g.gDiv = document.createElement('div');     // create global div
1662     // initialize the table variable
1663     g.t = t;
1665     // get data columns in the first row of the table
1666     var $firstRowCols = $(t).find('tr:first th.draggable');
1668     // initialize visible headers count
1669     g.visibleHeadersCount = $firstRowCols.filter(':visible').length;
1671     // assign first column (actions) span
1672     if (! $(t).find('tr:first th:first').hasClass('draggable')) {  // action header exist
1673         g.actionSpan = $(t).find('tr:first th:first').prop('colspan');
1674     } else {
1675         g.actionSpan = 0;
1676     }
1678     // assign table create time
1679     // #table_create_time will only available if we are in "Browse" tab
1680     g.tableCreateTime = $('#table_create_time').val();
1682     // assign the hints
1683     g.sortHint = PMA_messages['strSortHint'];
1684     g.markHint = PMA_messages['strColMarkHint'];
1686     // assign common hidden inputs
1687     var $common_hidden_inputs = $('.common_hidden_inputs');
1688     g.token = $common_hidden_inputs.find('input[name=token]').val();
1689     g.server = $common_hidden_inputs.find('input[name=server]').val();
1690     g.db = $common_hidden_inputs.find('input[name=db]').val();
1691     g.table = $common_hidden_inputs.find('input[name=table]').val();
1693     // add table class
1694     $(t).addClass('pma_table');
1696     // add relative position to global div so that resize handlers are correctly positioned
1697     $(g.gDiv).css('position', 'relative');
1699     // link the global div
1700     $(t).before(g.gDiv);
1701     $(g.gDiv).append(t);
1703     // FEATURES
1704     enableResize    = enableResize == undefined ? true : enableResize;
1705     enableReorder   = enableReorder == undefined ? true : enableReorder;
1706     enableVisib     = enableVisib == undefined ? true : enableVisib;
1707     enableGridEdit  = enableGridEdit == undefined ? true : enableGridEdit;
1708     if (enableResize) {
1709         g.initColResize();
1710     }
1711     if (enableReorder &&
1712         $('.navigation').length > 0)    // disable reordering for result from EXPLAIN or SHOW syntax, which do not have a table navigation panel
1713     {
1714         g.initColReorder();
1715     }
1716     if (enableVisib) {
1717         g.initColVisib();
1718     }
1719     if (enableGridEdit &&
1720         $(t).is('.ajax'))   // make sure AjaxEnable is enabled in Settings
1721     {
1722         g.initGridEdit();
1723     }
1725     // create qtip for each <th> with draggable class
1726     PMA_createqTip($(t).find('th.draggable'));
1728     // register events for hint tooltip
1729     $(t).find('th.draggable a')
1730         .attr('title', '')          // hide default tooltip for sorting
1731         .mouseenter(function(e) {
1732             g.showSortHint = true;
1733             g.updateHint(e);
1734         })
1735         .mouseleave(function(e) {
1736             g.showSortHint = false;
1737             g.updateHint(e);
1738         });
1739     $(t).find('th.marker')
1740         .mouseenter(function(e) {
1741             g.showMarkHint = true;
1742         })
1743         .mouseleave(function(e) {
1744             g.showMarkHint = false;
1745         });
1746     // register events for dragging-related feature
1747     if (enableResize || enableReorder) {
1748         $(document).mousemove(function(e) {
1749             g.dragMove(e);
1750         });
1751         $(document).mouseup(function(e) {
1752             g.dragEnd(e);
1753         });
1754     }
1756     // bind event to update currently hovered qtip API
1757     $(t).find('th')
1758         .mouseenter(function(e) {
1759             g.qtip = $(this).qtip('api');
1760             g.updateHint(e);
1761         })
1762         .mouseleave(function(e) {
1763             g.updateHint(e);
1764         });
1766     // some adjustment
1767     $(t).removeClass('data');
1768     $(g.gDiv).addClass('data');