bug #4002 Edit Index on big table does not show "Loading" or any message
[phpmyadmin.git] / js / makegrid.js
blob6b014e6447ecc24718a803fad35124b70d375a9a
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'
984                     ) {
985                         $input_field.val(current_datetime_value);
986                     } else {
987                         $editArea.datetimepicker('setDate', current_datetime_value);
988                     }
989                     $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
991                     // remove {cursor: 'pointer'} added inside
992                     // jquery-ui-timepicker-addon.js
993                     $input_field.css('cursor', '');
994                     // make the cell editable, so one can can bypass the timepicker
995                     // and enter date/time value manually
996                     g.isEditCellTextEditable = true;
997                 } else {
998                     g.isEditCellTextEditable = true;
999                     // only append edit area hint if there is a null checkbox
1000                     if ($editArea.children().length > 0) {
1001                         $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
1002                     }
1003                 }
1004                 if ($editArea.children().length > 0) {
1005                     $editArea.show();
1006                 }
1007             }
1008         },
1010         /**
1011          * Post the content of edited cell.
1012          */
1013         postEditedCell: function() {
1014             if (g.isSaving) {
1015                 return;
1016             }
1017             g.isSaving = true;
1019             /**
1020              * @var relation_fields Array containing the name/value pairs of relational fields
1021              */
1022             var relation_fields = {};
1023             /**
1024              * @var relational_display string 'K' if relational key, 'D' if relational display column
1025              */
1026             var relational_display = $("#relational_display_K").prop('checked') ? 'K' : 'D';
1027             /**
1028              * @var transform_fields    Array containing the name/value pairs for transformed fields
1029              */
1030             var transform_fields = {};
1031             /**
1032              * @var transformation_fields   Boolean, if there are any transformed fields in the edited cells
1033              */
1034             var transformation_fields = false;
1035             /**
1036              * @var full_sql_query String containing the complete SQL query to update this table
1037              */
1038             var full_sql_query = '';
1039             /**
1040              * @var rel_fields_list  String, url encoded representation of {@link relations_fields}
1041              */
1042             var rel_fields_list = '';
1043             /**
1044              * @var transform_fields_list  String, url encoded representation of {@link transform_fields}
1045              */
1046             var transform_fields_list = '';
1047             /**
1048              * @var where_clause Array containing where clause for updated fields
1049              */
1050             var full_where_clause = [];
1051             /**
1052              * @var is_unique   Boolean, whether the rows in this table is unique or not
1053              */
1054             var is_unique = $('td.edit_row_anchor').is('.nonunique') ? 0 : 1;
1055             /**
1056              * multi edit variables
1057              */
1058             var me_fields_name = [];
1059             var me_fields = [];
1060             var me_fields_null = [];
1062             // alert user if edited table is not unique
1063             if (!is_unique) {
1064                 alert(g.alertNonUnique);
1065             }
1067             // loop each edited row
1068             $('td.to_be_saved').parents('tr').each(function() {
1069                 var $tr = $(this);
1070                 var where_clause = $tr.find('.where_clause').val();
1071                 full_where_clause.push(PMA_urldecode(where_clause));
1072                 var condition_array = jQuery.parseJSON($tr.find('.condition_array').val());
1074                 /**
1075                  * multi edit variables, for current row
1076                  * @TODO array indices are still not correct, they should be md5 of field's name
1077                  */
1078                 var fields_name = [];
1079                 var fields = [];
1080                 var fields_null = [];
1082                 // loop each edited cell in a row
1083                 $tr.find('.to_be_saved').each(function() {
1084                     /**
1085                      * @var $this_field    Object referring to the td that is being edited
1086                      */
1087                     var $this_field = $(this);
1089                     /**
1090                      * @var field_name  String containing the name of this field.
1091                      * @see getFieldName()
1092                      */
1093                     var field_name = getFieldName($this_field);
1095                     /**
1096                      * @var this_field_params   Array temporary storage for the name/value of current field
1097                      */
1098                     var this_field_params = {};
1100                     if ($this_field.is('.transformed')) {
1101                         transformation_fields =  true;
1102                     }
1103                     this_field_params[field_name] = $this_field.data('value');
1105                     /**
1106                      * @var is_null String capturing whether 'checkbox_null_<field_name>_<row_index>' is checked.
1107                      */
1108                     var is_null = this_field_params[field_name] === null;
1110                     fields_name.push(field_name);
1112                     if (is_null) {
1113                         fields_null.push('on');
1114                         fields.push('');
1115                     } else {
1116                         fields_null.push('');
1117                         fields.push($this_field.data('value'));
1119                         var cell_index = $this_field.index('.to_be_saved');
1120                         if ($this_field.is(":not(.relation, .enum, .set, .bit)")) {
1121                             if ($this_field.is('.transformed')) {
1122                                 transform_fields[cell_index] = {};
1123                                 $.extend(transform_fields[cell_index], this_field_params);
1124                             }
1125                         } else if ($this_field.is('.relation')) {
1126                             relation_fields[cell_index] = {};
1127                             $.extend(relation_fields[cell_index], this_field_params);
1128                         }
1129                     }
1130                     // check if edited field appears in WHERE clause
1131                     if (where_clause.indexOf(PMA_urlencode(field_name)) > -1) {
1132                         var field_str = '`' + g.table + '`.' + '`' + field_name + '`';
1133                         for (var field in condition_array) {
1134                             if (field.indexOf(field_str) > -1) {
1135                                 condition_array[field] = is_null ? 'IS NULL' : "= '" + this_field_params[field_name].replace(/'/g,"''") + "'";
1136                                 break;
1137                             }
1138                         }
1139                     }
1141                 }); // end of loop for every edited cells in a row
1143                 // save new_clause
1144                 var new_clause = '';
1145                 for (var field in condition_array) {
1146                     new_clause += field + ' ' + condition_array[field] + ' AND ';
1147                 }
1148                 new_clause = new_clause.substring(0, new_clause.length - 5); // remove the last AND
1149                 new_clause = PMA_urlencode(new_clause);
1150                 $tr.data('new_clause', new_clause);
1151                 // save condition_array
1152                 $tr.find('.condition_array').val(JSON.stringify(condition_array));
1154                 me_fields_name.push(fields_name);
1155                 me_fields.push(fields);
1156                 me_fields_null.push(fields_null);
1158             }); // end of loop for every edited rows
1160             rel_fields_list = $.param(relation_fields);
1161             transform_fields_list = $.param(transform_fields);
1163             // Make the Ajax post after setting all parameters
1164             /**
1165              * @var post_params Object containing parameters for the POST request
1166              */
1167             var post_params = {'ajax_request' : true,
1168                             'sql_query' : full_sql_query,
1169                             'token' : g.token,
1170                             'server' : g.server,
1171                             'db' : g.db,
1172                             'table' : g.table,
1173                             'clause_is_unique' : is_unique,
1174                             'where_clause' : full_where_clause,
1175                             'fields[multi_edit]' : me_fields,
1176                             'fields_name[multi_edit]' : me_fields_name,
1177                             'fields_null[multi_edit]' : me_fields_null,
1178                             'rel_fields_list' : rel_fields_list,
1179                             'do_transformations' : transformation_fields,
1180                             'transform_fields_list' : transform_fields_list,
1181                             'relational_display' : relational_display,
1182                             'goto' : 'sql.php',
1183                             'submit_type' : 'save'
1184                           };
1186             if (!g.saveCellsAtOnce) {
1187                 $(g.cEdit).find('*').prop('disabled', true);
1188                 $(g.cEdit).find('.edit_box').addClass('edit_box_posting');
1189             } else {
1190                 $('div.save_edited').addClass('saving_edited_data')
1191                     .find('input').prop('disabled', true);    // disable the save button
1192             }
1194             $.ajax({
1195                 type: 'POST',
1196                 url: 'tbl_replace.php',
1197                 data: post_params,
1198                 success:
1199                     function(data) {
1200                         g.isSaving = false;
1201                         if (!g.saveCellsAtOnce) {
1202                             $(g.cEdit).find('*').removeProp('disabled');
1203                             $(g.cEdit).find('.edit_box').removeClass('edit_box_posting');
1204                         } else {
1205                             $('div.save_edited').removeClass('saving_edited_data')
1206                                 .find('input').removeProp('disabled');  // enable the save button back
1207                         }
1208                         if (data.success == true) {
1209                             PMA_ajaxShowMessage(data.message);
1211                             // update where_clause related data in each edited row
1212                             $('td.to_be_saved').parents('tr').each(function() {
1213                                 var new_clause = $(this).data('new_clause');
1214                                 var $where_clause = $(this).find('.where_clause');
1215                                 var old_clause = $where_clause.val();
1216                                 var decoded_old_clause = PMA_urldecode(old_clause);
1217                                 var decoded_new_clause = PMA_urldecode(new_clause);
1219                                 $where_clause.val(new_clause);
1220                                 // update Edit, Copy, and Delete links also
1221                                 $(this).find('a').each(function() {
1222                                     $(this).attr('href', $(this).attr('href').replace(old_clause, new_clause));
1223                                     // update delete confirmation in Delete link
1224                                     if ($(this).attr('href').indexOf('DELETE') > -1) {
1225                                         $(this).removeAttr('onclick')
1226                                             .unbind('click')
1227                                             .bind('click', function() {
1228                                                 return confirmLink(this, 'DELETE FROM `' + g.db + '`.`' + g.table + '` WHERE ' +
1229                                                        decoded_new_clause + (is_unique ? '' : ' LIMIT 1'));
1230                                             });
1231                                     }
1232                                 });
1233                                 // update the multi edit checkboxes
1234                                 $(this).find('input[type=checkbox]').each(function() {
1235                                     var $checkbox = $(this);
1236                                     var checkbox_name = $checkbox.attr('name');
1237                                     var checkbox_value = $checkbox.val();
1239                                     $checkbox.attr('name', checkbox_name.replace(old_clause, new_clause));
1240                                     $checkbox.val(checkbox_value.replace(decoded_old_clause, decoded_new_clause));
1241                                 });
1242                             });
1243                             // update the display of executed SQL query command
1244                             $('#result_query').remove();
1245                             if (typeof data.sql_query != 'undefined') {
1246                                 // display feedback
1247                                 $('#sqlqueryresults').prepend(data.sql_query);
1248                             }
1249                             // hide and/or update the successfully saved cells
1250                             g.hideEditCell(true, data);
1252                             // remove the "Save edited cells" button
1253                             $('div.save_edited').hide();
1254                             // update saved fields
1255                             $(g.t).find('.to_be_saved')
1256                                 .removeClass('to_be_saved')
1257                                 .data('value', null)
1258                                 .data('original_data', null);
1260                             g.isCellEdited = false;
1261                         } else {
1262                             PMA_ajaxShowMessage(data.error, false);
1263                         }
1264                     }
1265             }); // end $.ajax()
1266         },
1268         /**
1269          * Save edited cell, so it can be posted later.
1270          */
1271         saveEditedCell: function() {
1272             /**
1273              * @var $this_field    Object referring to the td that is being edited
1274              */
1275             var $this_field = $(g.currentEditCell);
1276             var $test_element = ''; // to test the presence of a element
1278             var need_to_post = false;
1280             /**
1281              * @var field_name  String containing the name of this field.
1282              * @see getFieldName()
1283              */
1284             var field_name = getFieldName($this_field);
1286             /**
1287              * @var this_field_params   Array temporary storage for the name/value of current field
1288              */
1289             var this_field_params = {};
1291             /**
1292              * @var is_null String capturing whether 'checkbox_null_<field_name>_<row_index>' is checked.
1293              */
1294             var is_null = $(g.cEdit).find('input:checkbox').is(':checked');
1295             var value;
1297             if ($(g.cEdit).find('.edit_area').is('.edit_area_loading')) {
1298                 // the edit area is still loading (retrieving cell data), no need to post
1299                 need_to_post = false;
1300             } else if (is_null) {
1301                 if (!g.wasEditedCellNull) {
1302                     this_field_params[field_name] = null;
1303                     need_to_post = true;
1304                 }
1305             } else {
1306                 if ($this_field.is('.bit')) {
1307                     this_field_params[field_name] = '0b' + $(g.cEdit).find('.edit_box').val();
1308                 } else if ($this_field.is('.set')) {
1309                     $test_element = $(g.cEdit).find('select');
1310                     this_field_params[field_name] = $test_element.map(function(){
1311                         return $(this).val();
1312                     }).get().join(",");
1313                 } else if ($this_field.is('.relation, .enum')) {
1314                     // for relation and enumeration, take the results from edit box value,
1315                     // because selected value from drop-down, new window or multiple
1316                     // selection list will always be updated to the edit box
1317                     this_field_params[field_name] = $(g.cEdit).find('.edit_box').val();
1318                 } else {
1319                     this_field_params[field_name] = $(g.cEdit).find('.edit_box').val();
1320                 }
1321                 if (g.wasEditedCellNull || this_field_params[field_name] != PMA_getCellValue(g.currentEditCell)) {
1322                     need_to_post = true;
1323                 }
1324             }
1326             if (need_to_post) {
1327                 $(g.currentEditCell).addClass('to_be_saved')
1328                     .data('value', this_field_params[field_name]);
1329                 if (g.saveCellsAtOnce) {
1330                     $('div.save_edited').show();
1331                 }
1332                 g.isCellEdited = true;
1333             }
1335             return need_to_post;
1336         },
1338         /**
1339          * Save or post currently edited cell, depending on the "saveCellsAtOnce" configuration.
1340          */
1341         saveOrPostEditedCell: function() {
1342             var saved = g.saveEditedCell();
1343             if (!g.saveCellsAtOnce) {
1344                 if (saved) {
1345                     g.postEditedCell();
1346                 } else {
1347                     g.hideEditCell(true);
1348                 }
1349             } else {
1350                 if (saved) {
1351                     g.hideEditCell(true, true);
1352                 } else {
1353                     g.hideEditCell(true);
1354                 }
1355             }
1356         },
1358         /**
1359          * Initialize column resize feature.
1360          */
1361         initColResize: function() {
1362             // create column resizer div
1363             g.cRsz = document.createElement('div');
1364             g.cRsz.className = 'cRsz';
1366             // get data columns in the first row of the table
1367             var $firstRowCols = $(g.t).find('tr:first th.draggable');
1369             // create column borders
1370             $firstRowCols.each(function() {
1371                 var cb = document.createElement('div'); // column border
1372                 $(cb).addClass('colborder')
1373                     .mousedown(function(e) {
1374                         g.dragStartRsz(e, this);
1375                     });
1376                 $(g.cRsz).append(cb);
1377             });
1378             g.reposRsz();
1380             // attach to global div
1381             $(g.gDiv).prepend(g.cRsz);
1382         },
1384         /**
1385          * Initialize column reordering feature.
1386          */
1387         initColReorder: function() {
1388             g.cCpy = document.createElement('div');     // column copy, to store copy of dragged column header
1389             g.cPointer = document.createElement('div'); // column pointer, used when reordering column
1391             // adjust g.cCpy
1392             g.cCpy.className = 'cCpy';
1393             $(g.cCpy).hide();
1395             // adjust g.cPointer
1396             g.cPointer.className = 'cPointer';
1397             $(g.cPointer).css('visibility', 'hidden');  // set visibility to hidden instead of calling hide() to force browsers to cache the image in cPointer class
1399             // assign column reordering hint
1400             g.reorderHint = PMA_messages['strColOrderHint'];
1402             // get data columns in the first row of the table
1403             var $firstRowCols = $(g.t).find('tr:first th.draggable');
1405             // initialize column order
1406             $col_order = $('#col_order');   // check if column order is passed from PHP
1407             if ($col_order.length > 0) {
1408                 g.colOrder = $col_order.val().split(',');
1409                 for (var i = 0; i < g.colOrder.length; i++) {
1410                     g.colOrder[i] = parseInt(g.colOrder[i]);
1411                 }
1412             } else {
1413                 g.colOrder = [];
1414                 for (var i = 0; i < $firstRowCols.length; i++) {
1415                     g.colOrder.push(i);
1416                 }
1417             }
1419             // register events
1420             $(t).find('th.draggable')
1421                 .mousedown(function(e) {
1422                     if (g.visibleHeadersCount > 1) {
1423                         g.dragStartReorder(e, this);
1424                     }
1425                 })
1426                 .mouseenter(function(e) {
1427                     if (g.visibleHeadersCount > 1) {
1428                         $(this).css('cursor', 'move');
1429                     } else {
1430                         $(this).css('cursor', 'inherit');
1431                     }
1432                 })
1433                 .mouseleave(function(e) {
1434                     g.showReorderHint = false;
1435                     $(this).tooltip("option", {
1436                         content: g.updateHint()
1437                     }) ;
1438                 })
1439                 .dblclick(function(e) {
1440                     e.preventDefault();
1441                     $("<div/>")
1442                     .prop("title", PMA_messages["strColNameCopyTitle"])
1443                     .addClass("modal-copy")
1444                     .text(PMA_messages["strColNameCopyText"])
1445                     .append(
1446                         $("<input/>")
1447                         .prop("readonly", true)
1448                         .val($(this).data("column"))
1449                         )
1450                     .dialog({
1451                         resizable: false,
1452                         modal: true
1453                     })
1454                     .find("input").focus().select();
1455                 });
1456             // restore column order when the restore button is clicked
1457             $('div.restore_column').click(function() {
1458                 g.restoreColOrder();
1459             });
1461             // attach to global div
1462             $(g.gDiv).append(g.cPointer);
1463             $(g.gDiv).append(g.cCpy);
1465             // prevent default "dragstart" event when dragging a link
1466             $(t).find('th a').bind('dragstart', function() {
1467                 return false;
1468             });
1470             // refresh the restore column button state
1471             g.refreshRestoreButton();
1472         },
1474         /**
1475          * Initialize column visibility feature.
1476          */
1477         initColVisib: function() {
1478             g.cDrop = document.createElement('div');    // column drop-down arrows
1479             g.cList = document.createElement('div');    // column visibility list
1481             // adjust g.cDrop
1482             g.cDrop.className = 'cDrop';
1484             // adjust g.cList
1485             g.cList.className = 'cList';
1486             $(g.cList).hide();
1488             // assign column visibility related hints
1489             g.showAllColText = PMA_messages['strShowAllCol'];
1491             // get data columns in the first row of the table
1492             var $firstRowCols = $(g.t).find('tr:first th.draggable');
1494             // initialize column visibility
1495             var $col_visib = $('#col_visib');   // check if column visibility is passed from PHP
1496             if ($col_visib.length > 0) {
1497                 g.colVisib = $col_visib.val().split(',');
1498                 for (var i = 0; i < g.colVisib.length; i++) {
1499                     g.colVisib[i] = parseInt(g.colVisib[i]);
1500                 }
1501             } else {
1502                 g.colVisib = [];
1503                 for (var i = 0; i < $firstRowCols.length; i++) {
1504                     g.colVisib.push(1);
1505                 }
1506             }
1508             // make sure we have more than one column
1509             if ($firstRowCols.length > 1) {
1510                 var $colVisibTh = $(g.t).find('th:not(.draggable)');
1511                 PMA_tooltip(
1512                     $colVisibTh,
1513                     'th',
1514                     PMA_messages['strColVisibHint']
1515                 );
1517                 // create column visibility drop-down arrow(s)
1518                 $colVisibTh.each(function() {
1519                         var $th = $(this);
1520                         var cd = document.createElement('div'); // column drop-down arrow
1521                         var pos = $th.position();
1522                         $(cd).addClass('coldrop')
1523                             .click(function() {
1524                                 if (g.cList.style.display == 'none') {
1525                                     g.showColList(this);
1526                                 } else {
1527                                     g.hideColList();
1528                                 }
1529                             });
1530                         $(g.cDrop).append(cd);
1531                     });
1533                 // add column visibility control
1534                 g.cList.innerHTML = '<div class="lDiv"></div>';
1535                 var $listDiv = $(g.cList).find('div');
1536                 for (var i = 0; i < $firstRowCols.length; i++) {
1537                     var currHeader = $firstRowCols[i];
1538                     var listElmt = document.createElement('div');
1539                     $(listElmt).text($(currHeader).text())
1540                         .prepend('<input type="checkbox" ' + (g.colVisib[i] ? 'checked="checked" ' : '') + '/>');
1541                     $listDiv.append(listElmt);
1542                     // add event on click
1543                     $(listElmt).click(function() {
1544                         if ( g.toggleCol($(this).index()) ) {
1545                             g.afterToggleCol();
1546                         }
1547                     });
1548                 }
1549                 // add "show all column" button
1550                 var showAll = document.createElement('div');
1551                 $(showAll).addClass('showAllColBtn')
1552                     .text(g.showAllColText);
1553                 $(g.cList).append(showAll);
1554                 $(showAll).click(function() {
1555                     g.showAllColumns();
1556                 });
1557                 // prepend "show all column" button at top if the list is too long
1558                 if ($firstRowCols.length > 10) {
1559                     var clone = showAll.cloneNode(true);
1560                     $(g.cList).prepend(clone);
1561                     $(clone).click(function() {
1562                         g.showAllColumns();
1563                     });
1564                 }
1565             }
1567             // hide column visibility list if we move outside the list
1568             $(t).find('td, th.draggable').mouseenter(function() {
1569                 g.hideColList();
1570             });
1572             // attach to global div
1573             $(g.gDiv).append(g.cDrop);
1574             $(g.gDiv).append(g.cList);
1576             // some adjustment
1577             g.reposDrop();
1578         },
1580         /**
1581          * Initialize grid editing feature.
1582          */
1583         initGridEdit: function() {
1585             function startGridEditing(e, cell) {
1586                 if (g.isCellEditActive) {
1587                     g.saveOrPostEditedCell();
1588                 } else {
1589                     g.showEditCell(cell);
1590                 }
1591                 e.stopPropagation();
1592             }
1594             // create cell edit wrapper element
1595             g.cEdit = document.createElement('div');
1597             // adjust g.cEdit
1598             g.cEdit.className = 'cEdit';
1599             $(g.cEdit).html('<textarea class="edit_box" rows="1" ></textarea><div class="edit_area" />');
1600             $(g.cEdit).hide();
1602             // assign cell editing hint
1603             g.cellEditHint = PMA_messages['strCellEditHint'];
1604             g.saveCellWarning = PMA_messages['strSaveCellWarning'];
1605             g.alertNonUnique = PMA_messages['strAlertNonUnique'];
1606             g.gotoLinkText = PMA_messages['strGoToLink'];
1607             g.showDataRowLinkText = PMA_messages['strShowDataRowLink'];
1609             // initialize cell editing configuration
1610             g.saveCellsAtOnce = $('#save_cells_at_once').val();
1612             // register events
1613             $(t).find('td.data.click1')
1614                 .click(function(e) {
1615                     startGridEditing(e, this);
1616                     // prevent default action when clicking on "link" in a table
1617                     if ($(e.target).is('.grid_edit a')) {
1618                         e.preventDefault();
1619                     }
1620                 });
1622             $(t).find('td.data.click2')
1623                 .click(function(e) {
1624                     $cell = $(this);
1625                     // In the case of relational link, We want single click on the link
1626                     // to goto the link and double click to start grid-editing.
1627                     var $link = $(e.target);
1628                     if ($link.is('.grid_edit.relation a')) {
1629                         e.preventDefault();
1630                         // get the click count and increase
1631                         var clicks = $cell.data('clicks');
1632                         clicks = (clicks == null) ? 1 : clicks + 1;
1634                         if (clicks == 1) {
1635                             // if there are no previous clicks,
1636                             // start the single click timer
1637                             timer = setTimeout(function() {
1638                                 // temporarily remove ajax class so the page loader will not handle it,
1639                                 // submit and then add it back
1640                                 $link.removeClass('ajax');
1641                                 AJAX.requestHandler.call($link[0]);
1642                                 $link.addClass('ajax');
1643                                 $cell.data('clicks', 0);
1644                             }, 700);
1645                             $cell.data('clicks', clicks);
1646                             $cell.data('timer', timer);
1647                         } else {
1648                             // this is a double click, cancel the single click timer
1649                             // and make the click count 0
1650                             clearTimeout($cell.data('timer'));
1651                             $cell.data('clicks', 0);
1652                             // start grid-editing
1653                             startGridEditing(e, this);
1654                         }
1655                     }
1656                 })
1657                 .dblclick(function(e) {
1658                     if ($(e.target).is('.grid_edit a')) {
1659                         e.preventDefault();
1660                     } else {
1661                         startGridEditing(e, this);
1662                     }
1663                 });
1665             $(g.cEdit).find('.edit_box').focus(function(e) {
1666                 g.showEditArea();
1667             });
1668             $(g.cEdit).find('.edit_box, select').live('keydown', function(e) {
1669                 if (e.which == 13) {
1670                     // post on pressing "Enter"
1671                     e.preventDefault();
1672                     g.saveOrPostEditedCell();
1673                 }
1674             });
1675             $(g.cEdit).keydown(function(e) {
1676                 if (!g.isEditCellTextEditable) {
1677                     // prevent text editing
1678                     e.preventDefault();
1679                 }
1680             });
1681             $('html').click(function(e) {
1682                 // hide edit cell if the click is not from g.cEdit
1683                 if ($(e.target).parents().index(g.cEdit) == -1) {
1684                     g.hideEditCell();
1685                 }
1686             }).keydown(function(e) {
1687                 if (e.which == 27 && g.isCellEditActive) {
1689                     // cancel on pressing "Esc"
1690                     g.hideEditCell(true);
1691                 }
1692             });
1693             $('div.save_edited').click(function() {
1694                 g.hideEditCell();
1695                 g.postEditedCell();
1696             });
1697             $(window).bind('beforeunload', function(e) {
1698                 if (g.isCellEdited) {
1699                     return g.saveCellWarning;
1700                 }
1701             });
1703             // attach to global div
1704             $(g.gDiv).append(g.cEdit);
1706             // add hint for grid editing feature when hovering "Edit" link in each table row
1707             if (PMA_messages['strGridEditFeatureHint'] != undefined) {
1708                 PMA_tooltip(
1709                     $(g.t).find('.edit_row_anchor a'),
1710                     'a',
1711                     PMA_messages['strGridEditFeatureHint']
1712                 );
1713             }
1714         }
1715     };
1717     /******************
1718      * Initialize grid
1719      ******************/
1721     // wrap all data cells, except actions cell, with span
1722     $(t).find('th, td:not(:has(span))')
1723         .wrapInner('<span />');
1725     // create grid elements
1726     g.gDiv = document.createElement('div');     // create global div
1728     // initialize the table variable
1729     g.t = t;
1731     // get data columns in the first row of the table
1732     var $firstRowCols = $(t).find('tr:first th.draggable');
1734     // initialize visible headers count
1735     g.visibleHeadersCount = $firstRowCols.filter(':visible').length;
1737     // assign first column (actions) span
1738     if (! $(t).find('tr:first th:first').hasClass('draggable')) {  // action header exist
1739         g.actionSpan = $(t).find('tr:first th:first').prop('colspan');
1740     } else {
1741         g.actionSpan = 0;
1742     }
1744     // assign table create time
1745     // #table_create_time will only available if we are in "Browse" tab
1746     g.tableCreateTime = $('#table_create_time').val();
1748     // assign the hints
1749     g.sortHint = PMA_messages['strSortHint'];
1750     g.markHint = PMA_messages['strColMarkHint'];
1751     g.copyHint = PMA_messages['strColNameCopyHint'];
1753     // assign common hidden inputs
1754     var $common_hidden_inputs = $('div.common_hidden_inputs');
1755     g.token = $common_hidden_inputs.find('input[name=token]').val();
1756     g.server = $common_hidden_inputs.find('input[name=server]').val();
1757     g.db = $common_hidden_inputs.find('input[name=db]').val();
1758     g.table = $common_hidden_inputs.find('input[name=table]').val();
1760     // add table class
1761     $(t).addClass('pma_table');
1763     // add relative position to global div so that resize handlers are correctly positioned
1764     $(g.gDiv).css('position', 'relative');
1766     // link the global div
1767     $(t).before(g.gDiv);
1768     $(g.gDiv).append(t);
1770     // FEATURES
1771     enableResize    = enableResize == undefined ? true : enableResize;
1772     enableReorder   = enableReorder == undefined ? true : enableReorder;
1773     enableVisib     = enableVisib == undefined ? true : enableVisib;
1774     enableGridEdit  = enableGridEdit == undefined ? true : enableGridEdit;
1775     if (enableResize) {
1776         g.initColResize();
1777     }
1778     if (enableReorder &&
1779         $('table.navigation').length > 0)    // disable reordering for result from EXPLAIN or SHOW syntax, which do not have a table navigation panel
1780     {
1781         g.initColReorder();
1782     }
1783     if (enableVisib) {
1784         g.initColVisib();
1785     }
1786     if (enableGridEdit &&
1787         $(t).is('.ajax'))   // make sure we have the ajax class
1788     {
1789         g.initGridEdit();
1790     }
1792     // create tooltip for each <th> with draggable class
1793     PMA_tooltip(
1794             $(t).find("th.draggable"),
1795             'th',
1796             g.updateHint()
1797     );
1799     // register events for hint tooltip (anchors inside draggable th)
1800     $(t).find('th.draggable a')
1801         .mouseenter(function(e) {
1802             g.showSortHint = true;
1803             $(t).find("th.draggable").tooltip("option", {
1804                 content: g.updateHint()
1805             });
1806         })
1807         .mouseleave(function(e) {
1808             g.showSortHint = false;
1809             $(t).find("th.draggable").tooltip("option", {
1810                 content: g.updateHint()
1811             });
1812         });
1814     // register events for dragging-related feature
1815     if (enableResize || enableReorder) {
1816         $(document).mousemove(function(e) {
1817             g.dragMove(e);
1818         });
1819         $(document).mouseup(function(e) {
1820             g.dragEnd(e);
1821         });
1822     }
1824     // some adjustment
1825     $(t).removeClass('data');
1826     $(g.gDiv).addClass('data');