Translation update done using Pootle.
[phpmyadmin/madhuracj.git] / js / makegrid.js
blobe7f2d32f5a0beac91b788c4c614f572c95b2b1d2
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                     var $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('.edit_box')
577                         .css({
578                             width: $cell.outerWidth(),
579                             height: $cell.outerHeight()
580                         });
581                     // fill the cell edit with text from <td>
582                     var value = PMA_getCellValue(cell);
583                     $(g.cEdit).find('.edit_box').val(value);
585                     g.currentEditCell = cell;
586                     $(g.cEdit).find('.edit_box').focus();
587                     $(g.cEdit).find('*').removeAttr('disabled');
588                 }
589             }
590         },
592         /**
593          * Remove edit cell and the edit area, if it is shown.
594          *
595          * @param force Optional, force to hide edit cell without saving edited field.
596          * @param data  Optional, data from the POST AJAX request to save the edited field
597          *              or just specify "true", if we want to replace the edited field with the new value.
598          * @param field Optional, the edited <td>. If not specified, the function will
599          *              use currently edited <td> from g.currentEditCell.
600          */
601         hideEditCell: function(force, data, field) {
602             if (g.isCellEditActive && !force) {
603                 // cell is being edited, save or post the edited data
604                 g.saveOrPostEditedCell();
605                 return;
606             }
608             // cancel any previous request
609             if (g.lastXHR != null) {
610                 g.lastXHR.abort();
611                 g.lastXHR = null;
612             }
614             if (data) {
615                 if (g.currentEditCell) {    // save value of currently edited cell
616                     // replace current edited field with the new value
617                     var $this_field = $(g.currentEditCell);
618                     var is_null = $this_field.data('value') == null;
619                     if (is_null) {
620                         $this_field.find('span').html('NULL');
621                         $this_field.addClass('null');
622                     } else {
623                         $this_field.removeClass('null');
624                         var new_html = $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 goto link, if this cell contains a link
708                 if ($td.find('a').length > 0) {
709                     var gotoLink = document.createElement('div');
710                     gotoLink.className = 'goto_link';
711                     $(gotoLink).append(g.gotoLinkText + ': ')
712                         .append($td.find('a').clone());
713                     $editArea.append(gotoLink);
714                 }
716                 g.wasEditedCellNull = false;
717                 if ($td.is(':not(.not_null)')) {
718                     // append a null checkbox
719                     $editArea.append('<div class="null_div">Null :<input type="checkbox"></div>');
720                     var $checkbox = $editArea.find('.null_div input');
721                     // check if current <td> is NULL
722                     if ($td.is('.null')) {
723                         $checkbox.attr('checked', true);
724                         g.wasEditedCellNull = true;
725                     }
727                     // if the select/editor is changed un-check the 'checkbox_null_<field_name>_<row_index>'.
728                     if ($td.is('.enum, .set')) {
729                         $editArea.find('select').live('change', function(e) {
730                             $checkbox.attr('checked', false);
731                         });
732                     } else if ($td.is('.relation')) {
733                         $editArea.find('select').live('change', function(e) {
734                             $checkbox.attr('checked', false);
735                         });
736                         $editArea.find('.browse_foreign').live('click', function(e) {
737                             $checkbox.attr('checked', false);
738                         });
739                     } else {
740                         $(g.cEdit).find('.edit_box').live('keypress change', function(e) {
741                             $checkbox.attr('checked', false);
742                         });
743                         $editArea.find('textarea').live('keydown', function(e) {
744                             $checkbox.attr('checked', false);
745                         });
746                     }
748                     // if null checkbox is clicked empty the corresponding select/editor.
749                     $checkbox.click(function(e) {
750                         if ($td.is('.enum')) {
751                             $editArea.find('select').attr('value', '');
752                         } else if ($td.is('.set')) {
753                             $editArea.find('select').find('option').each(function() {
754                                 var $option = $(this);
755                                 $option.attr('selected', false);
756                             });
757                         } else if ($td.is('.relation')) {
758                             // if the dropdown is there to select the foreign value
759                             if ($editArea.find('select').length > 0) {
760                                 $editArea.find('select').attr('value', '');
761                             }
762                         } else {
763                             $editArea.find('textarea').val('');
764                         }
765                         $(g.cEdit).find('.edit_box').val('');
766                     });
767                 }
769                 if ($td.is('.relation')) {
770                     //handle relations
771                     $editArea.addClass('edit_area_loading');
773                     // initialize the original data
774                     $td.data('original_data', null);
776                     /**
777                      * @var post_params Object containing parameters for the POST request
778                      */
779                     var post_params = {
780                         'ajax_request' : true,
781                         'get_relational_values' : true,
782                         'server' : g.server,
783                         'db' : g.db,
784                         'table' : g.table,
785                         'column' : field_name,
786                         'token' : g.token,
787                         'curr_value' : relation_curr_value,
788                         'relation_key_or_display_column' : relation_key_or_display_column
789                     }
791                     g.lastXHR = $.post('sql.php', post_params, function(data) {
792                         g.lastXHR = null;
793                         $editArea.removeClass('edit_area_loading');
794                         if ($(data.dropdown).is('select')) {
795                             // save original_data
796                             var value = $(data.dropdown).val();
797                             $td.data('original_data', value);
798                             // update the text input field, in case where the "Relational display column" is checked
799                             $(g.cEdit).find('.edit_box').val(value);
800                         }
802                         $editArea.append(data.dropdown);
803                         $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
804                     }) // end $.post()
806                     $editArea.find('select').live('change', function(e) {
807                         $(g.cEdit).find('.edit_box').val($(this).val());
808                     })
809                     $editArea.show();
810                 }
811                 else if($td.is('.enum')) {
812                     //handle enum fields
813                     $editArea.addClass('edit_area_loading');
815                     /**
816                      * @var post_params Object containing parameters for the POST request
817                      */
818                     var post_params = {
819                             'ajax_request' : true,
820                             'get_enum_values' : true,
821                             'server' : g.server,
822                             'db' : g.db,
823                             'table' : g.table,
824                             'column' : field_name,
825                             'token' : g.token,
826                             'curr_value' : curr_value
827                     }
828                     g.lastXHR = $.post('sql.php', post_params, function(data) {
829                         g.lastXHR = null;
830                         $editArea.removeClass('edit_area_loading');
831                         $editArea.append(data.dropdown);
832                         $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
833                     }) // end $.post()
835                     $editArea.find('select').live('change', function(e) {
836                         $(g.cEdit).find('.edit_box').val($(this).val());
837                     })
838                     $editArea.show();
839                 }
840                 else if($td.is('.set')) {
841                     //handle set fields
842                     $editArea.addClass('edit_area_loading');
844                     /**
845                      * @var post_params Object containing parameters for the POST request
846                      */
847                     var post_params = {
848                             'ajax_request' : true,
849                             'get_set_values' : true,
850                             'server' : g.server,
851                             'db' : g.db,
852                             'table' : g.table,
853                             'column' : field_name,
854                             'token' : g.token,
855                             'curr_value' : curr_value
856                     }
858                     g.lastXHR = $.post('sql.php', post_params, function(data) {
859                         g.lastXHR = null;
860                         $editArea.removeClass('edit_area_loading');
861                         $editArea.append(data.select);
862                         $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
863                     }) // end $.post()
865                     $editArea.find('select').live('change', function(e) {
866                         $(g.cEdit).find('.edit_box').val($(this).val());
867                     })
868                     $editArea.show();
869                 }
870                 else if($td.is('.truncated, .transformed')) {
871                     if ($td.is('.to_be_saved')) {   // cell has been edited
872                         var value = $td.data('value');
873                         $(g.cEdit).find('.edit_box').val(value);
874                         $editArea.append('<textarea></textarea>');
875                         $editArea.find('textarea')
876                             .val(value)
877                             .live('keyup', function(e) {
878                                 $(g.cEdit).find('.edit_box').val($(this).val());
879                             });
880                         $(g.cEdit).find('.edit_box').live('keyup', function(e) {
881                             $editArea.find('textarea').val($(this).val());
882                         });
883                         $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
884                     } else {
885                         //handle truncated/transformed values values
886                         $editArea.addClass('edit_area_loading');
888                         // initialize the original data
889                         $td.data('original_data', null);
891                         /**
892                          * @var sql_query   String containing the SQL query used to retrieve value of truncated/transformed data
893                          */
894                         var sql_query = 'SELECT `' + field_name + '` FROM `' + g.table + '` WHERE ' + PMA_urldecode(where_clause);
896                         // Make the Ajax call and get the data, wrap it and insert it
897                         g.lastXHR = $.post('sql.php', {
898                             'token' : g.token,
899                             'server' : g.server,
900                             'db' : g.db,
901                             'ajax_request' : true,
902                             'sql_query' : sql_query,
903                             'grid_edit' : true
904                         }, function(data) {
905                             g.lastXHR = null;
906                             $editArea.removeClass('edit_area_loading');
907                             if(data.success == true) {
908                                 if ($td.is('.truncated')) {
909                                     // get the truncated data length
910                                     g.maxTruncatedLen = $(g.currentEditCell).text().length - 3;
911                                 }
913                                 $td.data('original_data', data.value);
914                                 $(g.cEdit).find('.edit_box').val(data.value);
915                                 $editArea.append('<textarea></textarea>');
916                                 $editArea.find('textarea')
917                                     .val(data.value)
918                                     .live('keyup', function(e) {
919                                         $(g.cEdit).find('.edit_box').val($(this).val());
920                                     });
921                                 $(g.cEdit).find('.edit_box').live('keyup', function(e) {
922                                     $editArea.find('textarea').val($(this).val());
923                                 });
924                                 $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
925                             }
926                             else {
927                                 PMA_ajaxShowMessage(data.error);
928                             }
929                         }) // end $.post()
930                     }
931                     g.isEditCellTextEditable = true;
932                     $editArea.show();
933                 } else if ($td.is('.datefield, .datetimefield, .timestampfield')) {
934                     var $input_field = $(g.cEdit).find('.edit_box');
935                     
936                     // remember current datetime value in $input_field, if it is not null
937                     var is_null = $td.is('.null');
938                     var current_datetime_value = !is_null ? $input_field.val() : '';
939                     
940                     var showTimeOption = true;
941                     if ($td.is('.datefield')) {
942                         showTimeOption = false;
943                     }
944                     PMA_addDatepicker($editArea, {
945                         altField: $input_field,
946                         showTimepicker: showTimeOption,
947                         onSelect: function(dateText, inst) {
948                             // remove null checkbox if it exists
949                             $(g.cEdit).find('.null_div input[type=checkbox]').attr('checked', false);
950                         }
951                     });
952                     
953                     // cancel any click on the datepicker element
954                     $editArea.find('> *').click(function(e) {
955                         e.stopPropagation();
956                     });
957                     
958                     // force to restore modified $input_field value after adding datepicker
959                     // (after adding a datepicker, the input field doesn't display the time anymore, only the date)
960                     if (!is_null) {
961                         $editArea.datetimepicker('setDate', current_datetime_value);
962                     } else {
963                         $input_field.val('');
964                     }
965                     $editArea.show();
966                 } else {
967                     g.isEditCellTextEditable = true;
968                 }
969             }
970         },
972         /**
973          * Post the content of edited cell.
974          */
975         postEditedCell: function() {
976             if (g.isSaving) {
977                 return;
978             }
979             g.isSaving = true;
981             /**
982              * @var relation_fields Array containing the name/value pairs of relational fields
983              */
984             var relation_fields = {};
985             /**
986              * @var relational_display string 'K' if relational key, 'D' if relational display column
987              */
988             var relational_display = $("#relational_display_K").attr('checked') ? 'K' : 'D';
989             /**
990              * @var transform_fields    Array containing the name/value pairs for transformed fields
991              */
992             var transform_fields = {};
993             /**
994              * @var transformation_fields   Boolean, if there are any transformed fields in the edited cells
995              */
996             var transformation_fields = false;
997             /**
998              * @var full_sql_query String containing the complete SQL query to update this table
999              */
1000             var full_sql_query = '';
1001             /**
1002              * @var rel_fields_list  String, url encoded representation of {@link relations_fields}
1003              */
1004             var rel_fields_list = '';
1005             /**
1006              * @var transform_fields_list  String, url encoded representation of {@link transform_fields}
1007              */
1008             var transform_fields_list = '';
1009             /**
1010              * @var where_clause Array containing where clause for updated fields
1011              */
1012             var full_where_clause = Array();
1013             /**
1014              * @var is_unique   Boolean, whether the rows in this table is unique or not
1015              */
1016             var is_unique = $('.edit_row_anchor').is('.nonunique') ? 0 : 1;
1017             /**
1018              * multi edit variables
1019              */
1020             var me_fields_name = Array();
1021             var me_fields = Array();
1022             var me_fields_null = Array();
1024             // alert user if edited table is not unique
1025             if (!is_unique) {
1026                 alert(g.alertNonUnique);
1027             }
1029             // loop each edited row
1030             $('.to_be_saved').parents('tr').each(function() {
1031                 var $tr = $(this);
1032                 var where_clause = $tr.find('.where_clause').val();
1033                 full_where_clause.push(PMA_urldecode(where_clause));
1034                 var condition_array = jQuery.parseJSON($tr.find('.condition_array').val());
1036                 /**
1037                  * multi edit variables, for current row
1038                  * @TODO array indices are still not correct, they should be md5 of field's name
1039                  */
1040                 var fields_name = Array();
1041                 var fields = Array();
1042                 var fields_null = Array();
1044                 // loop each edited cell in a row
1045                 $tr.find('.to_be_saved').each(function() {
1046                     /**
1047                      * @var $this_field    Object referring to the td that is being edited
1048                      */
1049                     var $this_field = $(this);
1051                     /**
1052                      * @var field_name  String containing the name of this field.
1053                      * @see getFieldName()
1054                      */
1055                     var field_name = getFieldName($this_field);
1057                     /**
1058                      * @var this_field_params   Array temporary storage for the name/value of current field
1059                      */
1060                     var this_field_params = {};
1062                     if($this_field.is('.transformed')) {
1063                         transformation_fields =  true;
1064                     }
1065                     this_field_params[field_name] = $this_field.data('value');
1067                     /**
1068                      * @var is_null String capturing whether 'checkbox_null_<field_name>_<row_index>' is checked.
1069                      */
1070                     var is_null = this_field_params[field_name] === null;
1072                     fields_name.push(field_name);
1074                     if (is_null) {
1075                         fields_null.push('on');
1076                         fields.push('');
1077                     } else {
1078                         fields_null.push('');
1079                         fields.push($this_field.data('value'));
1081                         var cell_index = $this_field.index('.to_be_saved');
1082                         if($this_field.is(":not(.relation, .enum, .set, .bit)")) {
1083                             if($this_field.is('.transformed')) {
1084                                 transform_fields[cell_index] = {};
1085                                 $.extend(transform_fields[cell_index], this_field_params);
1086                             }
1087                         } else if($this_field.is('.relation')) {
1088                             relation_fields[cell_index] = {};
1089                             $.extend(relation_fields[cell_index], this_field_params);
1090                         }
1091                     }
1092                     // check if edited field appears in WHERE clause
1093                     if (where_clause.indexOf(PMA_urlencode(field_name)) > -1) {
1094                         var field_str = '`' + g.table + '`.' + '`' + field_name + '`';
1095                         for (var field in condition_array) {
1096                             if (field.indexOf(field_str) > -1) {
1097                                 condition_array[field] = is_null ? 'IS NULL' : "= '" + this_field_params[field_name].replace(/'/g,"''") + "'";
1098                                 break;
1099                             }
1100                         }
1101                     }
1103                 }); // end of loop for every edited cells in a row
1105                 // save new_clause
1106                 var new_clause = '';
1107                 for (var field in condition_array) {
1108                     new_clause += field + ' ' + condition_array[field] + ' AND ';
1109                 }
1110                 new_clause = new_clause.substring(0, new_clause.length - 5); // remove the last AND
1111                 new_clause = PMA_urlencode(new_clause);
1112                 $tr.data('new_clause', new_clause);
1113                 // save condition_array
1114                 $tr.find('.condition_array').val(JSON.stringify(condition_array));
1116                 me_fields_name.push(fields_name);
1117                 me_fields.push(fields);
1118                 me_fields_null.push(fields_null);
1120             }); // end of loop for every edited rows
1122             rel_fields_list = $.param(relation_fields);
1123             transform_fields_list = $.param(transform_fields);
1125             // Make the Ajax post after setting all parameters
1126             /**
1127              * @var post_params Object containing parameters for the POST request
1128              */
1129             var post_params = {'ajax_request' : true,
1130                             'sql_query' : full_sql_query,
1131                             'token' : g.token,
1132                             'server' : g.server,
1133                             'db' : g.db,
1134                             'table' : g.table,
1135                             'clause_is_unique' : is_unique,
1136                             'where_clause' : full_where_clause,
1137                             'fields[multi_edit]' : me_fields,
1138                             'fields_name[multi_edit]' : me_fields_name,
1139                             'fields_null[multi_edit]' : me_fields_null,
1140                             'rel_fields_list' : rel_fields_list,
1141                             'do_transformations' : transformation_fields,
1142                             'transform_fields_list' : transform_fields_list,
1143                             'relational_display' : relational_display,
1144                             'goto' : 'sql.php',
1145                             'submit_type' : 'save'
1146                           };
1148             if (!g.saveCellsAtOnce) {
1149                 $(g.cEdit).find('*').attr('disabled', 'disabled');
1150                 var $editArea = $(g.cEdit).find('.edit_area');
1151                 $(g.cEdit).find('.edit_box').addClass('edit_box_posting');
1152             } else {
1153                 $('.save_edited').addClass('saving_edited_data')
1154                     .find('input').attr('disabled', 'disabled');    // disable the save button
1155             }
1157             $.ajax({
1158                 type: 'POST',
1159                 url: 'tbl_replace.php',
1160                 data: post_params,
1161                 success:
1162                     function(data) {
1163                         g.isSaving = false;
1164                         if (!g.saveCellsAtOnce) {
1165                             $(g.cEdit).find('*').removeAttr('disabled');
1166                             $(g.cEdit).find('.edit_box').removeClass('edit_box_posting');
1167                         } else {
1168                             $('.save_edited').removeClass('saving_edited_data')
1169                                 .find('input').removeAttr('disabled');  // enable the save button back
1170                         }
1171                         if(data.success == true) {
1172                             PMA_ajaxShowMessage(data.message);
1173                             // update where_clause related data in each edited row
1174                             $('.to_be_saved').parents('tr').each(function() {
1175                                 var new_clause = $(this).data('new_clause');
1176                                 var $where_clause = $(this).find('.where_clause');
1177                                 var old_clause = $where_clause.attr('value');
1178                                 var decoded_old_clause = PMA_urldecode(old_clause);
1179                                 var decoded_new_clause = PMA_urldecode(new_clause);
1181                                 $where_clause.attr('value', new_clause);
1182                                 // update Edit, Copy, and Delete links also
1183                                 $(this).find('a').each(function() {
1184                                     $(this).attr('href', $(this).attr('href').replace(old_clause, new_clause));
1185                                     // update delete confirmation in Delete link
1186                                     if ($(this).attr('href').indexOf('DELETE') > -1) {
1187                                         $(this).removeAttr('onclick')
1188                                             .unbind('click')
1189                                             .bind('click', function() {
1190                                                 return confirmLink(this, 'DELETE FROM `' + g.db + '`.`' + g.table + '` WHERE ' +
1191                                                        decoded_new_clause + (is_unique ? '' : ' LIMIT 1'));
1192                                             });
1193                                     }
1194                                 });
1195                                 // update the multi edit checkboxes
1196                                 $(this).find('input[type=checkbox]').each(function() {
1197                                     var $checkbox = $(this);
1198                                     var checkbox_name = $checkbox.attr('name');
1199                                     var checkbox_value = $checkbox.attr('value');
1201                                     $checkbox.attr('name', checkbox_name.replace(old_clause, new_clause));
1202                                     $checkbox.attr('value', checkbox_value.replace(decoded_old_clause, decoded_new_clause));
1203                                 });
1204                             });
1205                             // update the display of executed SQL query command
1206                             $('#result_query').remove();
1207                             if (typeof data.sql_query != 'undefined') {
1208                                 // display feedback
1209                                 $('#sqlqueryresults').prepend(data.sql_query);
1210                             }
1211                             // hide and/or update the successfully saved cells
1212                             g.hideEditCell(true, data);
1214                             // remove the "Save edited cells" button
1215                             $('.save_edited').hide();
1216                             // update saved fields
1217                             $(g.t).find('.to_be_saved')
1218                                 .removeClass('to_be_saved')
1219                                 .data('value', null)
1220                                 .data('original_data', null);
1222                             g.isCellEdited = false;
1223                         } else {
1224                             PMA_ajaxShowMessage(data.error);
1225                         }
1226                     }
1227             }) // end $.ajax()
1228         },
1230         /**
1231          * Save edited cell, so it can be posted later.
1232          */
1233         saveEditedCell: function() {
1234             /**
1235              * @var $this_field    Object referring to the td that is being edited
1236              */
1237             var $this_field = $(g.currentEditCell);
1238             var $test_element = ''; // to test the presence of a element
1240             var need_to_post = false;
1242             /**
1243              * @var field_name  String containing the name of this field.
1244              * @see getFieldName()
1245              */
1246             var field_name = getFieldName($this_field);
1248             /**
1249              * @var this_field_params   Array temporary storage for the name/value of current field
1250              */
1251             var this_field_params = {};
1253             /**
1254              * @var is_null String capturing whether 'checkbox_null_<field_name>_<row_index>' is checked.
1255              */
1256             var is_null = $(g.cEdit).find('input:checkbox').is(':checked');
1257             var value;
1259             if ($(g.cEdit).find('.edit_area').is('.edit_area_loading')) {
1260                 // the edit area is still loading (retrieving cell data), no need to post
1261                 need_to_post = false;
1262             } else if (is_null) {
1263                 if (!g.wasEditedCellNull) {
1264                     this_field_params[field_name] = null;
1265                     need_to_post = true;
1266                 }
1267             } else {
1268                 if ($this_field.is('.bit')) {
1269                     this_field_params[field_name] = '0b' + $(g.cEdit).find('.edit_box').val();
1270                 } else if ($this_field.is('.set')) {
1271                     $test_element = $(g.cEdit).find('select');
1272                     this_field_params[field_name] = $test_element.map(function(){
1273                         return $(this).val();
1274                     }).get().join(",");
1275                 } else if ($this_field.is('.relation, .enum')) {
1276                     // results from a drop-down
1277                     $test_element = $(g.cEdit).find('select');
1278                     if ($test_element.length != 0) {
1279                         this_field_params[field_name] = $test_element.val();
1280                     }
1282                     // results from Browse foreign value
1283                     $test_element = $(g.cEdit).find('span.curr_value');
1284                     if ($test_element.length != 0) {
1285                         this_field_params[field_name] = $test_element.text();
1286                     }
1287                 } else {
1288                     this_field_params[field_name] = $(g.cEdit).find('.edit_box').val();
1289                 }
1290                 if (g.wasEditedCellNull || this_field_params[field_name] != PMA_getCellValue(g.currentEditCell)) {
1291                     need_to_post = true;
1292                 }
1293             }
1295             if (need_to_post) {
1296                 $(g.currentEditCell).addClass('to_be_saved')
1297                     .data('value', this_field_params[field_name]);
1298                 if (g.saveCellsAtOnce) {
1299                     $('.save_edited').show();
1300                 }
1301                 g.isCellEdited = true;
1302             }
1304             return need_to_post;
1305         },
1307         /**
1308          * Save or post currently edited cell, depending on the "saveCellsAtOnce" configuration.
1309          */
1310         saveOrPostEditedCell: function() {
1311             var saved = g.saveEditedCell();
1312             if (!g.saveCellsAtOnce) {
1313                 if (saved) {
1314                     g.postEditedCell();
1315                 } else {
1316                     g.hideEditCell(true);
1317                 }
1318             } else {
1319                 if (saved) {
1320                     g.hideEditCell(true, true);
1321                 } else {
1322                     g.hideEditCell(true);
1323                 }
1324             }
1325         },
1327         /**
1328          * Initialize column resize feature.
1329          */
1330         initColResize: function() {
1331             // create column resizer div
1332             g.cRsz = document.createElement('div');
1333             g.cRsz.className = 'cRsz';
1335             // get data columns in the first row of the table
1336             var $firstRowCols = $(g.t).find('tr:first th.draggable');
1338             // create column borders
1339             $firstRowCols.each(function() {
1340                 var cb = document.createElement('div'); // column border
1341                 $(cb).addClass('colborder')
1342                     .mousedown(function(e) {
1343                         g.dragStartRsz(e, this);
1344                     });
1345                 $(g.cRsz).append(cb);
1346             });
1347             g.reposRsz();
1349             // attach to global div
1350             $(g.gDiv).prepend(g.cRsz);
1351         },
1353         /**
1354          * Initialize column reordering feature.
1355          */
1356         initColReorder: function() {
1357             g.cCpy = document.createElement('div');     // column copy, to store copy of dragged column header
1358             g.cPointer = document.createElement('div'); // column pointer, used when reordering column
1360             // adjust g.cCpy
1361             g.cCpy.className = 'cCpy';
1362             $(g.cCpy).hide();
1364             // adjust g.cPointer
1365             g.cPointer.className = 'cPointer';
1366             $(g.cPointer).css('visibility', 'hidden');  // set visibility to hidden instead of calling hide() to force browsers to cache the image in cPointer class
1368             // assign column reordering hint
1369             g.reorderHint = PMA_messages['strColOrderHint'];
1371             // get data columns in the first row of the table
1372             var $firstRowCols = $(g.t).find('tr:first th.draggable');
1374             // initialize column order
1375             $col_order = $('#col_order');   // check if column order is passed from PHP
1376             if ($col_order.length > 0) {
1377                 g.colOrder = $col_order.val().split(',');
1378                 for (var i = 0; i < g.colOrder.length; i++) {
1379                     g.colOrder[i] = parseInt(g.colOrder[i]);
1380                 }
1381             } else {
1382                 g.colOrder = new Array();
1383                 for (var i = 0; i < $firstRowCols.length; i++) {
1384                     g.colOrder.push(i);
1385                 }
1386             }
1388             // register events
1389             $(t).find('th.draggable')
1390                 .mousedown(function(e) {
1391                     if (g.visibleHeadersCount > 1) {
1392                         g.dragStartReorder(e, this);
1393                     }
1394                 })
1395                 .mouseenter(function(e) {
1396                     if (g.visibleHeadersCount > 1) {
1397                         g.showReorderHint = true;
1398                         $(this).css('cursor', 'move');
1399                     } else {
1400                         $(this).css('cursor', 'inherit');
1401                     }
1402                 })
1403                 .mouseleave(function(e) {
1404                     g.showReorderHint = false;
1405                 });
1406             // restore column order when the restore button is clicked
1407             $('.restore_column').click(function() {
1408                 g.restoreColOrder();
1409             });
1411             // attach to global div
1412             $(g.gDiv).append(g.cPointer);
1413             $(g.gDiv).append(g.cCpy);
1415             // prevent default "dragstart" event when dragging a link
1416             $(t).find('th a').bind('dragstart', function() {
1417                 return false;
1418             });
1420             // refresh the restore column button state
1421             g.refreshRestoreButton();
1422         },
1424         /**
1425          * Initialize column visibility feature.
1426          */
1427         initColVisib: function() {
1428             g.cDrop = document.createElement('div');    // column drop-down arrows
1429             g.cList = document.createElement('div');    // column visibility list
1431             // adjust g.cDrop
1432             g.cDrop.className = 'cDrop';
1434             // adjust g.cList
1435             g.cList.className = 'cList';
1436             $(g.cList).hide();
1438             // assign column visibility related hints
1439             g.colVisibHint = PMA_messages['strColVisibHint'];
1440             g.showAllColText = PMA_messages['strShowAllCol'];
1442             // get data columns in the first row of the table
1443             var $firstRowCols = $(g.t).find('tr:first th.draggable');
1445             // initialize column visibility
1446             $col_visib = $('#col_visib');   // check if column visibility is passed from PHP
1447             if ($col_visib.length > 0) {
1448                 g.colVisib = $col_visib.val().split(',');
1449                 for (var i = 0; i < g.colVisib.length; i++) {
1450                     g.colVisib[i] = parseInt(g.colVisib[i]);
1451                 }
1452             } else {
1453                 g.colVisib = new Array();
1454                 for (var i = 0; i < $firstRowCols.length; i++) {
1455                     g.colVisib.push(1);
1456                 }
1457             }
1459             // get data columns in the first row of the table
1460             var $firstRowCols = $(t).find('tr:first th.draggable');
1462             // make sure we have more than one column
1463             if ($firstRowCols.length > 1) {
1464                 var $colVisibTh = $(g.t).find('th:not(.draggable)');
1465                 PMA_createqTip($colVisibTh);
1467                 // create column visibility drop-down arrow(s)
1468                 $colVisibTh.each(function() {
1469                         var $th = $(this);
1470                         var cd = document.createElement('div'); // column drop-down arrow
1471                         var pos = $th.position();
1472                         $(cd).addClass('coldrop')
1473                             .click(function() {
1474                                 if (g.cList.style.display == 'none') {
1475                                     g.showColList(this);
1476                                 } else {
1477                                     g.hideColList();
1478                                 }
1479                             });
1480                         $(g.cDrop).append(cd);
1481                     })
1482                     .mouseenter(function(e) {
1483                         g.showColVisibHint = true;
1484                     })
1485                     .mouseleave(function(e) {
1486                         g.showColVisibHint = false;
1487                     });
1489                 // add column visibility control
1490                 g.cList.innerHTML = '<div class="lDiv"></div>';
1491                 var $listDiv = $(g.cList).find('div');
1492                 for (var i = 0; i < $firstRowCols.length; i++) {
1493                     var currHeader = $firstRowCols[i];
1494                     var listElmt = document.createElement('div');
1495                     $(listElmt).text($(currHeader).text())
1496                         .prepend('<input type="checkbox" ' + (g.colVisib[i] ? 'checked="checked" ' : '') + '/>');
1497                     $listDiv.append(listElmt);
1498                     // add event on click
1499                     $(listElmt).click(function() {
1500                         if ( g.toggleCol($(this).index()) ) {
1501                             g.afterToggleCol();
1502                         }
1503                     });
1504                 }
1505                 // add "show all column" button
1506                 var showAll = document.createElement('div');
1507                 $(showAll).addClass('showAllColBtn')
1508                     .text(g.showAllColText);
1509                 $(g.cList).append(showAll);
1510                 $(showAll).click(function() {
1511                     g.showAllColumns();
1512                 });
1513                 // prepend "show all column" button at top if the list is too long
1514                 if ($firstRowCols.length > 10) {
1515                     var clone = showAll.cloneNode(true);
1516                     $(g.cList).prepend(clone);
1517                     $(clone).click(function() {
1518                         g.showAllColumns();
1519                     });
1520                 }
1521             }
1523             // hide column visibility list if we move outside the list
1524             $(t).find('td, th.draggable').mouseenter(function() {
1525                 g.hideColList();
1526             });
1528             // attach to global div
1529             $(g.gDiv).append(g.cDrop);
1530             $(g.gDiv).append(g.cList);
1532             // some adjustment
1533             g.reposDrop();
1534         },
1536         /**
1537          * Initialize grid editing feature.
1538          */
1539         initGridEdit: function() {
1540             // create cell edit wrapper element
1541             g.cEdit = document.createElement('div');
1543             // adjust g.cEdit
1544             g.cEdit.className = 'cEdit';
1545             $(g.cEdit).html('<textarea class="edit_box" rows="1" ></textarea><div class="edit_area" />');
1546             $(g.cEdit).hide();
1548             // assign cell editing hint
1549             g.cellEditHint = PMA_messages['strCellEditHint'];
1550             g.saveCellWarning = PMA_messages['strSaveCellWarning'];
1551             g.alertNonUnique = PMA_messages['strAlertNonUnique'];
1552             g.gotoLinkText = PMA_messages['strGoToLink'];
1554             // initialize cell editing configuration
1555             g.saveCellsAtOnce = $('#save_cells_at_once').val();
1557             // register events
1558             $(t).find('td.data')
1559                 .click(function(e) {
1560                     if (g.isCellEditActive) {
1561                         g.saveOrPostEditedCell();
1562                         e.stopPropagation();
1563                     } else {
1564                         g.showEditCell(this);
1565                         e.stopPropagation();
1566                     }
1567                     // prevent default action when clicking on "link" in a table
1568                     if ($(e.target).is('a')) {
1569                         e.preventDefault();
1570                     }
1571                 });
1572             $(g.cEdit).find('.edit_box').focus(function(e) {
1573                 g.showEditArea();
1574             });
1575             $(g.cEdit).find('.edit_box, select').live('keydown', function(e) {
1576                 if (e.which == 13) {
1577                     // post on pressing "Enter"
1578                     e.preventDefault();
1579                     g.saveOrPostEditedCell();
1580                 }
1581             });
1582             $(g.cEdit).keydown(function(e) {
1583                 if (!g.isEditCellTextEditable) {
1584                     // prevent text editing
1585                     e.preventDefault();
1586                 }
1587             });
1588             $('html').click(function(e) {
1589                 // hide edit cell if the click is not from g.cEdit
1590                 if ($(e.target).parents().index(g.cEdit) == -1) {
1591                     g.hideEditCell();
1592                 }
1593             });
1594             $('html').keydown(function(e) {
1595                 if (e.which == 27 && g.isCellEditActive) {
1597                     // cancel on pressing "Esc"
1598                     g.hideEditCell(true);
1599                 }
1600             });
1601             $('.save_edited').click(function() {
1602                 g.hideEditCell();
1603                 g.postEditedCell();
1604             });
1605             $(window).bind('beforeunload', function(e) {
1606                 if (g.isCellEdited) {
1607                     return g.saveCellWarning;
1608                 }
1609             });
1611             // attach to global div
1612             $(g.gDiv).append(g.cEdit);
1614             // add hint for grid editing feature when hovering "Edit" link in each table row
1615             PMA_createqTip($(g.t).find('.edit_row_anchor a'), PMA_messages['strGridEditFeatureHint']);
1616         }
1617     }
1619     /******************
1620      * Initialize grid
1621      ******************/
1623     // wrap all data cells, except actions cell, with span
1624     $(t).find('th, td:not(:has(span))')
1625         .wrapInner('<span />');
1627     // create grid elements
1628     g.gDiv = document.createElement('div');     // create global div
1630     // initialize the table variable
1631     g.t = t;
1633     // get data columns in the first row of the table
1634     var $firstRowCols = $(t).find('tr:first th.draggable');
1636     // initialize visible headers count
1637     g.visibleHeadersCount = $firstRowCols.filter(':visible').length;
1639     // assign first column (actions) span
1640     if (! $(t).find('tr:first th:first').hasClass('draggable')) {  // action header exist
1641         g.actionSpan = $(t).find('tr:first th:first').prop('colspan');
1642     } else {
1643         g.actionSpan = 0;
1644     }
1646     // assign table create time
1647     // #table_create_time will only available if we are in "Browse" tab
1648     g.tableCreateTime = $('#table_create_time').val();
1650     // assign the hints
1651     g.sortHint = PMA_messages['strSortHint'];
1652     g.markHint = PMA_messages['strColMarkHint'];
1654     // assign common hidden inputs
1655     var $common_hidden_inputs = $('.common_hidden_inputs');
1656     g.token = $common_hidden_inputs.find('input[name=token]').val();
1657     g.server = $common_hidden_inputs.find('input[name=server]').val();
1658     g.db = $common_hidden_inputs.find('input[name=db]').val();
1659     g.table = $common_hidden_inputs.find('input[name=table]').val();
1661     // add table class
1662     $(t).addClass('pma_table');
1664     // add relative position to global div so that resize handlers are correctly positioned
1665     $(g.gDiv).css('position', 'relative');
1667     // link the global div
1668     $(t).before(g.gDiv);
1669     $(g.gDiv).append(t);
1671     // FEATURES
1672     enableResize    = enableResize == undefined ? true : enableResize;
1673     enableReorder   = enableReorder == undefined ? true : enableReorder;
1674     enableVisib     = enableVisib == undefined ? true : enableVisib;
1675     enableGridEdit  = enableGridEdit == undefined ? true : enableGridEdit;
1676     if (enableResize) {
1677         g.initColResize();
1678     }
1679     if (enableReorder &&
1680         $('.navigation').length > 0)    // disable reordering for result from EXPLAIN or SHOW syntax, which do not have a table navigation panel
1681     {
1682         g.initColReorder();
1683     }
1684     if (enableVisib) {
1685         g.initColVisib();
1686     }
1687     if (enableGridEdit &&
1688         $(t).is('.ajax'))   // make sure AjaxEnable is enabled in Settings
1689     {
1690         g.initGridEdit();
1691     }
1693     // create qtip for each <th> with draggable class
1694     PMA_createqTip($(t).find('th.draggable'));
1696     // register events for hint tooltip
1697     $(t).find('th.draggable a')
1698         .attr('title', '')          // hide default tooltip for sorting
1699         .mouseenter(function(e) {
1700             g.showSortHint = true;
1701             g.updateHint(e);
1702         })
1703         .mouseleave(function(e) {
1704             g.showSortHint = false;
1705             g.updateHint(e);
1706         });
1707     $(t).find('th.marker')
1708         .mouseenter(function(e) {
1709             g.showMarkHint = true;
1710         })
1711         .mouseleave(function(e) {
1712             g.showMarkHint = false;
1713         });
1714     // register events for dragging-related feature
1715     if (enableResize || enableReorder) {
1716         $(document).mousemove(function(e) {
1717             g.dragMove(e);
1718         });
1719         $(document).mouseup(function(e) {
1720             g.dragEnd(e);
1721         });
1722     }
1724     // bind event to update currently hovered qtip API
1725     $(t).find('th')
1726         .mouseenter(function(e) {
1727             g.qtip = $(this).qtip('api');
1728             g.updateHint(e);
1729         })
1730         .mouseleave(function(e) {
1731             g.updateHint(e);
1732         });
1734     // some adjustment
1735     $(t).removeClass('data');
1736     $(g.gDiv).addClass('data');