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