Welcome to mirror list, hosted at ThFree Co, Russian Federation.

sql.js « js - github.com/phpmyadmin/phpmyadmin.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
path: root/js/sql.js
blob: e8f299fe88f89abff39b41ff3c9bdda042f85b8c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
 * @fileoverview    functions used wherever an sql query form is used
 *
 * @requires    jQuery
 * @requires    js/functions.js
 *
 */

var $data_a;
var prevScrollX = 0;

/**
 * decode a string URL_encoded
 *
 * @param string str
 * @return string the URL-decoded string
 */
function PMA_urldecode (str) {
    if (typeof str !== 'undefined') {
        return decodeURIComponent(str.replace(/\+/g, '%20'));
    }
}

/**
 * endecode a string URL_decoded
 *
 * @param string str
 * @return string the URL-encoded string
 */
function PMA_urlencode (str) {
    if (typeof str !== 'undefined') {
        return encodeURIComponent(str).replace(/\%20/g, '+');
    }
}

/**
 * Saves SQL query in local storage or cookie
 *
 * @param string SQL query
 * @return void
 */
function PMA_autosaveSQL (query) {
    if (isStorageSupported('localStorage')) {
        window.localStorage.auto_saved_sql = query;
    } else {
        Cookies.set('auto_saved_sql', query);
    }
}

/**
 * Saves SQL query in local storage or cookie
 *
 * @param string database name
 * @param string table name
 * @param string SQL query
 * @return void
 */
function PMA_showThisQuery (db, table, query) {
    var show_this_query_object = {
        'db': db,
        'table': table,
        'query': query
    };
    if (isStorageSupported('localStorage')) {
        window.localStorage.show_this_query = 1;
        window.localStorage.show_this_query_object = JSON.stringify(show_this_query_object);
    } else {
        Cookies.set('show_this_quey', 1);
        Cookies.set('show_this_query_object', JSON.stringify(show_this_query_object));
    }
}

/**
 * Set query to codemirror if show this query is
 * checked and query for the db and table pair exists
 */
function setShowThisQuery () {
    var db = $('input[name="db"]').val();
    var table = $('input[name="table"]').val();
    if (isStorageSupported('localStorage')) {
        if (window.localStorage.show_this_query_object !== undefined) {
            var stored_db = JSON.parse(window.localStorage.show_this_query_object).db;
            var stored_table = JSON.parse(window.localStorage.show_this_query_object).table;
            var stored_query = JSON.parse(window.localStorage.show_this_query_object).query;
        }
        if (window.localStorage.show_this_query !== undefined
            && window.localStorage.show_this_query === '1') {
            $('input[name="show_query"]').prop('checked', true);
            if (db === stored_db && table === stored_table) {
                if (codemirror_editor) {
                    codemirror_editor.setValue(stored_query);
                } else if (document.sqlform) {
                    document.sqlform.sql_query.value = stored_query;
                }
            }
        } else {
            $('input[name="show_query"]').prop('checked', false);
        }
    }
}

/**
 * Saves SQL query with sort in local storage or cookie
 *
 * @param string SQL query
 * @return void
 */
function PMA_autosaveSQLSort (query) {
    if (query) {
        if (isStorageSupported('localStorage')) {
            window.localStorage.auto_saved_sql_sort = query;
        } else {
            Cookies.set('auto_saved_sql_sort', query);
        }
    }
}

/**
 * Get the field name for the current field.  Required to construct the query
 * for grid editing
 *
 * @param $table_results enclosing results table
 * @param $this_field    jQuery object that points to the current field's tr
 */
function getFieldName ($table_results, $this_field) {
    var this_field_index = $this_field.index();
    // ltr or rtl direction does not impact how the DOM was generated
    // check if the action column in the left exist
    var left_action_exist = !$table_results.find('th:first').hasClass('draggable');
    // number of column span for checkbox and Actions
    var left_action_skip = left_action_exist ? $table_results.find('th:first').attr('colspan') - 1 : 0;

    // If this column was sorted, the text of the a element contains something
    // like <small>1</small> that is useful to indicate the order in case
    // of a sort on multiple columns; however, we dont want this as part
    // of the column name so we strip it ( .clone() to .end() )
    var field_name = $table_results
        .find('thead')
        .find('th:eq(' + (this_field_index - left_action_skip) + ') a')
        .clone()    // clone the element
        .children() // select all the children
        .remove()   // remove all of them
        .end()      // go back to the selected element
        .text();    // grab the text
    // happens when just one row (headings contain no a)
    if (field_name === '') {
        var $heading = $table_results.find('thead').find('th:eq(' + (this_field_index - left_action_skip) + ')').children('span');
        // may contain column comment enclosed in a span - detach it temporarily to read the column name
        var $tempColComment = $heading.children().detach();
        field_name = $heading.text();
        // re-attach the column comment
        $heading.append($tempColComment);
    }

    field_name = $.trim(field_name);

    return field_name;
}

/**
 * Unbind all event handlers before tearing down a page
 */
AJAX.registerTeardown('sql.js', function () {
    $(document).off('click', 'a.delete_row.ajax');
    $(document).off('submit', '.bookmarkQueryForm');
    $('input#bkm_label').off('keyup');
    $(document).off('makegrid', '.sqlqueryresults');
    $(document).off('stickycolumns', '.sqlqueryresults');
    $('#togglequerybox').off('click');
    $(document).off('click', '#button_submit_query');
    $(document).off('change', '#id_bookmark');
    $('input[name=\'bookmark_variable\']').off('keypress');
    $(document).off('submit', '#sqlqueryform.ajax');
    $(document).off('click', 'input[name=navig].ajax');
    $(document).off('submit', 'form[name=\'displayOptionsForm\'].ajax');
    $(document).off('mouseenter', 'th.column_heading.pointer');
    $(document).off('mouseleave', 'th.column_heading.pointer');
    $(document).off('click', 'th.column_heading.marker');
    $(window).off('scroll');
    $(document).off('keyup', '.filter_rows');
    $(document).off('click', '#printView');
    if (codemirror_editor) {
        codemirror_editor.off('change');
    } else {
        $('#sqlquery').off('input propertychange');
    }
    $('body').off('click', '.navigation .showAllRows');
    $('body').off('click', 'a.browse_foreign');
    $('body').off('click', '#simulate_dml');
    $('body').off('keyup', '#sqlqueryform');
    $('body').off('click', 'form[name="resultsForm"].ajax button[name="submit_mult"], form[name="resultsForm"].ajax input[name="submit_mult"]');
});

/**
 * @description <p>Ajax scripts for sql and browse pages</p>
 *
 * Actions ajaxified here:
 * <ul>
 * <li>Retrieve results of an SQL query</li>
 * <li>Paginate the results table</li>
 * <li>Sort the results table</li>
 * <li>Change table according to display options</li>
 * <li>Grid editing of data</li>
 * <li>Saving a bookmark</li>
 * </ul>
 *
 * @name        document.ready
 * @memberOf    jQuery
 */
AJAX.registerOnload('sql.js', function () {
    if (codemirror_editor || document.sqlform) {
        setShowThisQuery();
    }
    $(function () {
        if (codemirror_editor) {
            codemirror_editor.on('change', function () {
                PMA_autosaveSQL(codemirror_editor.getValue());
            });
        } else {
            $('#sqlquery').on('input propertychange', function () {
                PMA_autosaveSQL($('#sqlquery').val());
            });
            // Save sql query with sort
            if ($('#RememberSorting') !== undefined && $('#RememberSorting').is(':checked')) {
                $('select[name="sql_query"]').on('change', function () {
                    PMA_autosaveSQLSort($('select[name="sql_query"]').val());
                });
            } else {
                if (isStorageSupported('localStorage') && window.localStorage.auto_saved_sql_sort !== undefined) {
                    window.localStorage.removeItem('auto_saved_sql_sort');
                } else {
                    Cookies.set('auto_saved_sql_sort', '');
                }
            }
            // If sql query with sort for current table is stored, change sort by key select value
            var sortStoredQuery = (isStorageSupported('localStorage') && typeof window.localStorage.auto_saved_sql_sort !== 'undefined') ? window.localStorage.auto_saved_sql_sort : Cookies.get('auto_saved_sql_sort');
            if (typeof sortStoredQuery !== 'undefined' && sortStoredQuery !== $('select[name="sql_query"]').val() && $('select[name="sql_query"] option[value="' + sortStoredQuery + '"]').length !== 0) {
                $('select[name="sql_query"]').val(sortStoredQuery).trigger('change');
            }
        }
    });

    // Delete row from SQL results
    $(document).on('click', 'a.delete_row.ajax', function (e) {
        e.preventDefault();
        var question =  PMA_sprintf(PMA_messages.strDoYouReally, escapeHtml($(this).closest('td').find('div').text()));
        var $link = $(this);
        $link.PMA_confirm(question, $link.attr('href'), function (url) {
            $msgbox = PMA_ajaxShowMessage();
            var argsep = PMA_commonParams.get('arg_separator');
            var params = 'ajax_request=1' + argsep + 'is_js_confirmed=1';
            var postData = $link.getPostData();
            if (postData) {
                params += argsep + postData;
            }
            $.post(url, params, function (data) {
                if (data.success) {
                    PMA_ajaxShowMessage(data.message);
                    $link.closest('tr').remove();
                } else {
                    PMA_ajaxShowMessage(data.error, false);
                }
            });
        });
    });

    // Ajaxification for 'Bookmark this SQL query'
    $(document).on('submit', '.bookmarkQueryForm', function (e) {
        e.preventDefault();
        PMA_ajaxShowMessage();
        var argsep = PMA_commonParams.get('arg_separator');
        $.post($(this).attr('action'), 'ajax_request=1' + argsep + $(this).serialize(), function (data) {
            if (data.success) {
                PMA_ajaxShowMessage(data.message);
            } else {
                PMA_ajaxShowMessage(data.error, false);
            }
        });
    });

    /* Hides the bookmarkoptions checkboxes when the bookmark label is empty */
    $('input#bkm_label').on('keyup', function () {
        $('input#id_bkm_all_users, input#id_bkm_replace')
            .parent()
            .toggle($(this).val().length > 0);
    }).trigger('keyup');

    /**
     * Attach Event Handler for 'Copy to clipbpard
     */
    $(document).on('click', '#copyToClipBoard', function (event) {
        event.preventDefault();

        var textArea = document.createElement('textarea');

        //
        // *** This styling is an extra step which is likely not required. ***
        //
        // Why is it here? To ensure:
        // 1. the element is able to have focus and selection.
        // 2. if element was to flash render it has minimal visual impact.
        // 3. less flakyness with selection and copying which **might** occur if
        //    the textarea element is not visible.
        //
        // The likelihood is the element won't even render, not even a flash,
        // so some of these are just precautions. However in IE the element
        // is visible whilst the popup box asking the user for permission for
        // the web page to copy to the clipboard.
        //

        // Place in top-left corner of screen regardless of scroll position.
        textArea.style.position = 'fixed';
        textArea.style.top = 0;
        textArea.style.left = 0;

        // Ensure it has a small width and height. Setting to 1px / 1em
        // doesn't work as this gives a negative w/h on some browsers.
        textArea.style.width = '2em';
        textArea.style.height = '2em';

        // We don't need padding, reducing the size if it does flash render.
        textArea.style.padding = 0;

        // Clean up any borders.
        textArea.style.border = 'none';
        textArea.style.outline = 'none';
        textArea.style.boxShadow = 'none';

        // Avoid flash of white box if rendered for any reason.
        textArea.style.background = 'transparent';

        textArea.value = '';

        $('#serverinfo a').each(function () {
            textArea.value += $(this).text().split(':')[1].trim() + '/';
        });
        textArea.value += '\t\t' + window.location.href;
        textArea.value += '\n';
        $('.success').each(function () {
            textArea.value += $(this).text() + '\n\n';
        });

        $('.sql pre').each(function () {
            textArea.value += $(this).text() + '\n\n';
        });

        $('.table_results .column_heading a').each(function () {
            // Don't copy ordering number text within <small> tag
            textArea.value += $(this).clone().find('small').remove().end().text() + '\t';
        });

        textArea.value += '\n';
        $('.table_results tbody tr').each(function () {
            $(this).find('.data span').each(function () {
                textArea.value += $(this).text() + '\t';
            });
            textArea.value += '\n';
        });

        document.body.appendChild(textArea);

        textArea.select();

        try {
            document.execCommand('copy');
        } catch (err) {
            alert('Sorry! Unable to copy');
        }

        document.body.removeChild(textArea);
    }); // end of Copy to Clipboard action

    /**
     * Attach Event Handler for 'Print' link
     */
    $(document).on('click', '#printView', function (event) {
        event.preventDefault();

        // Take to preview mode
        printPreview();
    }); // end of 'Print' action

    /**
     * Attach the {@link makegrid} function to a custom event, which will be
     * triggered manually everytime the table of results is reloaded
     * @memberOf    jQuery
     */
    $(document).on('makegrid', '.sqlqueryresults', function () {
        $('.table_results').each(function () {
            PMA_makegrid(this);
        });
    });

    /*
     * Attach a custom event for sticky column headings which will be
     * triggered manually everytime the table of results is reloaded
     * @memberOf    jQuery
     */
    $(document).on('stickycolumns', '.sqlqueryresults', function () {
        $('.sticky_columns').remove();
        $('.table_results').each(function () {
            var $table_results = $(this);
            // add sticky columns div
            var $stick_columns = initStickyColumns($table_results);
            rearrangeStickyColumns($stick_columns, $table_results);
            // adjust sticky columns on scroll
            $(window).on('scroll', function () {
                handleStickyColumns($stick_columns, $table_results);
            });
        });
    });

    /**
     * Append the "Show/Hide query box" message to the query input form
     *
     * @memberOf jQuery
     * @name    appendToggleSpan
     */
    // do not add this link more than once
    if (! $('#sqlqueryform').find('a').is('#togglequerybox')) {
        $('<a id="togglequerybox"></a>')
            .html(PMA_messages.strHideQueryBox)
            .appendTo('#sqlqueryform')
        // initially hidden because at this point, nothing else
        // appears under the link
            .hide();

        // Attach the toggling of the query box visibility to a click
        $('#togglequerybox').bind('click', function () {
            var $link = $(this);
            $link.siblings().slideToggle('fast');
            if ($link.text() === PMA_messages.strHideQueryBox) {
                $link.text(PMA_messages.strShowQueryBox);
                // cheap trick to add a spacer between the menu tabs
                // and "Show query box"; feel free to improve!
                $('#togglequerybox_spacer').remove();
                $link.before('<br id="togglequerybox_spacer" />');
            } else {
                $link.text(PMA_messages.strHideQueryBox);
            }
            // avoid default click action
            return false;
        });
    }


    /**
     * Event handler for sqlqueryform.ajax button_submit_query
     *
     * @memberOf    jQuery
     */
    $(document).on('click', '#button_submit_query', function (event) {
        $('.success,.error').hide();
        // hide already existing error or success message
        var $form = $(this).closest('form');
        // the Go button related to query submission was clicked,
        // instead of the one related to Bookmarks, so empty the
        // id_bookmark selector to avoid misinterpretation in
        // import.php about what needs to be done
        $form.find('select[name=id_bookmark]').val('');
        // let normal event propagation happen
        if (isStorageSupported('localStorage')) {
            window.localStorage.removeItem('auto_saved_sql');
        } else {
            Cookies.set('auto_saved_sql', '');
        }
        var isShowQuery =  $('input[name="show_query"').is(':checked');
        if (isShowQuery) {
            window.localStorage.show_this_query = '1';
            var db = $('input[name="db"]').val();
            var table = $('input[name="table"]').val();
            var query;
            if (codemirror_editor) {
                query = codemirror_editor.getValue();
            } else {
                query = $('#sqlquery').val();
            }
            PMA_showThisQuery(db, table, query);
        } else {
            window.localStorage.show_this_query = '0';
        }
    });

    /**
     * Event handler to show appropiate number of variable boxes
     * based on the bookmarked query
     */
    $(document).on('change', '#id_bookmark', function (event) {
        var varCount = $(this).find('option:selected').data('varcount');
        if (typeof varCount === 'undefined') {
            varCount = 0;
        }

        var $varDiv = $('#bookmark_variables');
        $varDiv.empty();
        for (var i = 1; i <= varCount; i++) {
            $varDiv.append($('<label for="bookmark_variable_' + i + '">' + PMA_sprintf(PMA_messages.strBookmarkVariable, i) + '</label>'));
            $varDiv.append($('<input type="text" size="10" name="bookmark_variable[' + i + ']" id="bookmark_variable_' + i + '"/>'));
        }

        if (varCount === 0) {
            $varDiv.parent('.formelement').hide();
        } else {
            $varDiv.parent('.formelement').show();
        }
    });

    /**
     * Event handler for hitting enter on sqlqueryform bookmark_variable
     * (the Variable textfield in Bookmarked SQL query section)
     *
     * @memberOf    jQuery
     */
    $('input[name=bookmark_variable]').on('keypress', function (event) {
        // force the 'Enter Key' to implicitly click the #button_submit_bookmark
        var keycode = (event.keyCode ? event.keyCode : (event.which ? event.which : event.charCode));
        if (keycode === 13) { // keycode for enter key
            // When you press enter in the sqlqueryform, which
            // has 2 submit buttons, the default is to run the
            // #button_submit_query, because of the tabindex
            // attribute.
            // This submits #button_submit_bookmark instead,
            // because when you are in the Bookmarked SQL query
            // section and hit enter, you expect it to do the
            // same action as the Go button in that section.
            $('#button_submit_bookmark').trigger('click');
            return false;
        } else  {
            return true;
        }
    });

    /**
     * Ajax Event handler for 'SQL Query Submit'
     *
     * @see         PMA_ajaxShowMessage()
     * @memberOf    jQuery
     * @name        sqlqueryform_submit
     */
    $(document).on('submit', '#sqlqueryform.ajax', function (event) {
        event.preventDefault();

        var $form = $(this);
        if (codemirror_editor) {
            $form[0].elements.sql_query.value = codemirror_editor.getValue();
        }
        if (! checkSqlQuery($form[0])) {
            return false;
        }

        // remove any div containing a previous error message
        $('div.error').remove();

        var $msgbox = PMA_ajaxShowMessage();
        var $sqlqueryresultsouter = $('#sqlqueryresultsouter');

        PMA_prepareForAjaxRequest($form);

        var argsep = PMA_commonParams.get('arg_separator');
        $.post($form.attr('action'), $form.serialize() + argsep + 'ajax_page_request=true', function (data) {
            if (typeof data !== 'undefined' && data.success === true) {
                // success happens if the query returns rows or not

                // show a message that stays on screen
                if (typeof data.action_bookmark !== 'undefined') {
                    // view only
                    if ('1' === data.action_bookmark) {
                        $('#sqlquery').text(data.sql_query);
                        // send to codemirror if possible
                        setQuery(data.sql_query);
                    }
                    // delete
                    if ('2' === data.action_bookmark) {
                        $('#id_bookmark option[value=\'' + data.id_bookmark + '\']').remove();
                        // if there are no bookmarked queries now (only the empty option),
                        // remove the bookmark section
                        if ($('#id_bookmark option').length === 1) {
                            $('#fieldsetBookmarkOptions').hide();
                            $('#fieldsetBookmarkOptionsFooter').hide();
                        }
                    }
                }
                $sqlqueryresultsouter
                    .show()
                    .html(data.message);
                PMA_highlightSQL($sqlqueryresultsouter);

                if (data._menu) {
                    if (history && history.pushState) {
                        history.replaceState({
                            menu : data._menu
                        },
                        null
                        );
                        AJAX.handleMenu.replace(data._menu);
                    } else {
                        PMA_MicroHistory.menus.replace(data._menu);
                        PMA_MicroHistory.menus.add(data._menuHash, data._menu);
                    }
                } else if (data._menuHash) {
                    if (! (history && history.pushState)) {
                        PMA_MicroHistory.menus.replace(PMA_MicroHistory.menus.get(data._menuHash));
                    }
                }

                if (data._params) {
                    PMA_commonParams.setAll(data._params);
                }

                if (typeof data.ajax_reload !== 'undefined') {
                    if (data.ajax_reload.reload) {
                        if (data.ajax_reload.table_name) {
                            PMA_commonParams.set('table', data.ajax_reload.table_name);
                            PMA_commonActions.refreshMain();
                        } else {
                            PMA_reloadNavigation();
                        }
                    }
                } else if (typeof data.reload !== 'undefined') {
                    // this happens if a USE or DROP command was typed
                    PMA_commonActions.setDb(data.db);
                    var url;
                    if (data.db) {
                        if (data.table) {
                            url = 'table_sql.php';
                        } else {
                            url = 'db_sql.php';
                        }
                    } else {
                        url = 'server_sql.php';
                    }
                    PMA_commonActions.refreshMain(url, function () {
                        $('#sqlqueryresultsouter')
                            .show()
                            .html(data.message);
                        PMA_highlightSQL($('#sqlqueryresultsouter'));
                    });
                }

                $('.sqlqueryresults').trigger('makegrid').trigger('stickycolumns');
                $('#togglequerybox').show();
                PMA_init_slider();

                if (typeof data.action_bookmark === 'undefined') {
                    if ($('#sqlqueryform input[name="retain_query_box"]').is(':checked') !== true) {
                        if ($('#togglequerybox').siblings(':visible').length > 0) {
                            $('#togglequerybox').trigger('click');
                        }
                    }
                }
            } else if (typeof data !== 'undefined' && data.success === false) {
                // show an error message that stays on screen
                $sqlqueryresultsouter
                    .show()
                    .html(data.error);
            }
            PMA_ajaxRemoveMessage($msgbox);
        }); // end $.post()
    }); // end SQL Query submit

    /**
     * Ajax Event handler for the display options
     * @memberOf    jQuery
     * @name        displayOptionsForm_submit
     */
    $(document).on('submit', 'form[name=\'displayOptionsForm\'].ajax', function (event) {
        event.preventDefault();

        $form = $(this);

        var $msgbox = PMA_ajaxShowMessage();
        var argsep = PMA_commonParams.get('arg_separator');
        $.post($form.attr('action'), $form.serialize() + argsep + 'ajax_request=true', function (data) {
            PMA_ajaxRemoveMessage($msgbox);
            var $sqlqueryresults = $form.parents('.sqlqueryresults');
            $sqlqueryresults
                .html(data.message)
                .trigger('makegrid')
                .trigger('stickycolumns');
            PMA_init_slider();
            PMA_highlightSQL($sqlqueryresults);
        }); // end $.post()
    }); // end displayOptionsForm handler

    // Filter row handling. --STARTS--
    $(document).on('keyup', '.filter_rows', function () {
        var unique_id = $(this).data('for');
        var $target_table = $('.table_results[data-uniqueId=\'' + unique_id + '\']');
        var $header_cells = $target_table.find('th[data-column]');
        var target_columns = Array();
        // To handle colspan=4, in case of edit,copy etc options.
        var dummy_th = ($('.edit_row_anchor').length !== 0 ?
            '<th class="hide dummy_th"></th><th class="hide dummy_th"></th><th class="hide dummy_th"></th>'
            : '');
        // Selecting columns that will be considered for filtering and searching.
        $header_cells.each(function () {
            target_columns.push($.trim($(this).text()));
        });

        var phrase = $(this).val();
        // Set same value to both Filter rows fields.
        $('.filter_rows[data-for=\'' + unique_id + '\']').not(this).val(phrase);
        // Handle colspan.
        $target_table.find('thead > tr').prepend(dummy_th);
        $.uiTableFilter($target_table, phrase, target_columns);
        $target_table.find('th.dummy_th').remove();
    });
    // Filter row handling. --ENDS--

    // Prompt to confirm on Show All
    $('body').on('click', '.navigation .showAllRows', function (e) {
        e.preventDefault();
        var $form = $(this).parents('form');

        if (! $(this).is(':checked')) { // already showing all rows
            submitShowAllForm();
        } else {
            $form.PMA_confirm(PMA_messages.strShowAllRowsWarning, $form.attr('action'), function (url) {
                submitShowAllForm();
            });
        }

        function submitShowAllForm () {
            var argsep = PMA_commonParams.get('arg_separator');
            var submitData = $form.serialize() + argsep + 'ajax_request=true' + argsep + 'ajax_page_request=true';
            PMA_ajaxShowMessage();
            AJAX.source = $form;
            $.post($form.attr('action'), submitData, AJAX.responseHandler);
        }
    });

    $('body').on('keyup', '#sqlqueryform', function () {
        PMA_handleSimulateQueryButton();
    });

    /**
     * Ajax event handler for 'Simulate DML'.
     */
    $('body').on('click', '#simulate_dml', function () {
        var $form = $('#sqlqueryform');
        var query = '';
        var delimiter = $('#id_sql_delimiter').val();
        var db_name = $form.find('input[name="db"]').val();

        if (codemirror_editor) {
            query = codemirror_editor.getValue();
        } else {
            query = $('#sqlquery').val();
        }

        if (query.length === 0) {
            alert(PMA_messages.strFormEmpty);
            $('#sqlquery').focus();
            return false;
        }

        var $msgbox = PMA_ajaxShowMessage();
        $.ajax({
            type: 'POST',
            url: $form.attr('action'),
            data: {
                server: PMA_commonParams.get('server'),
                db: db_name,
                ajax_request: '1',
                simulate_dml: '1',
                sql_query: query,
                sql_delimiter: delimiter
            },
            success: function (response) {
                PMA_ajaxRemoveMessage($msgbox);
                if (response.success) {
                    var dialog_content = '<div class="preview_sql">';
                    if (response.sql_data) {
                        var len = response.sql_data.length;
                        for (var i = 0; i < len; i++) {
                            dialog_content += '<strong>' + PMA_messages.strSQLQuery +
                                '</strong>' + response.sql_data[i].sql_query +
                                PMA_messages.strMatchedRows +
                                ' <a href="' + response.sql_data[i].matched_rows_url +
                                '">' + response.sql_data[i].matched_rows + '</a><br>';
                            if (i < len - 1) {
                                dialog_content += '<hr>';
                            }
                        }
                    } else {
                        dialog_content += response.message;
                    }
                    dialog_content += '</div>';
                    var $dialog_content = $(dialog_content);
                    var button_options = {};
                    button_options[PMA_messages.strClose] = function () {
                        $(this).dialog('close');
                    };
                    var $response_dialog = $('<div />').append($dialog_content).dialog({
                        minWidth: 540,
                        maxHeight: 400,
                        modal: true,
                        buttons: button_options,
                        title: PMA_messages.strSimulateDML,
                        open: function () {
                            PMA_highlightSQL($(this));
                        },
                        close: function () {
                            $(this).remove();
                        }
                    });
                } else {
                    PMA_ajaxShowMessage(response.error);
                }
            },
            error: function (response) {
                PMA_ajaxShowMessage(PMA_messages.strErrorProcessingRequest);
            }
        });
    });

    /**
     * Handles multi submits of results browsing page such as edit, delete and export
     */
    $('body').on('click', 'form[name="resultsForm"].ajax button[name="submit_mult"], form[name="resultsForm"].ajax input[name="submit_mult"]', function (e) {
        e.preventDefault();
        var $button = $(this);
        var $form = $button.closest('form');
        var argsep = PMA_commonParams.get('arg_separator');
        var submitData = $form.serialize() + argsep + 'ajax_request=true' + argsep + 'ajax_page_request=true' + argsep + 'submit_mult=' + $button.val();
        PMA_ajaxShowMessage();
        AJAX.source = $form;
        $.post($form.attr('action'), submitData, AJAX.responseHandler);
    });
}); // end $()

/**
 * Starting from some th, change the class of all td under it.
 * If isAddClass is specified, it will be used to determine whether to add or remove the class.
 */
function PMA_changeClassForColumn ($this_th, newclass, isAddClass) {
    // index 0 is the th containing the big T
    var th_index = $this_th.index();
    var has_big_t = $this_th.closest('tr').children(':first').hasClass('column_action');
    // .eq() is zero-based
    if (has_big_t) {
        th_index--;
    }
    var $table = $this_th.parents('.table_results');
    if (! $table.length) {
        $table = $this_th.parents('table').siblings('.table_results');
    }
    var $tds = $table.find('tbody tr').find('td.data:eq(' + th_index + ')');
    if (isAddClass === undefined) {
        $tds.toggleClass(newclass);
    } else {
        $tds.toggleClass(newclass, isAddClass);
    }
}

/**
 * Handles browse foreign values modal dialog
 *
 * @param object $this_a reference to the browse foreign value link
 */
function browseForeignDialog ($this_a) {
    var formId = '#browse_foreign_form';
    var showAllId = '#foreign_showAll';
    var tableId = '#browse_foreign_table';
    var filterId = '#input_foreign_filter';
    var $dialog = null;
    $.get($this_a.attr('href'), { 'ajax_request': true }, function (data) {
        // Creates browse foreign value dialog
        $dialog = $('<div>').append(data.message).dialog({
            title: PMA_messages.strBrowseForeignValues,
            width: Math.min($(window).width() - 100, 700),
            maxHeight: $(window).height() - 100,
            dialogClass: 'browse_foreign_modal',
            close: function (ev, ui) {
                // remove event handlers attached to elements related to dialog
                $(tableId).off('click', 'td a.foreign_value');
                $(formId).off('click', showAllId);
                $(formId).off('submit');
                // remove dialog itself
                $(this).remove();
            },
            modal: true
        });
    }).done(function () {
        var showAll = false;
        $(tableId).on('click', 'td a.foreign_value', function (e) {
            e.preventDefault();
            var $input = $this_a.prev('input[type=text]');
            // Check if input exists or get CEdit edit_box
            if ($input.length === 0) {
                $input = $this_a.closest('.edit_area').prev('.edit_box');
            }
            // Set selected value as input value
            $input.val($(this).data('key'));
            $dialog.dialog('close');
        });
        $(formId).on('click', showAllId, function () {
            showAll = true;
        });
        $(formId).on('submit', function (e) {
            e.preventDefault();
            // if filter value is not equal to old value
            // then reset page number to 1
            if ($(filterId).val() !== $(filterId).data('old')) {
                $(formId).find('select[name=pos]').val('0');
            }
            var postParams = $(this).serializeArray();
            // if showAll button was clicked to submit form then
            // add showAll button parameter to form
            if (showAll) {
                postParams.push({
                    name: $(showAllId).attr('name'),
                    value: $(showAllId).val()
                });
            }
            // updates values in dialog
            $.post($(this).attr('action') + '?ajax_request=1', postParams, function (data) {
                var $obj = $('<div>').html(data.message);
                $(formId).html($obj.find(formId).html());
                $(tableId).html($obj.find(tableId).html());
            });
            showAll = false;
        });
    });
}

function checkSavedQuery () {
    if (isStorageSupported('localStorage') && window.localStorage.auto_saved_sql !== undefined) {
        PMA_ajaxShowMessage(PMA_messages.strPreviousSaveQuery);
    }
}

AJAX.registerOnload('sql.js', function () {
    $('body').on('click', 'a.browse_foreign', function (e) {
        e.preventDefault();
        browseForeignDialog($(this));
    });

    /**
     * vertical column highlighting in horizontal mode when hovering over the column header
     */
    $(document).on('mouseenter', 'th.column_heading.pointer', function (e) {
        PMA_changeClassForColumn($(this), 'hover', true);
    });
    $(document).on('mouseleave', 'th.column_heading.pointer', function (e) {
        PMA_changeClassForColumn($(this), 'hover', false);
    });

    /**
     * vertical column marking in horizontal mode when clicking the column header
     */
    $(document).on('click', 'th.column_heading.marker', function () {
        PMA_changeClassForColumn($(this), 'marked');
    });

    /**
     * create resizable table
     */
    $('.sqlqueryresults').trigger('makegrid').trigger('stickycolumns');

    /**
     * Check if there is any saved query
     */
    if (codemirror_editor || document.sqlform) {
        checkSavedQuery();
    }
});

/*
 * Profiling Chart
 */
function makeProfilingChart () {
    if ($('#profilingchart').length === 0 ||
        $('#profilingchart').html().length !== 0 ||
        !$.jqplot || !$.jqplot.Highlighter || !$.jqplot.PieRenderer
    ) {
        return;
    }

    var data = [];
    $.each(JSON.parse($('#profilingChartData').html()), function (key, value) {
        data.push([key, parseFloat(value)]);
    });

    // Remove chart and data divs contents
    $('#profilingchart').html('').show();
    $('#profilingChartData').html('');

    PMA_createProfilingChart('profilingchart', data);
}

/*
 * initialize profiling data tables
 */
function initProfilingTables () {
    if (!$.tablesorter) {
        return;
    }

    $('#profiletable').tablesorter({
        widgets: ['zebra'],
        sortList: [[0, 0]],
        textExtraction: function (node) {
            if (node.children.length > 0) {
                return node.children[0].innerHTML;
            } else {
                return node.innerHTML;
            }
        }
    });

    $('#profilesummarytable').tablesorter({
        widgets: ['zebra'],
        sortList: [[1, 1]],
        textExtraction: function (node) {
            if (node.children.length > 0) {
                return node.children[0].innerHTML;
            } else {
                return node.innerHTML;
            }
        }
    });
}

/*
 * Set position, left, top, width of sticky_columns div
 */
function setStickyColumnsPosition ($sticky_columns, $table_results, position, top, left, margin_left) {
    $sticky_columns
        .css('position', position)
        .css('top', top)
        .css('left', left ? left : 'auto')
        .css('margin-left', margin_left ? margin_left : '0px')
        .css('width', $table_results.width());
}

/*
 * Initialize sticky columns
 */
function initStickyColumns ($table_results) {
    return $('<table class="sticky_columns"></table>')
        .insertBefore($table_results)
        .css('position', 'fixed')
        .css('z-index', '99')
        .css('width', $table_results.width())
        .css('margin-left', $('#page_content').css('margin-left'))
        .css('top', $('#floating_menubar').height())
        .css('display', 'none');
}

/*
 * Arrange/Rearrange columns in sticky header
 */
function rearrangeStickyColumns ($sticky_columns, $table_results) {
    var $originalHeader = $table_results.find('thead');
    var $originalColumns = $originalHeader.find('tr:first').children();
    var $clonedHeader = $originalHeader.clone();
    // clone width per cell
    $clonedHeader.find('tr:first').children().width(function (i,val) {
        var width = $originalColumns.eq(i).width();
        var is_firefox = navigator.userAgent.indexOf('Firefox') > -1;
        if (! is_firefox) {
            width += 1;
        }
        return width;
    });
    $sticky_columns.empty().append($clonedHeader);
}

/*
 * Adjust sticky columns on horizontal/vertical scroll for all tables
 */
function handleAllStickyColumns () {
    $('.sticky_columns').each(function () {
        handleStickyColumns($(this), $(this).next('.table_results'));
    });
}

/*
 * Adjust sticky columns on horizontal/vertical scroll
 */
function handleStickyColumns ($sticky_columns, $table_results) {
    var currentScrollX = $(window).scrollLeft();
    var windowOffset = $(window).scrollTop();
    var tableStartOffset = $table_results.offset().top;
    var tableEndOffset = tableStartOffset + $table_results.height();
    if (windowOffset >= tableStartOffset && windowOffset <= tableEndOffset) {
        // for horizontal scrolling
        if (prevScrollX !== currentScrollX) {
            prevScrollX = currentScrollX;
            setStickyColumnsPosition($sticky_columns, $table_results, 'absolute', $('#floating_menubar').height() + windowOffset - tableStartOffset);
        // for vertical scrolling
        } else {
            setStickyColumnsPosition($sticky_columns, $table_results, 'fixed', $('#floating_menubar').height(), $('#pma_navigation').width() - currentScrollX, $('#page_content').css('margin-left'));
        }
        $sticky_columns.show();
    } else {
        $sticky_columns.hide();
    }
}

AJAX.registerOnload('sql.js', function () {
    makeProfilingChart();
    initProfilingTables();
});