Fix merge conflicts
[phpmyadmin.git] / js / makegrid.js
blobc6237886a397ec5db7bfcd3f37561851fc77a33a
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 + ': ')
720                         .append($td.find('a').clone().click(
721                             function (event) {
722                                 event.preventDefault();
723                                 window.open(this.href);
724                             }));
725                     $editArea.append(gotoLink);
726                 }
728                 g.wasEditedCellNull = false;
729                 if ($td.is(':not(.not_null)')) {
730                     // append a null checkbox
731                     $editArea.append('<div class="null_div">Null :<input type="checkbox"></div>');
732                     var $checkbox = $editArea.find('.null_div input');
733                     // check if current <td> is NULL
734                     if ($td.is('.null')) {
735                         $checkbox.prop('checked', true);
736                         g.wasEditedCellNull = true;
737                     }
739                     // if the select/editor is changed un-check the 'checkbox_null_<field_name>_<row_index>'.
740                     if ($td.is('.enum, .set')) {
741                         $editArea.find('select').live('change', function(e) {
742                             $checkbox.prop('checked', false);
743                         });
744                     } else if ($td.is('.relation')) {
745                         $editArea.find('select').live('change', function(e) {
746                             $checkbox.prop('checked', false);
747                         });
748                         $editArea.find('.browse_foreign').live('click', function(e) {
749                             $checkbox.prop('checked', false);
750                         });
751                     } else {
752                         $(g.cEdit).find('.edit_box').live('keypress change', function(e) {
753                             $checkbox.prop('checked', false);
754                         });
755                         // Capture ctrl+v (on IE and Chrome)
756                         $(g.cEdit).find('.edit_box').live('keydown', function(e) {
757                             if (e.ctrlKey && e.which == 86) {
758                                 $checkbox.prop('checked', false);
759                             }
760                         });
761                         $editArea.find('textarea').live('keydown', function(e) {
762                             $checkbox.prop('checked', false);
763                         });
764                     }
766                     // if null checkbox is clicked empty the corresponding select/editor.
767                     $checkbox.click(function(e) {
768                         if ($td.is('.enum')) {
769                             $editArea.find('select').val('');
770                         } else if ($td.is('.set')) {
771                             $editArea.find('select').find('option').each(function() {
772                                 var $option = $(this);
773                                 $option.prop('selected', false);
774                             });
775                         } else if ($td.is('.relation')) {
776                             // if the dropdown is there to select the foreign value
777                             if ($editArea.find('select').length > 0) {
778                                 $editArea.find('select').val('');
779                             }
780                         } else {
781                             $editArea.find('textarea').val('');
782                         }
783                         $(g.cEdit).find('.edit_box').val('');
784                     });
785                 }
787                 if ($td.is('.relation')) {
788                     //handle relations
789                     $editArea.addClass('edit_area_loading');
791                     // initialize the original data
792                     $td.data('original_data', null);
794                     /**
795                      * @var post_params Object containing parameters for the POST request
796                      */
797                     var post_params = {
798                         'ajax_request' : true,
799                         'get_relational_values' : true,
800                         'server' : g.server,
801                         'db' : g.db,
802                         'table' : g.table,
803                         'column' : field_name,
804                         'token' : g.token,
805                         'curr_value' : relation_curr_value,
806                         'relation_key_or_display_column' : relation_key_or_display_column
807                     };
809                     g.lastXHR = $.post('sql.php', post_params, function(data) {
810                         g.lastXHR = null;
811                         $editArea.removeClass('edit_area_loading');
812                         if ($(data.dropdown).is('select')) {
813                             // save original_data
814                             var value = $(data.dropdown).val();
815                             $td.data('original_data', value);
816                             // update the text input field, in case where the "Relational display column" is checked
817                             $(g.cEdit).find('.edit_box').val(value);
818                         }
820                         $editArea.append(data.dropdown);
821                         $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
823                         // for 'Browse foreign values' options,
824                         // hide the value next to 'Browse foreign values' link
825                         $editArea.find('span.curr_value').hide();
826                         // handle update for new values selected from new window
827                         $editArea.find('span.curr_value').change(function() {
828                             $(g.cEdit).find('.edit_box').val($(this).text());
829                         });
830                     }); // end $.post()
832                     $editArea.show();
833                     $editArea.find('select').live('change', function(e) {
834                         $(g.cEdit).find('.edit_box').val($(this).val());
835                     });
836                     g.isEditCellTextEditable = true;
837                 }
838                 else if ($td.is('.enum')) {
839                     //handle enum fields
840                     $editArea.addClass('edit_area_loading');
842                     /**
843                      * @var post_params Object containing parameters for the POST request
844                      */
845                     var post_params = {
846                             'ajax_request' : true,
847                             'get_enum_values' : true,
848                             'server' : g.server,
849                             'db' : g.db,
850                             'table' : g.table,
851                             'column' : field_name,
852                             'token' : g.token,
853                             'curr_value' : curr_value
854                     };
855                     g.lastXHR = $.post('sql.php', post_params, function(data) {
856                         g.lastXHR = null;
857                         $editArea.removeClass('edit_area_loading');
858                         $editArea.append(data.dropdown);
859                         $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
860                     }); // end $.post()
862                     $editArea.show();
863                     $editArea.find('select').live('change', function(e) {
864                         $(g.cEdit).find('.edit_box').val($(this).val());
865                     });
866                 }
867                 else if ($td.is('.set')) {
868                     //handle set fields
869                     $editArea.addClass('edit_area_loading');
871                     /**
872                      * @var post_params Object containing parameters for the POST request
873                      */
874                     var post_params = {
875                             'ajax_request' : true,
876                             'get_set_values' : true,
877                             'server' : g.server,
878                             'db' : g.db,
879                             'table' : g.table,
880                             'column' : field_name,
881                             'token' : g.token,
882                             'curr_value' : curr_value
883                     };
885                     g.lastXHR = $.post('sql.php', post_params, function(data) {
886                         g.lastXHR = null;
887                         $editArea.removeClass('edit_area_loading');
888                         $editArea.append(data.select);
889                         $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
890                     }); // end $.post()
892                     $editArea.show();
893                     $editArea.find('select').live('change', function(e) {
894                         $(g.cEdit).find('.edit_box').val($(this).val());
895                     });
896                 }
897                 else if ($td.is('.truncated, .transformed')) {
898                     if ($td.is('.to_be_saved')) {   // cell has been edited
899                         var value = $td.data('value');
900                         $(g.cEdit).find('.edit_box').val(value);
901                         $editArea.append('<textarea></textarea>');
902                         $editArea.find('textarea')
903                             .val(value)
904                             .live('keyup', function(e) {
905                                 $(g.cEdit).find('.edit_box').val($(this).val());
906                             });
907                         $(g.cEdit).find('.edit_box').live('keyup', function(e) {
908                             $editArea.find('textarea').val($(this).val());
909                         });
910                         $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
911                     } else {
912                         //handle truncated/transformed values values
913                         $editArea.addClass('edit_area_loading');
915                         // initialize the original data
916                         $td.data('original_data', null);
918                         /**
919                          * @var sql_query   String containing the SQL query used to retrieve value of truncated/transformed data
920                          */
921                         var sql_query = 'SELECT `' + field_name + '` FROM `' + g.table + '` WHERE ' + PMA_urldecode(where_clause);
923                         // Make the Ajax call and get the data, wrap it and insert it
924                         g.lastXHR = $.post('sql.php', {
925                             'token' : g.token,
926                             'server' : g.server,
927                             'db' : g.db,
928                             'ajax_request' : true,
929                             'sql_query' : sql_query,
930                             'grid_edit' : true
931                         }, function(data) {
932                             g.lastXHR = null;
933                             $editArea.removeClass('edit_area_loading');
934                             if (data.success == true) {
935                                 if ($td.is('.truncated')) {
936                                     // get the truncated data length
937                                     g.maxTruncatedLen = $(g.currentEditCell).text().length - 3;
938                                 }
940                                 $td.data('original_data', data.value);
941                                 $(g.cEdit).find('.edit_box').val(data.value);
942                                 $editArea.append('<textarea></textarea>');
943                                 $editArea.find('textarea')
944                                     .val(data.value)
945                                     .live('keyup', function(e) {
946                                         $(g.cEdit).find('.edit_box').val($(this).val());
947                                     });
948                                 $(g.cEdit).find('.edit_box').live('keyup', function(e) {
949                                     $editArea.find('textarea').val($(this).val());
950                                 });
951                                 $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
952                             } else {
953                                 PMA_ajaxShowMessage(data.error, false);
954                             }
955                         }); // end $.post()
956                         $editArea.show();
957                     }
958                     g.isEditCellTextEditable = true;
959                 } else if ($td.is('.datefield, .datetimefield, .timestampfield')) {
960                     var $input_field = $(g.cEdit).find('.edit_box');
962                     // remember current datetime value in $input_field, if it is not null
963                     var is_null = $td.is('.null');
964                     var current_datetime_value = !is_null ? $input_field.val() : '';
966                     var showTimeOption = true;
967                     if ($td.is('.datefield')) {
968                         showTimeOption = false;
969                     }
970                     PMA_addDatepicker($editArea, {
971                         altField: $input_field,
972                         showTimepicker: showTimeOption,
973                         onSelect: function(dateText, inst) {
974                             // remove null checkbox if it exists
975                             $(g.cEdit).find('.null_div input[type=checkbox]').prop('checked', false);
976                         }
977                     });
979                     // cancel any click on the datepicker element
980                     $editArea.find('> *').click(function(e) {
981                         e.stopPropagation();
982                     });
984                     // force to restore modified $input_field value after adding datepicker
985                     // (after adding a datepicker, the input field doesn't display the time anymore, only the date)
986                     if (is_null 
987                         || current_datetime_value == '0000-00-00' 
988                         || current_datetime_value == '0000-00-00 00:00:00'
989                     ) {
990                         $input_field.val(current_datetime_value);
991                     } else {
992                         $editArea.datetimepicker('setDate', current_datetime_value);                        
993                     }
994                     $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
996                     // remove {cursor: 'pointer'} added inside
997                     // jquery-ui-timepicker-addon.js
998                     $input_field.css('cursor', '');
999                     // make the cell editable, so one can can bypass the timepicker
1000                     // and enter date/time value manually
1001                     g.isEditCellTextEditable = true;
1002                 } else {
1003                     g.isEditCellTextEditable = true;
1004                     // only append edit area hint if there is a null checkbox
1005                     if ($editArea.children().length > 0) {
1006                         $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
1007                     }
1008                 }
1009                 if ($editArea.children().length > 0) {
1010                     $editArea.show();
1011                 }
1012             }
1013         },
1015         /**
1016          * Post the content of edited cell.
1017          */
1018         postEditedCell: function() {
1019             if (g.isSaving) {
1020                 return;
1021             }
1022             g.isSaving = true;
1024             /**
1025              * @var relation_fields Array containing the name/value pairs of relational fields
1026              */
1027             var relation_fields = {};
1028             /**
1029              * @var relational_display string 'K' if relational key, 'D' if relational display column
1030              */
1031             var relational_display = $("#relational_display_K").prop('checked') ? 'K' : 'D';
1032             /**
1033              * @var transform_fields    Array containing the name/value pairs for transformed fields
1034              */
1035             var transform_fields = {};
1036             /**
1037              * @var transformation_fields   Boolean, if there are any transformed fields in the edited cells
1038              */
1039             var transformation_fields = false;
1040             /**
1041              * @var full_sql_query String containing the complete SQL query to update this table
1042              */
1043             var full_sql_query = '';
1044             /**
1045              * @var rel_fields_list  String, url encoded representation of {@link relations_fields}
1046              */
1047             var rel_fields_list = '';
1048             /**
1049              * @var transform_fields_list  String, url encoded representation of {@link transform_fields}
1050              */
1051             var transform_fields_list = '';
1052             /**
1053              * @var where_clause Array containing where clause for updated fields
1054              */
1055             var full_where_clause = [];
1056             /**
1057              * @var is_unique   Boolean, whether the rows in this table is unique or not
1058              */
1059             var is_unique = $('td.edit_row_anchor').is('.nonunique') ? 0 : 1;
1060             /**
1061              * multi edit variables
1062              */
1063             var me_fields_name = [];
1064             var me_fields = [];
1065             var me_fields_null = [];
1067             // alert user if edited table is not unique
1068             if (!is_unique) {
1069                 alert(g.alertNonUnique);
1070             }
1072             // loop each edited row
1073             $('td.to_be_saved').parents('tr').each(function() {
1074                 var $tr = $(this);
1075                 var where_clause = $tr.find('.where_clause').val();
1076                 full_where_clause.push(PMA_urldecode(where_clause));
1077                 var condition_array = jQuery.parseJSON($tr.find('.condition_array').val());
1079                 /**
1080                  * multi edit variables, for current row
1081                  * @TODO array indices are still not correct, they should be md5 of field's name
1082                  */
1083                 var fields_name = [];
1084                 var fields = [];
1085                 var fields_null = [];
1087                 // loop each edited cell in a row
1088                 $tr.find('.to_be_saved').each(function() {
1089                     /**
1090                      * @var $this_field    Object referring to the td that is being edited
1091                      */
1092                     var $this_field = $(this);
1094                     /**
1095                      * @var field_name  String containing the name of this field.
1096                      * @see getFieldName()
1097                      */
1098                     var field_name = getFieldName($this_field);
1100                     /**
1101                      * @var this_field_params   Array temporary storage for the name/value of current field
1102                      */
1103                     var this_field_params = {};
1105                     if ($this_field.is('.transformed')) {
1106                         transformation_fields =  true;
1107                     }
1108                     this_field_params[field_name] = $this_field.data('value');
1110                     /**
1111                      * @var is_null String capturing whether 'checkbox_null_<field_name>_<row_index>' is checked.
1112                      */
1113                     var is_null = this_field_params[field_name] === null;
1115                     fields_name.push(field_name);
1117                     if (is_null) {
1118                         fields_null.push('on');
1119                         fields.push('');
1120                     } else {
1121                         fields_null.push('');
1122                         fields.push($this_field.data('value'));
1124                         var cell_index = $this_field.index('.to_be_saved');
1125                         if ($this_field.is(":not(.relation, .enum, .set, .bit)")) {
1126                             if ($this_field.is('.transformed')) {
1127                                 transform_fields[cell_index] = {};
1128                                 $.extend(transform_fields[cell_index], this_field_params);
1129                             }
1130                         } else if ($this_field.is('.relation')) {
1131                             relation_fields[cell_index] = {};
1132                             $.extend(relation_fields[cell_index], this_field_params);
1133                         }
1134                     }
1135                     // check if edited field appears in WHERE clause
1136                     if (where_clause.indexOf(PMA_urlencode(field_name)) > -1) {
1137                         var field_str = '`' + g.table + '`.' + '`' + field_name + '`';
1138                         for (var field in condition_array) {
1139                             if (field.indexOf(field_str) > -1) {
1140                                 condition_array[field] = is_null ? 'IS NULL' : "= '" + this_field_params[field_name].replace(/'/g,"''") + "'";
1141                                 break;
1142                             }
1143                         }
1144                     }
1146                 }); // end of loop for every edited cells in a row
1148                 // save new_clause
1149                 var new_clause = '';
1150                 for (var field in condition_array) {
1151                     new_clause += field + ' ' + condition_array[field] + ' AND ';
1152                 }
1153                 new_clause = new_clause.substring(0, new_clause.length - 5); // remove the last AND
1154                 new_clause = PMA_urlencode(new_clause);
1155                 $tr.data('new_clause', new_clause);
1156                 // save condition_array
1157                 $tr.find('.condition_array').val(JSON.stringify(condition_array));
1159                 me_fields_name.push(fields_name);
1160                 me_fields.push(fields);
1161                 me_fields_null.push(fields_null);
1163             }); // end of loop for every edited rows
1165             rel_fields_list = $.param(relation_fields);
1166             transform_fields_list = $.param(transform_fields);
1168             // Make the Ajax post after setting all parameters
1169             /**
1170              * @var post_params Object containing parameters for the POST request
1171              */
1172             var post_params = {'ajax_request' : true,
1173                             'sql_query' : full_sql_query,
1174                             'token' : g.token,
1175                             'server' : g.server,
1176                             'db' : g.db,
1177                             'table' : g.table,
1178                             'clause_is_unique' : is_unique,
1179                             'where_clause' : full_where_clause,
1180                             'fields[multi_edit]' : me_fields,
1181                             'fields_name[multi_edit]' : me_fields_name,
1182                             'fields_null[multi_edit]' : me_fields_null,
1183                             'rel_fields_list' : rel_fields_list,
1184                             'do_transformations' : transformation_fields,
1185                             'transform_fields_list' : transform_fields_list,
1186                             'relational_display' : relational_display,
1187                             'goto' : 'sql.php',
1188                             'submit_type' : 'save'
1189                           };
1191             if (!g.saveCellsAtOnce) {
1192                 $(g.cEdit).find('*').prop('disabled', true);
1193                 $(g.cEdit).find('.edit_box').addClass('edit_box_posting');
1194             } else {
1195                 $('div.save_edited').addClass('saving_edited_data')
1196                     .find('input').prop('disabled', true);    // disable the save button
1197             }
1199             $.ajax({
1200                 type: 'POST',
1201                 url: 'tbl_replace.php',
1202                 data: post_params,
1203                 success:
1204                     function(data) {
1205                         g.isSaving = false;
1206                         if (!g.saveCellsAtOnce) {
1207                             $(g.cEdit).find('*').removeProp('disabled');
1208                             $(g.cEdit).find('.edit_box').removeClass('edit_box_posting');
1209                         } else {
1210                             $('div.save_edited').removeClass('saving_edited_data')
1211                                 .find('input').removeProp('disabled');  // enable the save button back
1212                         }
1213                         if (data.success == true) {
1214                             PMA_ajaxShowMessage(data.message);
1215                             
1216                             // update where_clause related data in each edited row
1217                             $('td.to_be_saved').parents('tr').each(function() {
1218                                 var new_clause = $(this).data('new_clause');
1219                                 var $where_clause = $(this).find('.where_clause');
1220                                 var old_clause = $where_clause.val();
1221                                 var decoded_old_clause = PMA_urldecode(old_clause);
1222                                 var decoded_new_clause = PMA_urldecode(new_clause);
1224                                 $where_clause.val(new_clause);
1225                                 // update Edit, Copy, and Delete links also
1226                                 $(this).find('a').each(function() {
1227                                     $(this).attr('href', $(this).attr('href').replace(old_clause, new_clause));
1228                                     // update delete confirmation in Delete link
1229                                     if ($(this).attr('href').indexOf('DELETE') > -1) {
1230                                         $(this).removeAttr('onclick')
1231                                             .unbind('click')
1232                                             .bind('click', function() {
1233                                                 return confirmLink(this, 'DELETE FROM `' + g.db + '`.`' + g.table + '` WHERE ' +
1234                                                        decoded_new_clause + (is_unique ? '' : ' LIMIT 1'));
1235                                             });
1236                                     }
1237                                 });
1238                                 // update the multi edit checkboxes
1239                                 $(this).find('input[type=checkbox]').each(function() {
1240                                     var $checkbox = $(this);
1241                                     var checkbox_name = $checkbox.attr('name');
1242                                     var checkbox_value = $checkbox.val();
1244                                     $checkbox.attr('name', checkbox_name.replace(old_clause, new_clause));
1245                                     $checkbox.val(checkbox_value.replace(decoded_old_clause, decoded_new_clause));
1246                                 });
1247                             });
1248                             // update the display of executed SQL query command
1249                             $('#result_query').remove();
1250                             if (typeof data.sql_query != 'undefined') {
1251                                 // display feedback
1252                                 $('#sqlqueryresults').prepend(data.sql_query);
1253                             }
1254                             // hide and/or update the successfully saved cells
1255                             g.hideEditCell(true, data);
1257                             // remove the "Save edited cells" button
1258                             $('div.save_edited').hide();
1259                             // update saved fields
1260                             $(g.t).find('.to_be_saved')
1261                                 .removeClass('to_be_saved')
1262                                 .data('value', null)
1263                                 .data('original_data', null);
1265                             g.isCellEdited = false;
1266                         } else {
1267                             PMA_ajaxShowMessage(data.error, false);
1268                         }
1269                     }
1270             }); // end $.ajax()
1271         },
1273         /**
1274          * Save edited cell, so it can be posted later.
1275          */
1276         saveEditedCell: function() {
1277             /**
1278              * @var $this_field    Object referring to the td that is being edited
1279              */
1280             var $this_field = $(g.currentEditCell);
1281             var $test_element = ''; // to test the presence of a element
1283             var need_to_post = false;
1285             /**
1286              * @var field_name  String containing the name of this field.
1287              * @see getFieldName()
1288              */
1289             var field_name = getFieldName($this_field);
1291             /**
1292              * @var this_field_params   Array temporary storage for the name/value of current field
1293              */
1294             var this_field_params = {};
1296             /**
1297              * @var is_null String capturing whether 'checkbox_null_<field_name>_<row_index>' is checked.
1298              */
1299             var is_null = $(g.cEdit).find('input:checkbox').is(':checked');
1300             var value;
1302             if ($(g.cEdit).find('.edit_area').is('.edit_area_loading')) {
1303                 // the edit area is still loading (retrieving cell data), no need to post
1304                 need_to_post = false;
1305             } else if (is_null) {
1306                 if (!g.wasEditedCellNull) {
1307                     this_field_params[field_name] = null;
1308                     need_to_post = true;
1309                 }
1310             } else {
1311                 if ($this_field.is('.bit')) {
1312                     this_field_params[field_name] = '0b' + $(g.cEdit).find('.edit_box').val();
1313                 } else if ($this_field.is('.set')) {
1314                     $test_element = $(g.cEdit).find('select');
1315                     this_field_params[field_name] = $test_element.map(function(){
1316                         return $(this).val();
1317                     }).get().join(",");
1318                 } else if ($this_field.is('.relation, .enum')) {
1319                     // for relation and enumeration, take the results from edit box value,
1320                     // because selected value from drop-down, new window or multiple
1321                     // selection list will always be updated to the edit box
1322                     this_field_params[field_name] = $(g.cEdit).find('.edit_box').val();
1323                 } else {
1324                     this_field_params[field_name] = $(g.cEdit).find('.edit_box').val();
1325                 }
1326                 if (g.wasEditedCellNull || this_field_params[field_name] != PMA_getCellValue(g.currentEditCell)) {
1327                     need_to_post = true;
1328                 }
1329             }
1331             if (need_to_post) {
1332                 $(g.currentEditCell).addClass('to_be_saved')
1333                     .data('value', this_field_params[field_name]);
1334                 if (g.saveCellsAtOnce) {
1335                     $('div.save_edited').show();
1336                 }
1337                 g.isCellEdited = true;
1338             }
1340             return need_to_post;
1341         },
1343         /**
1344          * Save or post currently edited cell, depending on the "saveCellsAtOnce" configuration.
1345          */
1346         saveOrPostEditedCell: function() {
1347             var saved = g.saveEditedCell();
1348             if (!g.saveCellsAtOnce) {
1349                 if (saved) {
1350                     g.postEditedCell();
1351                 } else {
1352                     g.hideEditCell(true);
1353                 }
1354             } else {
1355                 if (saved) {
1356                     g.hideEditCell(true, true);
1357                 } else {
1358                     g.hideEditCell(true);
1359                 }
1360             }
1361         },
1363         /**
1364          * Initialize column resize feature.
1365          */
1366         initColResize: function() {
1367             // create column resizer div
1368             g.cRsz = document.createElement('div');
1369             g.cRsz.className = 'cRsz';
1371             // get data columns in the first row of the table
1372             var $firstRowCols = $(g.t).find('tr:first th.draggable');
1374             // create column borders
1375             $firstRowCols.each(function() {
1376                 var cb = document.createElement('div'); // column border
1377                 $(cb).addClass('colborder')
1378                     .mousedown(function(e) {
1379                         g.dragStartRsz(e, this);
1380                     });
1381                 $(g.cRsz).append(cb);
1382             });
1383             g.reposRsz();
1385             // attach to global div
1386             $(g.gDiv).prepend(g.cRsz);
1387         },
1389         /**
1390          * Initialize column reordering feature.
1391          */
1392         initColReorder: function() {
1393             g.cCpy = document.createElement('div');     // column copy, to store copy of dragged column header
1394             g.cPointer = document.createElement('div'); // column pointer, used when reordering column
1396             // adjust g.cCpy
1397             g.cCpy.className = 'cCpy';
1398             $(g.cCpy).hide();
1400             // adjust g.cPointer
1401             g.cPointer.className = 'cPointer';
1402             $(g.cPointer).css('visibility', 'hidden');  // set visibility to hidden instead of calling hide() to force browsers to cache the image in cPointer class
1404             // assign column reordering hint
1405             g.reorderHint = PMA_messages['strColOrderHint'];
1407             // get data columns in the first row of the table
1408             var $firstRowCols = $(g.t).find('tr:first th.draggable');
1410             // initialize column order
1411             $col_order = $('#col_order');   // check if column order is passed from PHP
1412             if ($col_order.length > 0) {
1413                 g.colOrder = $col_order.val().split(',');
1414                 for (var i = 0; i < g.colOrder.length; i++) {
1415                     g.colOrder[i] = parseInt(g.colOrder[i]);
1416                 }
1417             } else {
1418                 g.colOrder = [];
1419                 for (var i = 0; i < $firstRowCols.length; i++) {
1420                     g.colOrder.push(i);
1421                 }
1422             }
1424             // register events
1425             $(t).find('th.draggable')
1426                 .mousedown(function(e) {
1427                     if (g.visibleHeadersCount > 1) {
1428                         g.dragStartReorder(e, this);
1429                     }
1430                 })
1431                 .mouseenter(function(e) {
1432                     if (g.visibleHeadersCount > 1) {
1433                         $(this).css('cursor', 'move');
1434                     } else {
1435                         $(this).css('cursor', 'inherit');
1436                     }
1437                 })
1438                 .mouseleave(function(e) {
1439                     g.showReorderHint = false;
1440                     $(this).tooltip("option", {
1441                         content: g.updateHint()
1442                     }) ;
1443                 })
1444                 .dblclick(function(e) {
1445                     e.preventDefault();
1446                     $("<div/>")
1447                     .prop("title", PMA_messages["strColNameCopyTitle"])
1448                     .addClass("modal-copy")
1449                     .text(PMA_messages["strColNameCopyText"])
1450                     .append(
1451                         $("<input/>")
1452                         .prop("readonly", true)
1453                         .val($(this).data("column"))
1454                         )
1455                     .dialog({
1456                         resizable: false,
1457                         modal: true
1458                     })
1459                     .find("input").focus().select();
1460                 });
1461             // restore column order when the restore button is clicked
1462             $('div.restore_column').click(function() {
1463                 g.restoreColOrder();
1464             });
1466             // attach to global div
1467             $(g.gDiv).append(g.cPointer);
1468             $(g.gDiv).append(g.cCpy);
1470             // prevent default "dragstart" event when dragging a link
1471             $(t).find('th a').bind('dragstart', function() {
1472                 return false;
1473             });
1475             // refresh the restore column button state
1476             g.refreshRestoreButton();
1477         },
1479         /**
1480          * Initialize column visibility feature.
1481          */
1482         initColVisib: function() {
1483             g.cDrop = document.createElement('div');    // column drop-down arrows
1484             g.cList = document.createElement('div');    // column visibility list
1486             // adjust g.cDrop
1487             g.cDrop.className = 'cDrop';
1489             // adjust g.cList
1490             g.cList.className = 'cList';
1491             $(g.cList).hide();
1493             // assign column visibility related hints
1494             g.showAllColText = PMA_messages['strShowAllCol'];
1496             // get data columns in the first row of the table
1497             var $firstRowCols = $(g.t).find('tr:first th.draggable');
1499             // initialize column visibility
1500             var $col_visib = $('#col_visib');   // check if column visibility is passed from PHP
1501             if ($col_visib.length > 0) {
1502                 g.colVisib = $col_visib.val().split(',');
1503                 for (var i = 0; i < g.colVisib.length; i++) {
1504                     g.colVisib[i] = parseInt(g.colVisib[i]);
1505                 }
1506             } else {
1507                 g.colVisib = [];
1508                 for (var i = 0; i < $firstRowCols.length; i++) {
1509                     g.colVisib.push(1);
1510                 }
1511             }
1513             // make sure we have more than one column
1514             if ($firstRowCols.length > 1) {
1515                 var $colVisibTh = $(g.t).find('th:not(.draggable)');
1516                 PMA_tooltip(
1517                     $colVisibTh,
1518                     'th',
1519                     PMA_messages['strColVisibHint']
1520                 );
1522                 // create column visibility drop-down arrow(s)
1523                 $colVisibTh.each(function() {
1524                         var $th = $(this);
1525                         var cd = document.createElement('div'); // column drop-down arrow
1526                         var pos = $th.position();
1527                         $(cd).addClass('coldrop')
1528                             .click(function() {
1529                                 if (g.cList.style.display == 'none') {
1530                                     g.showColList(this);
1531                                 } else {
1532                                     g.hideColList();
1533                                 }
1534                             });
1535                         $(g.cDrop).append(cd);
1536                     });
1538                 // add column visibility control
1539                 g.cList.innerHTML = '<div class="lDiv"></div>';
1540                 var $listDiv = $(g.cList).find('div');
1541                 for (var i = 0; i < $firstRowCols.length; i++) {
1542                     var currHeader = $firstRowCols[i];
1543                     var listElmt = document.createElement('div');
1544                     $(listElmt).text($(currHeader).text())
1545                         .prepend('<input type="checkbox" ' + (g.colVisib[i] ? 'checked="checked" ' : '') + '/>');
1546                     $listDiv.append(listElmt);
1547                     // add event on click
1548                     $(listElmt).click(function() {
1549                         if ( g.toggleCol($(this).index()) ) {
1550                             g.afterToggleCol();
1551                         }
1552                     });
1553                 }
1554                 // add "show all column" button
1555                 var showAll = document.createElement('div');
1556                 $(showAll).addClass('showAllColBtn')
1557                     .text(g.showAllColText);
1558                 $(g.cList).append(showAll);
1559                 $(showAll).click(function() {
1560                     g.showAllColumns();
1561                 });
1562                 // prepend "show all column" button at top if the list is too long
1563                 if ($firstRowCols.length > 10) {
1564                     var clone = showAll.cloneNode(true);
1565                     $(g.cList).prepend(clone);
1566                     $(clone).click(function() {
1567                         g.showAllColumns();
1568                     });
1569                 }
1570             }
1572             // hide column visibility list if we move outside the list
1573             $(t).find('td, th.draggable').mouseenter(function() {
1574                 g.hideColList();
1575             });
1577             // attach to global div
1578             $(g.gDiv).append(g.cDrop);
1579             $(g.gDiv).append(g.cList);
1581             // some adjustment
1582             g.reposDrop();
1583         },
1585         /**
1586          * Initialize grid editing feature.
1587          */
1588         initGridEdit: function() {
1590             function startGridEditing(e, cell) {
1591                 if (g.isCellEditActive) {
1592                     g.saveOrPostEditedCell();                    
1593                 } else {
1594                     g.showEditCell(cell);
1595                 }
1596                 e.stopPropagation();
1597             }
1599             // create cell edit wrapper element
1600             g.cEdit = document.createElement('div');
1602             // adjust g.cEdit
1603             g.cEdit.className = 'cEdit';
1604             $(g.cEdit).html('<textarea class="edit_box" rows="1" ></textarea><div class="edit_area" />');
1605             $(g.cEdit).hide();
1607             // assign cell editing hint
1608             g.cellEditHint = PMA_messages['strCellEditHint'];
1609             g.saveCellWarning = PMA_messages['strSaveCellWarning'];
1610             g.alertNonUnique = PMA_messages['strAlertNonUnique'];
1611             g.gotoLinkText = PMA_messages['strGoToLink'];
1612             g.showDataRowLinkText = PMA_messages['strShowDataRowLink'];
1614             // initialize cell editing configuration
1615             g.saveCellsAtOnce = $('#save_cells_at_once').val();
1617             // register events
1618             $(t).find('td.data.click1')
1619                 .click(function(e) {
1620                     startGridEditing(e, this);
1621                     // prevent default action when clicking on "link" in a table
1622                     if ($(e.target).is('.grid_edit a')) {
1623                         e.preventDefault();
1624                     }
1625                 });
1627             $(t).find('td.data.click2')
1628                 .click(function(e) {
1629                     $cell = $(this);
1630                     // In the case of relational link, We want single click on the link 
1631                     // to goto the link and double click to start grid-editing.
1632                     var $link = $(e.target);
1633                     if ($link.is('.grid_edit.relation a')) {
1634                         e.preventDefault();
1635                         // get the click count and increase
1636                         var clicks = $cell.data('clicks');
1637                         clicks = (clicks == null) ? 1 : clicks + 1;
1639                         if (clicks == 1) {
1640                             // if there are no previous clicks, 
1641                             // start the single click timer
1642                             timer = setTimeout(function() {
1643                                 // temporarily remove ajax class so the page loader will not handle it,
1644                                 // submit and then add it back
1645                                 $link.removeClass('ajax');
1646                                 AJAX.requestHandler.call($link[0]);
1647                                 $link.addClass('ajax');
1648                                 $cell.data('clicks', 0);
1649                             }, 700);
1650                             $cell.data('clicks', clicks);
1651                             $cell.data('timer', timer);
1652                         } else {
1653                             // this is a double click, cancel the single click timer
1654                             // and make the click count 0
1655                             clearTimeout($cell.data('timer'));
1656                             $cell.data('clicks', 0);
1657                             // start grid-editing
1658                             startGridEditing(e, this);
1659                         }
1660                     }
1661                 })
1662                 .dblclick(function(e) {
1663                     if ($(e.target).is('.grid_edit a')) {
1664                         e.preventDefault();
1665                     } else {
1666                         startGridEditing(e, this);
1667                     }
1668                 });
1670             $(g.cEdit).find('.edit_box').focus(function(e) {
1671                 g.showEditArea();
1672             });
1673             $(g.cEdit).find('.edit_box, select').live('keydown', function(e) {
1674                 if (e.which == 13) {
1675                     // post on pressing "Enter"
1676                     e.preventDefault();
1677                     g.saveOrPostEditedCell();
1678                 }
1679             });
1680             $(g.cEdit).keydown(function(e) {
1681                 if (!g.isEditCellTextEditable) {
1682                     // prevent text editing
1683                     e.preventDefault();
1684                 }
1685             });
1686             $('html').click(function(e) {
1687                 // hide edit cell if the click is not from g.cEdit
1688                 if ($(e.target).parents().index(g.cEdit) == -1) {
1689                     g.hideEditCell();
1690                 }
1691             }).keydown(function(e) {
1692                 if (e.which == 27 && g.isCellEditActive) {
1694                     // cancel on pressing "Esc"
1695                     g.hideEditCell(true);
1696                 }
1697             });
1698             $('div.save_edited').click(function() {
1699                 g.hideEditCell();
1700                 g.postEditedCell();
1701             });
1702             $(window).bind('beforeunload', function(e) {
1703                 if (g.isCellEdited) {
1704                     return g.saveCellWarning;
1705                 }
1706             });
1708             // attach to global div
1709             $(g.gDiv).append(g.cEdit);
1711             // add hint for grid editing feature when hovering "Edit" link in each table row
1712             if (PMA_messages['strGridEditFeatureHint'] != undefined) {
1713                 PMA_tooltip(
1714                     $(g.t).find('.edit_row_anchor a'),
1715                     'a',
1716                     PMA_messages['strGridEditFeatureHint']
1717                 );
1718             }
1719         }
1720     };
1722     /******************
1723      * Initialize grid
1724      ******************/
1726     // wrap all data cells, except actions cell, with span
1727     $(t).find('th, td:not(:has(span))')
1728         .wrapInner('<span />');
1730     // create grid elements
1731     g.gDiv = document.createElement('div');     // create global div
1733     // initialize the table variable
1734     g.t = t;
1736     // get data columns in the first row of the table
1737     var $firstRowCols = $(t).find('tr:first th.draggable');
1739     // initialize visible headers count
1740     g.visibleHeadersCount = $firstRowCols.filter(':visible').length;
1742     // assign first column (actions) span
1743     if (! $(t).find('tr:first th:first').hasClass('draggable')) {  // action header exist
1744         g.actionSpan = $(t).find('tr:first th:first').prop('colspan');
1745     } else {
1746         g.actionSpan = 0;
1747     }
1749     // assign table create time
1750     // #table_create_time will only available if we are in "Browse" tab
1751     g.tableCreateTime = $('#table_create_time').val();
1753     // assign the hints
1754     g.sortHint = PMA_messages['strSortHint'];
1755     g.markHint = PMA_messages['strColMarkHint'];
1756     g.copyHint = PMA_messages['strColNameCopyHint'];
1758     // assign common hidden inputs
1759     var $common_hidden_inputs = $('div.common_hidden_inputs');
1760     g.token = $common_hidden_inputs.find('input[name=token]').val();
1761     g.server = $common_hidden_inputs.find('input[name=server]').val();
1762     g.db = $common_hidden_inputs.find('input[name=db]').val();
1763     g.table = $common_hidden_inputs.find('input[name=table]').val();
1765     // add table class
1766     $(t).addClass('pma_table');
1768     // add relative position to global div so that resize handlers are correctly positioned
1769     $(g.gDiv).css('position', 'relative');
1771     // link the global div
1772     $(t).before(g.gDiv);
1773     $(g.gDiv).append(t);
1775     // FEATURES
1776     enableResize    = enableResize == undefined ? true : enableResize;
1777     enableReorder   = enableReorder == undefined ? true : enableReorder;
1778     enableVisib     = enableVisib == undefined ? true : enableVisib;
1779     enableGridEdit  = enableGridEdit == undefined ? true : enableGridEdit;
1780     if (enableResize) {
1781         g.initColResize();
1782     }
1783     if (enableReorder &&
1784         $('table.navigation').length > 0)    // disable reordering for result from EXPLAIN or SHOW syntax, which do not have a table navigation panel
1785     {
1786         g.initColReorder();
1787     }
1788     if (enableVisib) {
1789         g.initColVisib();
1790     }
1791     if (enableGridEdit &&
1792         $(t).is('.ajax'))   // make sure we have the ajax class
1793     {
1794         g.initGridEdit();
1795     }
1797     // create tooltip for each <th> with draggable class
1798     PMA_tooltip(
1799             $(t).find("th.draggable"),
1800             'th',
1801             g.updateHint()
1802     );
1804     // register events for hint tooltip (anchors inside draggable th)
1805     $(t).find('th.draggable a')
1806         .mouseenter(function(e) {
1807             g.showSortHint = true;
1808             $(t).find("th.draggable").tooltip("option", {
1809                 content: g.updateHint()
1810             }); 
1811         })
1812         .mouseleave(function(e) {
1813             g.showSortHint = false;
1814             $(t).find("th.draggable").tooltip("option", {
1815                 content: g.updateHint()
1816             }); 
1817         });
1819     // register events for dragging-related feature
1820     if (enableResize || enableReorder) {
1821         $(document).mousemove(function(e) {
1822             g.dragMove(e);
1823         });
1824         $(document).mouseup(function(e) {
1825             g.dragEnd(e);
1826         });
1827     }
1829     // some adjustment
1830     $(t).removeClass('data');
1831     $(g.gDiv).addClass('data');