updated adodb package to work with php 7.1
[openemr.git] / phpmyadmin / js / sql.js
blob13edb43943dae8be08d39ae62eb133c1edf691e2
1 /* vim: set expandtab sw=4 ts=4 sts=4: */
2 /**
3  * @fileoverview    functions used wherever an sql query form is used
4  *
5  * @requires    jQuery
6  * @requires    js/functions.js
7  *
8  */
10 var $data_a;
11 var prevScrollX = 0;
13 /**
14  * decode a string URL_encoded
15  *
16  * @param string str
17  * @return string the URL-decoded string
18  */
19 function PMA_urldecode(str)
21     if (typeof str !== 'undefined') {
22         return decodeURIComponent(str.replace(/\+/g, '%20'));
23     }
26 /**
27  * endecode a string URL_decoded
28  *
29  * @param string str
30  * @return string the URL-encoded string
31  */
32 function PMA_urlencode(str)
34     if (typeof str !== 'undefined') {
35         return encodeURIComponent(str).replace(/\%20/g, '+');
36     }
39 /**
40  * Get the field name for the current field.  Required to construct the query
41  * for grid editing
42  *
43  * @param $table_results enclosing results table
44  * @param $this_field    jQuery object that points to the current field's tr
45  */
46 function getFieldName($table_results, $this_field)
49     var this_field_index = $this_field.index();
50     // ltr or rtl direction does not impact how the DOM was generated
51     // check if the action column in the left exist
52     var left_action_exist = !$table_results.find('th:first').hasClass('draggable');
53     // number of column span for checkbox and Actions
54     var left_action_skip = left_action_exist ? $table_results.find('th:first').attr('colspan') - 1 : 0;
56     // If this column was sorted, the text of the a element contains something
57     // like <small>1</small> that is useful to indicate the order in case
58     // of a sort on multiple columns; however, we dont want this as part
59     // of the column name so we strip it ( .clone() to .end() )
60     var field_name = $table_results
61         .find('thead')
62         .find('th:eq(' + (this_field_index - left_action_skip) + ') a')
63         .clone()    // clone the element
64         .children() // select all the children
65         .remove()   // remove all of them
66         .end()      // go back to the selected element
67         .text();    // grab the text
68     // happens when just one row (headings contain no a)
69     if (field_name === '') {
70         var $heading = $table_results.find('thead').find('th:eq(' + (this_field_index - left_action_skip) + ')').children('span');
71         // may contain column comment enclosed in a span - detach it temporarily to read the column name
72         var $tempColComment = $heading.children().detach();
73         field_name = $heading.text();
74         // re-attach the column comment
75         $heading.append($tempColComment);
76     }
78     field_name = $.trim(field_name);
80     return field_name;
83 /**
84  * Unbind all event handlers before tearing down a page
85  */
86 AJAX.registerTeardown('sql.js', function () {
87     $(document).off('click', 'a.delete_row.ajax');
88     $(document).off('submit', '.bookmarkQueryForm');
89     $('input#bkm_label').unbind('keyup');
90     $(document).off('makegrid', ".sqlqueryresults");
91     $(document).off('stickycolumns', ".sqlqueryresults");
92     $("#togglequerybox").unbind('click');
93     $(document).off('click', "#button_submit_query");
94     $(document).off('change', '#id_bookmark');
95     $("input[name=bookmark_variable]").unbind("keypress");
96     $(document).off('submit', "#sqlqueryform.ajax");
97     $(document).off('click', "input[name=navig].ajax");
98     $(document).off('submit', "form[name='displayOptionsForm'].ajax");
99     $(document).off('mouseenter', 'th.column_heading.pointer');
100     $(document).off('mouseleave', 'th.column_heading.pointer');
101     $(document).off('click', 'th.column_heading.marker');
102     $(window).unbind('scroll');
103     $(document).off("keyup", ".filter_rows");
104     $(document).off('click', "#printView");
105     if (codemirror_editor) {
106         codemirror_editor.off('change');
107     } else {
108         $('#sqlquery').off('input propertychange');
109     }
110     $('body').off('click', '.navigation .showAllRows');
111     $('body').off('click','a.browse_foreign');
112     $('body').off('click', '#simulate_dml');
113     $('body').off('keyup', '#sqlqueryform');
114     $('body').off('click', 'form[name="resultsForm"].ajax button[name="submit_mult"], form[name="resultsForm"].ajax input[name="submit_mult"]');
118  * @description <p>Ajax scripts for sql and browse pages</p>
120  * Actions ajaxified here:
121  * <ul>
122  * <li>Retrieve results of an SQL query</li>
123  * <li>Paginate the results table</li>
124  * <li>Sort the results table</li>
125  * <li>Change table according to display options</li>
126  * <li>Grid editing of data</li>
127  * <li>Saving a bookmark</li>
128  * </ul>
130  * @name        document.ready
131  * @memberOf    jQuery
132  */
133 AJAX.registerOnload('sql.js', function () {
135     $(function () {
136         if (codemirror_editor) {
137             codemirror_editor.on('change', function () {
138                 var query = codemirror_editor.getValue();
139                 if (query) {
140                     $.cookie('auto_saved_sql', query);
141                 }
142             });
143         } else {
144             $('#sqlquery').on('input propertychange', function () {
145                 var query = $('#sqlquery').val();
146                 if (query) {
147                     $.cookie('auto_saved_sql', query);
148                 }
149             });
150         }
151     });
153     // Delete row from SQL results
154     $(document).on('click', 'a.delete_row.ajax', function (e) {
155         e.preventDefault();
156         var question =  PMA_sprintf(PMA_messages.strDoYouReally, escapeHtml($(this).closest('td').find('div').text()));
157         var $link = $(this);
158         $link.PMA_confirm(question, $link.attr('href'), function (url) {
159             $msgbox = PMA_ajaxShowMessage();
160             if ($link.hasClass('formLinkSubmit')) {
161                 submitFormLink($link);
162             } else {
163                 $.get(url, {'ajax_request': true, 'is_js_confirmed': true}, function (data) {
164                     if (data.success) {
165                         PMA_ajaxShowMessage(data.message);
166                         $link.closest('tr').remove();
167                     } else {
168                         PMA_ajaxShowMessage(data.error, false);
169                     }
170                 });
171             }
172         });
173     });
175     // Ajaxification for 'Bookmark this SQL query'
176     $(document).on('submit', '.bookmarkQueryForm', function (e) {
177         e.preventDefault();
178         PMA_ajaxShowMessage();
179         $.post($(this).attr('action'), 'ajax_request=1&' + $(this).serialize(), function (data) {
180             if (data.success) {
181                 PMA_ajaxShowMessage(data.message);
182             } else {
183                 PMA_ajaxShowMessage(data.error, false);
184             }
185         });
186     });
188     /* Hides the bookmarkoptions checkboxes when the bookmark label is empty */
189     $('input#bkm_label').keyup(function () {
190         $('input#id_bkm_all_users, input#id_bkm_replace')
191             .parent()
192             .toggle($(this).val().length > 0);
193     }).trigger('keyup');
195     /**
196      * Attach Event Handler for 'Print View'
197      */
198     $(document).on('click', "#printView", function (event) {
199         event.preventDefault();
201         // Print the page
202         printPage();
203     }); //end of Print View action
205     /**
206      * Attach the {@link makegrid} function to a custom event, which will be
207      * triggered manually everytime the table of results is reloaded
208      * @memberOf    jQuery
209      */
210     $(document).on('makegrid', ".sqlqueryresults", function () {
211         $('.table_results').each(function () {
212             PMA_makegrid(this);
213         });
214     });
216     /*
217      * Attach a custom event for sticky column headings which will be
218      * triggered manually everytime the table of results is reloaded
219      * @memberOf    jQuery
220      */
221     $(document).on('stickycolumns', ".sqlqueryresults", function () {
222         $(".sticky_columns").remove();
223         $(".table_results").each(function () {
224             var $table_results = $(this);
225             //add sticky columns div
226             var $stick_columns = initStickyColumns($table_results);
227             rearrangeStickyColumns($stick_columns, $table_results);
228             //adjust sticky columns on scroll
229             $(window).bind('scroll', function() {
230                 handleStickyColumns($stick_columns, $table_results);
231             });
232         });
233     });
235     /**
236      * Append the "Show/Hide query box" message to the query input form
237      *
238      * @memberOf jQuery
239      * @name    appendToggleSpan
240      */
241     // do not add this link more than once
242     if (! $('#sqlqueryform').find('a').is('#togglequerybox')) {
243         $('<a id="togglequerybox"></a>')
244         .html(PMA_messages.strHideQueryBox)
245         .appendTo("#sqlqueryform")
246         // initially hidden because at this point, nothing else
247         // appears under the link
248         .hide();
250         // Attach the toggling of the query box visibility to a click
251         $("#togglequerybox").bind('click', function () {
252             var $link = $(this);
253             $link.siblings().slideToggle("fast");
254             if ($link.text() == PMA_messages.strHideQueryBox) {
255                 $link.text(PMA_messages.strShowQueryBox);
256                 // cheap trick to add a spacer between the menu tabs
257                 // and "Show query box"; feel free to improve!
258                 $('#togglequerybox_spacer').remove();
259                 $link.before('<br id="togglequerybox_spacer" />');
260             } else {
261                 $link.text(PMA_messages.strHideQueryBox);
262             }
263             // avoid default click action
264             return false;
265         });
266     }
269     /**
270      * Event handler for sqlqueryform.ajax button_submit_query
271      *
272      * @memberOf    jQuery
273      */
274     $(document).on('click', "#button_submit_query", function (event) {
275         $(".success,.error").hide();
276         //hide already existing error or success message
277         var $form = $(this).closest("form");
278         // the Go button related to query submission was clicked,
279         // instead of the one related to Bookmarks, so empty the
280         // id_bookmark selector to avoid misinterpretation in
281         // import.php about what needs to be done
282         $form.find("select[name=id_bookmark]").val("");
283         // let normal event propagation happen
284     });
286     /**
287      * Event handler to show appropiate number of variable boxes
288      * based on the bookmarked query
289      */
290     $(document).on('change', '#id_bookmark', function (event) {
292         var varCount = $(this).find('option:selected').data('varcount');
293         if (typeof varCount == 'undefined') {
294             varCount = 0;
295         }
297         var $varDiv = $('#bookmark_variables');
298         $varDiv.empty();
299         for (var i = 1; i <= varCount; i++) {
300             $varDiv.append($('<label for="bookmark_variable_' + i + '">' + PMA_sprintf(PMA_messages.strBookmarkVariable, i) + '</label>'));
301             $varDiv.append($('<input type="text" size="10" name="bookmark_variable[' + i + ']" id="bookmark_variable_' + i + '"></input>'));
302         }
304         if (varCount == 0) {
305             $varDiv.parent('.formelement').hide();
306         } else {
307             $varDiv.parent('.formelement').show();
308         }
309     });
311     /**
312      * Event handler for hitting enter on sqlqueryform bookmark_variable
313      * (the Variable textfield in Bookmarked SQL query section)
314      *
315      * @memberOf    jQuery
316      */
317     $("input[name=bookmark_variable]").bind("keypress", function (event) {
318         // force the 'Enter Key' to implicitly click the #button_submit_bookmark
319         var keycode = (event.keyCode ? event.keyCode : (event.which ? event.which : event.charCode));
320         if (keycode == 13) { // keycode for enter key
321             // When you press enter in the sqlqueryform, which
322             // has 2 submit buttons, the default is to run the
323             // #button_submit_query, because of the tabindex
324             // attribute.
325             // This submits #button_submit_bookmark instead,
326             // because when you are in the Bookmarked SQL query
327             // section and hit enter, you expect it to do the
328             // same action as the Go button in that section.
329             $("#button_submit_bookmark").click();
330             return false;
331         } else  {
332             return true;
333         }
334     });
336     /**
337      * Ajax Event handler for 'SQL Query Submit'
338      *
339      * @see         PMA_ajaxShowMessage()
340      * @memberOf    jQuery
341      * @name        sqlqueryform_submit
342      */
343     $(document).on('submit', "#sqlqueryform.ajax", function (event) {
344         event.preventDefault();
346         var $form = $(this);
347         if (codemirror_editor) {
348             $form[0].elements.sql_query.value = codemirror_editor.getValue();
349         }
350         if (! checkSqlQuery($form[0])) {
351             return false;
352         }
354         // remove any div containing a previous error message
355         $('div.error').remove();
357         var $msgbox = PMA_ajaxShowMessage();
358         var $sqlqueryresultsouter = $('#sqlqueryresultsouter');
360         PMA_prepareForAjaxRequest($form);
362         $.post($form.attr('action'), $form.serialize() + '&ajax_page_request=true', function (data) {
363             if (typeof data !== 'undefined' && data.success === true) {
364                 // success happens if the query returns rows or not
366                 // show a message that stays on screen
367                 if (typeof data.action_bookmark != 'undefined') {
368                     // view only
369                     if ('1' == data.action_bookmark) {
370                         $('#sqlquery').text(data.sql_query);
371                         // send to codemirror if possible
372                         setQuery(data.sql_query);
373                     }
374                     // delete
375                     if ('2' == data.action_bookmark) {
376                         $("#id_bookmark option[value='" + data.id_bookmark + "']").remove();
377                         // if there are no bookmarked queries now (only the empty option),
378                         // remove the bookmark section
379                         if ($('#id_bookmark option').length == 1) {
380                             $('#fieldsetBookmarkOptions').hide();
381                             $('#fieldsetBookmarkOptionsFooter').hide();
382                         }
383                     }
384                 }
385                 $sqlqueryresultsouter
386                     .show()
387                     .html(data.message);
388                 PMA_highlightSQL($sqlqueryresultsouter);
390                 if (data._menu) {
391                     if (history && history.pushState) {
392                         history.replaceState({
393                                 menu : data._menu
394                             },
395                             null
396                         );
397                         AJAX.handleMenu.replace(data._menu);
398                     } else {
399                         PMA_MicroHistory.menus.replace(data._menu);
400                         PMA_MicroHistory.menus.add(data._menuHash, data._menu);
401                     }
402                 } else if (data._menuHash) {
403                     if (! (history && history.pushState)) {
404                         PMA_MicroHistory.menus.replace(PMA_MicroHistory.menus.get(data._menuHash));
405                     }
406                 }
408                 if (data._params) {
409                     PMA_commonParams.setAll(data._params);
410                 }
412                 if (typeof data.ajax_reload != 'undefined') {
413                     if (data.ajax_reload.reload) {
414                         if (data.ajax_reload.table_name) {
415                             PMA_commonParams.set('table', data.ajax_reload.table_name);
416                             PMA_commonActions.refreshMain();
417                         } else {
418                             PMA_reloadNavigation();
419                         }
420                     }
421                 } else if (typeof data.reload != 'undefined') {
422                     // this happens if a USE or DROP command was typed
423                     PMA_commonActions.setDb(data.db);
424                     var url;
425                     if (data.db) {
426                         if (data.table) {
427                             url = 'table_sql.php';
428                         } else {
429                             url = 'db_sql.php';
430                         }
431                     } else {
432                         url = 'server_sql.php';
433                     }
434                     PMA_commonActions.refreshMain(url, function () {
435                         $('#sqlqueryresultsouter')
436                             .show()
437                             .html(data.message);
438                         PMA_highlightSQL($('#sqlqueryresultsouter'));
439                     });
440                 }
442                 $('.sqlqueryresults').trigger('makegrid').trigger('stickycolumns');
443                 $('#togglequerybox').show();
444                 PMA_init_slider();
446                 if (typeof data.action_bookmark == 'undefined') {
447                     if ($('#sqlqueryform input[name="retain_query_box"]').is(':checked') !== true) {
448                         if ($("#togglequerybox").siblings(":visible").length > 0) {
449                             $("#togglequerybox").trigger('click');
450                         }
451                     }
452                 }
453             } else if (typeof data !== 'undefined' && data.success === false) {
454                 // show an error message that stays on screen
455                 $sqlqueryresultsouter
456                     .show()
457                     .html(data.error);
458             }
459             PMA_ajaxRemoveMessage($msgbox);
460         }); // end $.post()
461     }); // end SQL Query submit
463     /**
464      * Ajax Event handler for the display options
465      * @memberOf    jQuery
466      * @name        displayOptionsForm_submit
467      */
468     $(document).on('submit', "form[name='displayOptionsForm'].ajax", function (event) {
469         event.preventDefault();
471         $form = $(this);
473         var $msgbox = PMA_ajaxShowMessage();
474         $.post($form.attr('action'), $form.serialize() + '&ajax_request=true', function (data) {
475             PMA_ajaxRemoveMessage($msgbox);
476             var $sqlqueryresults = $form.parents(".sqlqueryresults");
477             $sqlqueryresults
478              .html(data.message)
479              .trigger('makegrid')
480              .trigger('stickycolumns');
481             PMA_init_slider();
482             PMA_highlightSQL($sqlqueryresults);
483         }); // end $.post()
484     }); //end displayOptionsForm handler
486     // Filter row handling. --STARTS--
487     $(document).on("keyup", ".filter_rows", function () {
488         var unique_id = $(this).data("for");
489         var $target_table = $(".table_results[data-uniqueId='" + unique_id + "']");
490         var $header_cells = $target_table.find("th[data-column]");
491         var target_columns = Array();
492         // To handle colspan=4, in case of edit,copy etc options.
493         var dummy_th = ($(".edit_row_anchor").length !== 0 ?
494             '<th class="hide dummy_th"></th><th class="hide dummy_th"></th><th class="hide dummy_th"></th>'
495             : '');
496         // Selecting columns that will be considered for filtering and searching.
497         $header_cells.each(function () {
498             target_columns.push($.trim($(this).text()));
499         });
501         var phrase = $(this).val();
502         // Set same value to both Filter rows fields.
503         $(".filter_rows[data-for='" + unique_id + "']").not(this).val(phrase);
504         // Handle colspan.
505         $target_table.find("thead > tr").prepend(dummy_th);
506         $.uiTableFilter($target_table, phrase, target_columns);
507         $target_table.find("th.dummy_th").remove();
508     });
509     // Filter row handling. --ENDS--
511     // Prompt to confirm on Show All
512     $('body').on('click', '.navigation .showAllRows', function (e) {
513         e.preventDefault();
514         var $form = $(this).parents('form');
516         if (! $(this).is(':checked')) { // already showing all rows
517             submitShowAllForm();
518         } else {
519             $form.PMA_confirm(PMA_messages.strShowAllRowsWarning, $form.attr('action'), function (url) {
520                 submitShowAllForm();
521             });
522         }
524         function submitShowAllForm() {
525             var submitData = $form.serialize() + '&ajax_request=true&ajax_page_request=true';
526             PMA_ajaxShowMessage();
527             AJAX.source = $form;
528             $.post($form.attr('action'), submitData, AJAX.responseHandler);
529         }
530     });
532     $('body').on('keyup', '#sqlqueryform', function () {
533         PMA_handleSimulateQueryButton();
534     });
536     /**
537      * Ajax event handler for 'Simulate DML'.
538      */
539     $('body').on('click', '#simulate_dml', function () {
540         var $form = $('#sqlqueryform');
541         var query = '';
542         var delimiter = $('#id_sql_delimiter').val();
543         var db_name = $form.find('input[name="db"]').val();
545         if (codemirror_editor) {
546             query = codemirror_editor.getValue();
547         } else {
548             query = $('#sqlquery').val();
549         }
551         if (query.length === 0) {
552             alert(PMA_messages.strFormEmpty);
553             $('#sqlquery').focus();
554             return false;
555         }
557         var $msgbox = PMA_ajaxShowMessage();
558         $.ajax({
559             type: 'POST',
560             url: $form.attr('action'),
561             data: {
562                 token: $form.find('input[name="token"]').val(),
563                 db: db_name,
564                 ajax_request: '1',
565                 simulate_dml: '1',
566                 sql_query: query,
567                 sql_delimiter: delimiter
568             },
569             success: function (response) {
570                 PMA_ajaxRemoveMessage($msgbox);
571                 if (response.success) {
572                     var dialog_content = '<div class="preview_sql">';
573                     if (response.sql_data) {
574                         var len = response.sql_data.length;
575                         for (var i=0; i<len; i++) {
576                             dialog_content += '<strong>' + PMA_messages.strSQLQuery +
577                                 '</strong>' + response.sql_data[i].sql_query +
578                                 PMA_messages.strMatchedRows +
579                                 ' <a href="' + response.sql_data[i].matched_rows_url +
580                                 '">' + response.sql_data[i].matched_rows + '</a><br>';
581                             if (i<len-1) {
582                                 dialog_content += '<hr>';
583                             }
584                         }
585                     } else {
586                         dialog_content += response.message;
587                     }
588                     dialog_content += '</div>';
589                     var $dialog_content = $(dialog_content);
590                     var button_options = {};
591                     button_options[PMA_messages.strClose] = function () {
592                         $(this).dialog('close');
593                     };
594                     var $response_dialog = $('<div />').append($dialog_content).dialog({
595                         minWidth: 540,
596                         maxHeight: 400,
597                         modal: true,
598                         buttons: button_options,
599                         title: PMA_messages.strSimulateDML,
600                         open: function () {
601                             PMA_highlightSQL($(this));
602                         },
603                         close: function () {
604                             $(this).remove();
605                         }
606                     });
607                 } else {
608                     PMA_ajaxShowMessage(response.error);
609                 }
610             },
611             error: function (response) {
612                 PMA_ajaxShowMessage(PMA_messages.strErrorProcessingRequest);
613             }
614         });
615     });
617     /**
618      * Handles multi submits of results browsing page such as edit, delete and export
619      */
620     $('body').on('click', 'form[name="resultsForm"].ajax button[name="submit_mult"], form[name="resultsForm"].ajax input[name="submit_mult"]', function (e) {
621         e.preventDefault();
622         var $button = $(this);
623         var $form = $button.closest('form');
624         var submitData = $form.serialize() + '&ajax_request=true&ajax_page_request=true&submit_mult=' + $button.val();
625         PMA_ajaxShowMessage();
626         AJAX.source = $form;
627         $.post($form.attr('action'), submitData, AJAX.responseHandler);
628     });
629 }); // end $()
632  * Starting from some th, change the class of all td under it.
633  * If isAddClass is specified, it will be used to determine whether to add or remove the class.
634  */
635 function PMA_changeClassForColumn($this_th, newclass, isAddClass)
637     // index 0 is the th containing the big T
638     var th_index = $this_th.index();
639     var has_big_t = $this_th.closest('tr').children(':first').hasClass('column_action');
640     // .eq() is zero-based
641     if (has_big_t) {
642         th_index--;
643     }
644     var $tds = $this_th.parents(".table_results").find('tbody tr').find('td.data:eq(' + th_index + ')');
645     if (isAddClass === undefined) {
646         $tds.toggleClass(newclass);
647     } else {
648         $tds.toggleClass(newclass, isAddClass);
649     }
653  * Handles browse foreign values modal dialog
655  * @param object $this_a reference to the browse foreign value link
656  */
657 function browseForeignDialog($this_a)
659     var formId = '#browse_foreign_form';
660     var showAllId = '#foreign_showAll';
661     var tableId = '#browse_foreign_table';
662     var filterId = '#input_foreign_filter';
663     var $dialog = null;
664     $.get($this_a.attr('href'), {'ajax_request': true}, function (data) {
665         // Creates browse foreign value dialog
666         $dialog = $('<div>').append(data.message).dialog({
667             title: PMA_messages.strBrowseForeignValues,
668             width: Math.min($(window).width() - 100, 700),
669             maxHeight: $(window).height() - 100,
670             dialogClass: 'browse_foreign_modal',
671             close: function (ev, ui) {
672                 // remove event handlers attached to elements related to dialog
673                 $(tableId).off('click', 'td a.foreign_value');
674                 $(formId).off('click', showAllId);
675                 $(formId).off('submit');
676                 // remove dialog itself
677                 $(this).remove();
678             },
679             modal: true
680         });
681     }).done(function () {
682         var showAll = false;
683         $(tableId).on('click', 'td a.foreign_value', function (e) {
684             e.preventDefault();
685             var $input = $this_a.prev('input[type=text]');
686             // Check if input exists or get CEdit edit_box
687             if ($input.length === 0 ) {
688                 $input = $this_a.closest('.edit_area').prev('.edit_box');
689             }
690             // Set selected value as input value
691             $input.val($(this).data('key'));
692             $dialog.dialog('close');
693         });
694         $(formId).on('click', showAllId, function () {
695             showAll = true;
696         });
697         $(formId).on('submit', function (e) {
698             e.preventDefault();
699             // if filter value is not equal to old value
700             // then reset page number to 1
701             if ($(filterId).val() != $(filterId).data('old')) {
702                 $(formId).find('select[name=pos]').val('0');
703             }
704             var postParams = $(this).serializeArray();
705             // if showAll button was clicked to submit form then
706             // add showAll button parameter to form
707             if (showAll) {
708                 postParams.push({
709                     name: $(showAllId).attr('name'),
710                     value: $(showAllId).val()
711                 });
712             }
713             // updates values in dialog
714             $.post($(this).attr('action') + '?ajax_request=1', postParams, function (data) {
715                 var $obj = $('<div>').html(data.message);
716                 $(formId).html($obj.find(formId).html());
717                 $(tableId).html($obj.find(tableId).html());
718             });
719             showAll = false;
720         });
721     });
724 AJAX.registerOnload('sql.js', function () {
725     $('body').on('click', 'a.browse_foreign', function (e) {
726         e.preventDefault();
727         browseForeignDialog($(this));
728     });
730     /**
731      * vertical column highlighting in horizontal mode when hovering over the column header
732      */
733     $(document).on('mouseenter', 'th.column_heading.pointer', function (e) {
734         PMA_changeClassForColumn($(this), 'hover', true);
735     });
736     $(document).on('mouseleave', 'th.column_heading.pointer', function (e) {
737         PMA_changeClassForColumn($(this), 'hover', false);
738     });
740     /**
741      * vertical column marking in horizontal mode when clicking the column header
742      */
743     $(document).on('click', 'th.column_heading.marker', function () {
744         PMA_changeClassForColumn($(this), 'marked');
745     });
747     /**
748      * create resizable table
749      */
750     $(".sqlqueryresults").trigger('makegrid').trigger('stickycolumns');
754  * Profiling Chart
755  */
756 function makeProfilingChart()
758     if ($('#profilingchart').length === 0 ||
759         $('#profilingchart').html().length !== 0 ||
760         !$.jqplot || !$.jqplot.Highlighter || !$.jqplot.PieRenderer
761     ) {
762         return;
763     }
765     var data = [];
766     $.each(jQuery.parseJSON($('#profilingChartData').html()), function (key, value) {
767         data.push([key, parseFloat(value)]);
768     });
770     // Remove chart and data divs contents
771     $('#profilingchart').html('').show();
772     $('#profilingChartData').html('');
774     PMA_createProfilingChartJqplot('profilingchart', data);
778  * initialize profiling data tables
779  */
780 function initProfilingTables()
782     if (!$.tablesorter) {
783         return;
784     }
786     $('#profiletable').tablesorter({
787         widgets: ['zebra'],
788         sortList: [[0, 0]],
789         textExtraction: function (node) {
790             if (node.children.length > 0) {
791                 return node.children[0].innerHTML;
792             } else {
793                 return node.innerHTML;
794             }
795         }
796     });
798     $('#profilesummarytable').tablesorter({
799         widgets: ['zebra'],
800         sortList: [[1, 1]],
801         textExtraction: function (node) {
802             if (node.children.length > 0) {
803                 return node.children[0].innerHTML;
804             } else {
805                 return node.innerHTML;
806             }
807         }
808     });
812  * Set position, left, top, width of sticky_columns div
813  */
814 function setStickyColumnsPosition($sticky_columns, $table_results, position, top, left, margin_left) {
815     $sticky_columns
816         .css("position", position)
817         .css("top", top)
818         .css("left", left ? left : "auto")
819         .css("margin-left", margin_left ? margin_left : "0px")
820         .css("width", $table_results.width());
824  * Initialize sticky columns
825  */
826 function initStickyColumns($table_results) {
827     var $sticky_columns = $('<table class="sticky_columns"></table>')
828             .insertBefore($table_results)
829             .css("position", "fixed")
830             .css("z-index", "99")
831             .css("width", $table_results.width())
832             .css("margin-left", $('#page_content').css("margin-left"))
833             .css("top", $('#floating_menubar').height())
834             .css("display", "none");
835     return $sticky_columns;
839  * Arrange/Rearrange columns in sticky header
840  */
841 function rearrangeStickyColumns($sticky_columns, $table_results) {
842     var $originalHeader = $table_results.find("thead");
843     var $originalColumns = $originalHeader.find("tr:first").children();
844     var $clonedHeader = $originalHeader.clone();
845     // clone width per cell
846     $clonedHeader.find("tr:first").children().width(function(i,val) {
847         var width = $originalColumns.eq(i).width();
848         var is_firefox = navigator.userAgent.indexOf('Firefox') > -1;
849         if (! is_firefox) {
850             width += 1;
851         }
852         return width;
853     });
854     $sticky_columns.empty().append($clonedHeader);
858  * Adjust sticky columns on horizontal/vertical scroll for all tables
859  */
860 function handleAllStickyColumns() {
861     $('.sticky_columns').each(function () {
862         handleStickyColumns($(this), $(this).next('.table_results'));
863     });
867  * Adjust sticky columns on horizontal/vertical scroll
868  */
869 function handleStickyColumns($sticky_columns, $table_results) {
870     var currentScrollX = $(window).scrollLeft();
871     var windowOffset = $(window).scrollTop();
872     var tableStartOffset = $table_results.offset().top;
873     var tableEndOffset = tableStartOffset + $table_results.height();
874     if (windowOffset >= tableStartOffset && windowOffset <= tableEndOffset) {
875         //for horizontal scrolling
876         if(prevScrollX != currentScrollX) {
877             prevScrollX = currentScrollX;
878             setStickyColumnsPosition($sticky_columns, $table_results, "absolute", $('#floating_menubar').height() + windowOffset - tableStartOffset);
879         //for vertical scrolling
880         } else {
881             setStickyColumnsPosition($sticky_columns, $table_results, "fixed", $('#floating_menubar').height(), $("#pma_navigation").width() - currentScrollX, $('#page_content').css("margin-left"));
882         }
883         $sticky_columns.show();
884     } else {
885         $sticky_columns.hide();
886     }
889 AJAX.registerOnload('sql.js', function () {
890     makeProfilingChart();
891     initProfilingTables();