Support for Drizzle IPV6 column type in Fremont
[phpmyadmin.git] / js / functions.js
blobed8ebafa6b8315de8b0255e536db648383bd4302
1 /* vim: set expandtab sw=4 ts=4 sts=4: */
2 /**
3  * general function, usually for data manipulation pages
4  *
5  */
7 /**
8  * @var sql_box_locked lock for the sqlbox textarea in the querybox/querywindow
9  */
10 var sql_box_locked = false;
12 /**
13  * @var array holds elements which content should only selected once
14  */
15 var only_once_elements = new Array();
17 /**
18  * @var   int   ajax_message_count   Number of AJAX messages shown since page load
19  */
20 var ajax_message_count = 0;
22 /**
23  * @var codemirror_editor object containing CodeMirror editor
24  */
25 var codemirror_editor = false;
27 /**
28  * @var chart_activeTimeouts object active timeouts that refresh the charts. When disabling a realtime chart, this can be used to stop the continuous ajax requests
29  */
30 var chart_activeTimeouts = new Object();
32 /**
33  * Returns browser's viewport size, without accounting for scrollbars
34  *
35  * @param window wnd
36  */
37 function getWindowSize(wnd) {
38     var vp = wnd || window;
39     return {
40         // most browsers || IE6-8 strict || failsafe
41         width: vp.innerWidth || (vp.documentElement !== undefined ? vp.documentElement.clientWidth : false) || $(vp).width(),
42         height: vp.innerHeight || (vp.documentElement !== undefined ? vp.documentElement.clientHeight : false) || $(vp).height()
43     };
46 /**
47  * Make sure that ajax requests will not be cached
48  * by appending a random variable to their parameters
49  */
50 $.ajaxPrefilter(function (options, originalOptions, jqXHR) {
51     var nocache = new Date().getTime() + "" + Math.floor(Math.random() * 1000000);
52     if (typeof options.data == "string") {
53         options.data += "&_nocache=" + nocache;
54     } else if (typeof options.data == "object") {
55         options.data = $.extend(originalOptions.data, {'_nocache':nocache});
56     }
57 });
59 /**
60  * Add a hidden field to the form to indicate that this will be an
61  * Ajax request (only if this hidden field does not exist)
62  *
63  * @param   object   the form
64  */
65 function PMA_prepareForAjaxRequest($form)
67     if (! $form.find('input:hidden').is('#ajax_request_hidden')) {
68         $form.append('<input type="hidden" id="ajax_request_hidden" name="ajax_request" value="true" />');
69     }
72 /**
73  * Generate a new password and copy it to the password input areas
74  *
75  * @param   object   the form that holds the password fields
76  *
77  * @return  boolean  always true
78  */
79 function suggestPassword(passwd_form)
81     // restrict the password to just letters and numbers to avoid problems:
82     // "editors and viewers regard the password as multiple words and
83     // things like double click no longer work"
84     var pwchars = "abcdefhjmnpqrstuvwxyz23456789ABCDEFGHJKLMNPQRSTUVWYXZ";
85     var passwordlength = 16;    // do we want that to be dynamic?  no, keep it simple :)
86     var passwd = passwd_form.generated_pw;
87     passwd.value = '';
89     for ( i = 0; i < passwordlength; i++ ) {
90         passwd.value += pwchars.charAt( Math.floor( Math.random() * pwchars.length ) )
91     }
92     passwd_form.text_pma_pw.value = passwd.value;
93     passwd_form.text_pma_pw2.value = passwd.value;
94     return true;
97 /**
98  * Version string to integer conversion.
99  */
100 function parseVersionString (str)
102     if (typeof(str) != 'string') { return false; }
103     var add = 0;
104     // Parse possible alpha/beta/rc/
105     var state = str.split('-');
106     if (state.length >= 2) {
107         if (state[1].substr(0, 2) == 'rc') {
108             add = - 20 - parseInt(state[1].substr(2));
109         } else if (state[1].substr(0, 4) == 'beta') {
110             add =  - 40 - parseInt(state[1].substr(4));
111         } else if (state[1].substr(0, 5) == 'alpha') {
112             add =  - 60 - parseInt(state[1].substr(5));
113         } else if (state[1].substr(0, 3) == 'dev') {
114             /* We don't handle dev, it's git snapshot */
115             add = 0;
116         }
117     }
118     // Parse version
119     var x = str.split('.');
120     // Use 0 for non existing parts
121     var maj = parseInt(x[0]) || 0;
122     var min = parseInt(x[1]) || 0;
123     var pat = parseInt(x[2]) || 0;
124     var hotfix = parseInt(x[3]) || 0;
125     return  maj * 100000000 + min * 1000000 + pat * 10000 + hotfix * 100 + add;
129  * Indicates current available version on main page.
130  */
131 function PMA_current_version()
133     var current = parseVersionString(pmaversion);
134     var latest = parseVersionString(PMA_latest_version);
135     var version_information_message = PMA_messages['strLatestAvailable'] + ' ' + PMA_latest_version;
136     if (latest > current) {
137         var message = $.sprintf(PMA_messages['strNewerVersion'], PMA_latest_version, PMA_latest_date);
138         if (Math.floor(latest / 10000) == Math.floor(current / 10000)) {
139             /* Security update */
140             klass = 'error';
141         } else {
142             klass = 'notice';
143         }
144         $('#maincontainer').after('<div class="' + klass + '">' + message + '</div>');
145     }
146     if (latest == current) {
147         version_information_message = ' (' + PMA_messages['strUpToDate'] + ')';
148     }
149     $('#li_pma_version').append(version_information_message);
153  * for libraries/display_change_password.lib.php
154  *     libraries/user_password.php
156  */
158 function displayPasswordGenerateButton()
160     $('#tr_element_before_generate_password').parent().append('<tr><td>' + PMA_messages['strGeneratePassword'] + '</td><td><input type="button" id="button_generate_password" value="' + PMA_messages['strGenerate'] + '" onclick="suggestPassword(this.form)" /><input type="text" name="generated_pw" id="generated_pw" /></td></tr>');
161     $('#div_element_before_generate_password').parent().append('<div class="item"><label for="button_generate_password">' + PMA_messages['strGeneratePassword'] + ':</label><span class="options"><input type="button" id="button_generate_password" value="' + PMA_messages['strGenerate'] + '" onclick="suggestPassword(this.form)" /></span><input type="text" name="generated_pw" id="generated_pw" /></div>');
165  * Adds a date/time picker to an element
167  * @param   object  $this_element   a jQuery object pointing to the element
168  */
169 function PMA_addDatepicker($this_element, options)
171     var showTimeOption = false;
172     if ($this_element.is('.datetimefield')) {
173         showTimeOption = true;
174     }
176     var defaultOptions = {
177         showOn: 'button',
178         buttonImage: themeCalendarImage, // defined in js/messages.php
179         buttonImageOnly: true,
180         stepMinutes: 1,
181         stepHours: 1,
182         showSecond: true,
183         showTimepicker: showTimeOption,
184         showButtonPanel: false,
185         dateFormat: 'yy-mm-dd', // yy means year with four digits
186         timeFormat: 'hh:mm:ss',
187         altFieldTimeOnly: false,
188         showAnim: '',
189         beforeShow: function(input, inst) {
190             // Remember that we came from the datepicker; this is used
191             // in tbl_change.js by verificationsAfterFieldChange()
192             $this_element.data('comes_from', 'datepicker');
194             // Fix wrong timepicker z-index, doesn't work without timeout
195             setTimeout(function() {
196                 $('#ui-timepicker-div').css('z-index',$('#ui-datepicker-div').css('z-index'))
197             },0);
198         }
199     };
201     $this_element.datetimepicker($.extend(defaultOptions, options));
205  * selects the content of a given object, f.e. a textarea
207  * @param   object  element     element of which the content will be selected
208  * @param   var     lock        variable which holds the lock for this element
209  *                              or true, if no lock exists
210  * @param   boolean only_once   if true this is only done once
211  *                              f.e. only on first focus
212  */
213 function selectContent( element, lock, only_once )
215     if ( only_once && only_once_elements[element.name] ) {
216         return;
217     }
219     only_once_elements[element.name] = true;
221     if ( lock  ) {
222         return;
223     }
225     element.select();
229  * Displays a confirmation box before submitting a "DROP/DELETE/ALTER" query.
230  * This function is called while clicking links
232  * @param   object   the link
233  * @param   object   the sql query to submit
235  * @return  boolean  whether to run the query or not
236  */
237 function confirmLink(theLink, theSqlQuery)
239     // Confirmation is not required in the configuration file
240     // or browser is Opera (crappy js implementation)
241     if (PMA_messages['strDoYouReally'] == '' || typeof(window.opera) != 'undefined') {
242         return true;
243     }
245     var is_confirmed = confirm(PMA_messages['strDoYouReally'] + ' :\n' + theSqlQuery);
246     if (is_confirmed) {
247         if ( $(theLink).hasClass('formLinkSubmit') ) {
248             var name = 'is_js_confirmed';
249             if ($(theLink).attr('href').indexOf('usesubform') != -1) {
250                 name = 'subform[' + $(theLink).attr('href').substr('#').match(/usesubform\[(\d+)\]/i)[1] + '][is_js_confirmed]';
251             }
253             $(theLink).parents('form').append('<input type="hidden" name="' + name + '" value="1" />');
254         } else if ( typeof(theLink.href) != 'undefined' ) {
255             theLink.href += '&is_js_confirmed=1';
256         } else if ( typeof(theLink.form) != 'undefined' ) {
257             theLink.form.action += '?is_js_confirmed=1';
258         }
259     }
261     return is_confirmed;
262 } // end of the 'confirmLink()' function
265  * Displays an error message if a "DROP DATABASE" statement is submitted
266  * while it isn't allowed, else confirms a "DROP/DELETE/ALTER" query before
267  * sumitting it if required.
268  * This function is called by the 'checkSqlQuery()' js function.
270  * @param   object   the form
271  * @param   object   the sql query textarea
273  * @return  boolean  whether to run the query or not
275  * @see     checkSqlQuery()
276  */
277 function confirmQuery(theForm1, sqlQuery1)
279     // Confirmation is not required in the configuration file
280     if (PMA_messages['strDoYouReally'] == '') {
281         return true;
282     }
284     // "DROP DATABASE" statement isn't allowed
285     if (PMA_messages['strNoDropDatabases'] != '') {
286         var drop_re = new RegExp('(^|;)\\s*DROP\\s+(IF EXISTS\\s+)?DATABASE\\s', 'i');
287         if (drop_re.test(sqlQuery1.value)) {
288             alert(PMA_messages['strNoDropDatabases']);
289             theForm1.reset();
290             sqlQuery1.focus();
291             return false;
292         } // end if
293     } // end if
295     // Confirms a "DROP/DELETE/ALTER/TRUNCATE" statement
296     //
297     // TODO: find a way (if possible) to use the parser-analyser
298     // for this kind of verification
299     // For now, I just added a ^ to check for the statement at
300     // beginning of expression
302     var do_confirm_re_0 = new RegExp('^\\s*DROP\\s+(IF EXISTS\\s+)?(TABLE|DATABASE|PROCEDURE)\\s', 'i');
303     var do_confirm_re_1 = new RegExp('^\\s*ALTER\\s+TABLE\\s+((`[^`]+`)|([A-Za-z0-9_$]+))\\s+DROP\\s', 'i');
304     var do_confirm_re_2 = new RegExp('^\\s*DELETE\\s+FROM\\s', 'i');
305     var do_confirm_re_3 = new RegExp('^\\s*TRUNCATE\\s', 'i');
307     if (do_confirm_re_0.test(sqlQuery1.value)
308         || do_confirm_re_1.test(sqlQuery1.value)
309         || do_confirm_re_2.test(sqlQuery1.value)
310         || do_confirm_re_3.test(sqlQuery1.value)) {
311         var message      = (sqlQuery1.value.length > 100)
312                          ? sqlQuery1.value.substr(0, 100) + '\n    ...'
313                          : sqlQuery1.value;
314         var is_confirmed = confirm(PMA_messages['strDoYouReally'] + ' :\n' + message);
315         // statement is confirmed -> update the
316         // "is_js_confirmed" form field so the confirm test won't be
317         // run on the server side and allows to submit the form
318         if (is_confirmed) {
319             theForm1.elements['is_js_confirmed'].value = 1;
320             return true;
321         }
322         // statement is rejected -> do not submit the form
323         else {
324             window.focus();
325             sqlQuery1.focus();
326             return false;
327         } // end if (handle confirm box result)
328     } // end if (display confirm box)
330     return true;
331 } // end of the 'confirmQuery()' function
335  * Displays a confirmation box before disabling the BLOB repository for a given database.
336  * This function is called while clicking links
338  * @param   object   the database
340  * @return  boolean  whether to disable the repository or not
341  */
342 function confirmDisableRepository(theDB)
344     // Confirmation is not required in the configuration file
345     // or browser is Opera (crappy js implementation)
346     if (PMA_messages['strDoYouReally'] == '' || typeof(window.opera) != 'undefined') {
347         return true;
348     }
350     var is_confirmed = confirm(PMA_messages['strBLOBRepositoryDisableStrongWarning'] + '\n' + PMA_messages['strBLOBRepositoryDisableAreYouSure']);
352     return is_confirmed;
353 } // end of the 'confirmDisableBLOBRepository()' function
357  * Displays an error message if the user submitted the sql query form with no
358  * sql query, else checks for "DROP/DELETE/ALTER" statements
360  * @param   object   the form
362  * @return  boolean  always false
364  * @see     confirmQuery()
365  */
366 function checkSqlQuery(theForm)
368     var sqlQuery = theForm.elements['sql_query'];
369     var isEmpty  = 1;
371     var space_re = new RegExp('\\s+');
372     if (typeof(theForm.elements['sql_file']) != 'undefined' &&
373             theForm.elements['sql_file'].value.replace(space_re, '') != '') {
374         return true;
375     }
376     if (typeof(theForm.elements['sql_localfile']) != 'undefined' &&
377             theForm.elements['sql_localfile'].value.replace(space_re, '') != '') {
378         return true;
379     }
380     if (isEmpty && typeof(theForm.elements['id_bookmark']) != 'undefined' &&
381             (theForm.elements['id_bookmark'].value != null || theForm.elements['id_bookmark'].value != '') &&
382             theForm.elements['id_bookmark'].selectedIndex != 0
383             ) {
384         return true;
385     }
386     // Checks for "DROP/DELETE/ALTER" statements
387     if (sqlQuery.value.replace(space_re, '') != '') {
388         if (confirmQuery(theForm, sqlQuery)) {
389             return true;
390         } else {
391             return false;
392         }
393     }
394     theForm.reset();
395     isEmpty = 1;
397     if (isEmpty) {
398         sqlQuery.select();
399         alert(PMA_messages['strFormEmpty']);
400         sqlQuery.focus();
401         return false;
402     }
404     return true;
405 } // end of the 'checkSqlQuery()' function
408  * Check if a form's element is empty.
409  * An element containing only spaces is also considered empty
411  * @param   object   the form
412  * @param   string   the name of the form field to put the focus on
414  * @return  boolean  whether the form field is empty or not
415  */
416 function emptyCheckTheField(theForm, theFieldName)
418     var theField = theForm.elements[theFieldName];
419     var space_re = new RegExp('\\s+');
420     return (theField.value.replace(space_re, '') == '') ? 1 : 0;
421 } // end of the 'emptyCheckTheField()' function
425  * Check whether a form field is empty or not
427  * @param   object   the form
428  * @param   string   the name of the form field to put the focus on
430  * @return  boolean  whether the form field is empty or not
431  */
432 function emptyFormElements(theForm, theFieldName)
434     var theField = theForm.elements[theFieldName];
435     var isEmpty = emptyCheckTheField(theForm, theFieldName);
438     return isEmpty;
439 } // end of the 'emptyFormElements()' function
443  * Ensures a value submitted in a form is numeric and is in a range
445  * @param   object   the form
446  * @param   string   the name of the form field to check
447  * @param   integer  the minimum authorized value
448  * @param   integer  the maximum authorized value
450  * @return  boolean  whether a valid number has been submitted or not
451  */
452 function checkFormElementInRange(theForm, theFieldName, message, min, max)
454     var theField         = theForm.elements[theFieldName];
455     var val              = parseInt(theField.value);
457     if (typeof(min) == 'undefined') {
458         min = 0;
459     }
460     if (typeof(max) == 'undefined') {
461         max = Number.MAX_VALUE;
462     }
464     // It's not a number
465     if (isNaN(val)) {
466         theField.select();
467         alert(PMA_messages['strNotNumber']);
468         theField.focus();
469         return false;
470     }
471     // It's a number but it is not between min and max
472     else if (val < min || val > max) {
473         theField.select();
474         alert(message.replace('%d', val));
475         theField.focus();
476         return false;
477     }
478     // It's a valid number
479     else {
480         theField.value = val;
481     }
482     return true;
484 } // end of the 'checkFormElementInRange()' function
487 function checkTableEditForm(theForm, fieldsCnt)
489     // TODO: avoid sending a message if user just wants to add a line
490     // on the form but has not completed at least one field name
492     var atLeastOneField = 0;
493     var i, elm, elm2, elm3, val, id;
495     for (i=0; i<fieldsCnt; i++)
496     {
497         id = "#field_" + i + "_2";
498         elm = $(id);
499         val = elm.val()
500         if (val == 'VARCHAR' || val == 'CHAR' || val == 'BIT' || val == 'VARBINARY' || val == 'BINARY') {
501             elm2 = $("#field_" + i + "_3");
502             val = parseInt(elm2.val());
503             elm3 = $("#field_" + i + "_1");
504             if (isNaN(val) && elm3.val() != "") {
505                 elm2.select();
506                 alert(PMA_messages['strNotNumber']);
507                 elm2.focus();
508                 return false;
509             }
510         }
512         if (atLeastOneField == 0) {
513             id = "field_" + i + "_1";
514             if (!emptyCheckTheField(theForm, id)) {
515                 atLeastOneField = 1;
516             }
517         }
518     }
519     if (atLeastOneField == 0) {
520         var theField = theForm.elements["field_0_1"];
521         alert(PMA_messages['strFormEmpty']);
522         theField.focus();
523         return false;
524     }
526     // at least this section is under jQuery
527     if ($("input.textfield[name='table']").val() == "") {
528         alert(PMA_messages['strFormEmpty']);
529         $("input.textfield[name='table']").focus();
530         return false;
531     }
534     return true;
535 } // enf of the 'checkTableEditForm()' function
537 $(document).ready(function() {
538     /**
539      * Row marking in horizontal mode (use "live" so that it works also for
540      * next pages reached via AJAX); a tr may have the class noclick to remove
541      * this behavior.
542      */
543     $('table:not(.noclick) tr.odd:not(.noclick), table:not(.noclick) tr.even:not(.noclick)').live('click',function(e) {
544         // do not trigger when clicked on anchor
545         if ($(e.target).is('a, img, a *')) {
546             return;
547         }
548         var $tr = $(this);
550         // make the table unselectable (to prevent default highlighting when shift+click)
551         //$tr.parents('table').noSelect();
553         if (!e.shiftKey || last_clicked_row == -1) {
554             // usual click
556             // XXX: FF fires two click events for <label> (label and checkbox), so we need to handle this differently
557             var $checkbox = $tr.find(':checkbox');
558             if ($checkbox.length) {
559                 // checkbox in a row, add or remove class depending on checkbox state
560                 var checked = $checkbox.attr('checked');
561                 if (!$(e.target).is(':checkbox, label')) {
562                     checked = !checked;
563                     $checkbox.attr('checked', checked);
564                 }
565                 if (checked) {
566                     $tr.addClass('marked');
567                 } else {
568                     $tr.removeClass('marked');
569                 }
570                 last_click_checked = checked;
571             } else {
572                 // normaln data table, just toggle class
573                 $tr.toggleClass('marked');
574                 last_click_checked = false;
575             }
577             // remember the last clicked row
578             last_clicked_row = last_click_checked ? $('tr.odd:not(.noclick), tr.even:not(.noclick)').index(this) : -1;
579             last_shift_clicked_row = -1;
580         } else {
581             // handle the shift click
582             PMA_clearSelection();
583             var start, end;
585             // clear last shift click result
586             if (last_shift_clicked_row >= 0) {
587                 if (last_shift_clicked_row >= last_clicked_row) {
588                     start = last_clicked_row;
589                     end = last_shift_clicked_row;
590                 } else {
591                     start = last_shift_clicked_row;
592                     end = last_clicked_row;
593                 }
594                 $tr.parent().find('tr.odd:not(.noclick), tr.even:not(.noclick)')
595                     .slice(start, end + 1)
596                     .removeClass('marked')
597                     .find(':checkbox')
598                     .attr('checked', false);
599             }
601             // handle new shift click
602             var curr_row = $('tr.odd:not(.noclick), tr.even:not(.noclick)').index(this);
603             if (curr_row >= last_clicked_row) {
604                 start = last_clicked_row;
605                 end = curr_row;
606             } else {
607                 start = curr_row;
608                 end = last_clicked_row;
609             }
610             $tr.parent().find('tr.odd:not(.noclick), tr.even:not(.noclick)')
611                 .slice(start, end + 1)
612                 .addClass('marked')
613                 .find(':checkbox')
614                 .attr('checked', true);
616             // remember the last shift clicked row
617             last_shift_clicked_row = curr_row;
618         }
619     });
621     /**
622      * Add a date/time picker to each element that needs it
623      * (only when timepicker.js is loaded)
624      */
625     if ($.timepicker != undefined) {
626         $('.datefield, .datetimefield').each(function() {
627             PMA_addDatepicker($(this));
628             });
629     }
633  * True if last click is to check a row.
634  */
635 var last_click_checked = false;
638  * Zero-based index of last clicked row.
639  * Used to handle the shift + click event in the code above.
640  */
641 var last_clicked_row = -1;
644  * Zero-based index of last shift clicked row.
645  */
646 var last_shift_clicked_row = -1;
649  * Row highlighting in horizontal mode (use "live"
650  * so that it works also for pages reached via AJAX)
651  */
652 /*$(document).ready(function() {
653     $('tr.odd, tr.even').live('hover',function(event) {
654         var $tr = $(this);
655         $tr.toggleClass('hover',event.type=='mouseover');
656         $tr.children().toggleClass('hover',event.type=='mouseover');
657     });
658 })*/
661  * This array is used to remember mark status of rows in browse mode
662  */
663 var marked_row = new Array;
666  * marks all rows and selects its first checkbox inside the given element
667  * the given element is usaly a table or a div containing the table or tables
669  * @param    container    DOM element
670  */
671 function markAllRows( container_id )
674     $("#"+container_id).find("input:checkbox:enabled").attr('checked', 'checked')
675     .parents("tr").addClass("marked");
676     return true;
680  * marks all rows and selects its first checkbox inside the given element
681  * the given element is usaly a table or a div containing the table or tables
683  * @param    container    DOM element
684  */
685 function unMarkAllRows( container_id )
688     $("#"+container_id).find("input:checkbox:enabled").removeAttr('checked')
689     .parents("tr").removeClass("marked");
690     return true;
694  * Checks/unchecks all checkbox in given conainer (f.e. a form, fieldset or div)
696  * @param   string   container_id  the container id
697  * @param   boolean  state         new value for checkbox (true or false)
698  * @return  boolean  always true
699  */
700 function setCheckboxes( container_id, state )
703     if(state) {
704         $("#"+container_id).find("input:checkbox").attr('checked', 'checked');
705     }
706     else {
707         $("#"+container_id).find("input:checkbox").removeAttr('checked');
708     }
710     return true;
711 } // end of the 'setCheckboxes()' function
714   * Checks/unchecks all options of a <select> element
715   *
716   * @param   string   the form name
717   * @param   string   the element name
718   * @param   boolean  whether to check or to uncheck options
719   *
720   * @return  boolean  always true
721   */
722 function setSelectOptions(the_form, the_select, do_check)
724     $("form[name='"+ the_form +"'] select[name='"+the_select+"']").find("option").attr('selected', do_check);
725     return true;
726 } // end of the 'setSelectOptions()' function
729  * Sets current value for query box.
730  */
731 function setQuery(query)
733     if (codemirror_editor) {
734         codemirror_editor.setValue(query);
735     } else {
736         document.sqlform.sql_query.value = query;
737     }
742   * Create quick sql statements.
743   *
744   */
745 function insertQuery(queryType)
747     if (queryType == "clear") {
748         setQuery('');
749         return;
750     }
752     var myQuery = document.sqlform.sql_query;
753     var query = "";
754     var myListBox = document.sqlform.dummy;
755     var table = document.sqlform.table.value;
757     if (myListBox.options.length > 0) {
758         sql_box_locked = true;
759         var chaineAj = "";
760         var valDis = "";
761         var editDis = "";
762         var NbSelect = 0;
763         for (var i=0; i < myListBox.options.length; i++) {
764             NbSelect++;
765             if (NbSelect > 1) {
766                 chaineAj += ", ";
767                 valDis += ",";
768                 editDis += ",";
769             }
770             chaineAj += myListBox.options[i].value;
771             valDis += "[value-" + NbSelect + "]";
772             editDis += myListBox.options[i].value + "=[value-" + NbSelect + "]";
773         }
774         if (queryType == "selectall") {
775             query = "SELECT * FROM `" + table + "` WHERE 1";
776         } else if (queryType == "select") {
777             query = "SELECT " + chaineAj + " FROM `" + table + "` WHERE 1";
778         } else if (queryType == "insert") {
779                query = "INSERT INTO `" + table + "`(" + chaineAj + ") VALUES (" + valDis + ")";
780         } else if (queryType == "update") {
781             query = "UPDATE `" + table + "` SET " + editDis + " WHERE 1";
782         } else if(queryType == "delete") {
783             query = "DELETE FROM `" + table + "` WHERE 1";
784         }
785         setQuery(query);
786         sql_box_locked = false;
787     }
792   * Inserts multiple fields.
793   *
794   */
795 function insertValueQuery()
797     var myQuery = document.sqlform.sql_query;
798     var myListBox = document.sqlform.dummy;
800     if(myListBox.options.length > 0) {
801         sql_box_locked = true;
802         var chaineAj = "";
803         var NbSelect = 0;
804         for(var i=0; i<myListBox.options.length; i++) {
805             if (myListBox.options[i].selected) {
806                 NbSelect++;
807                 if (NbSelect > 1) {
808                     chaineAj += ", ";
809                 }
810                 chaineAj += myListBox.options[i].value;
811             }
812         }
814         /* CodeMirror support */
815         if (codemirror_editor) {
816             codemirror_editor.replaceSelection(chaineAj);
817         //IE support
818         } else if (document.selection) {
819             myQuery.focus();
820             sel = document.selection.createRange();
821             sel.text = chaineAj;
822             document.sqlform.insert.focus();
823         }
824         //MOZILLA/NETSCAPE support
825         else if (document.sqlform.sql_query.selectionStart || document.sqlform.sql_query.selectionStart == "0") {
826             var startPos = document.sqlform.sql_query.selectionStart;
827             var endPos = document.sqlform.sql_query.selectionEnd;
828             var chaineSql = document.sqlform.sql_query.value;
830             myQuery.value = chaineSql.substring(0, startPos) + chaineAj + chaineSql.substring(endPos, chaineSql.length);
831         } else {
832             myQuery.value += chaineAj;
833         }
834         sql_box_locked = false;
835     }
839   * listbox redirection
840   */
841 function goToUrl(selObj, goToLocation)
843     eval("document.location.href = '" + goToLocation + "pos=" + selObj.options[selObj.selectedIndex].value + "'");
847   * Refresh the WYSIWYG scratchboard after changes have been made
848   */
849 function refreshDragOption(e)
851     var elm = $('#' + e);
852     if (elm.css('visibility') == 'visible') {
853         refreshLayout();
854         TableDragInit();
855     }
859   * Refresh/resize the WYSIWYG scratchboard
860   */
861 function refreshLayout()
863     var elm = $('#pdflayout')
864     var orientation = $('#orientation_opt').val();
865     if($('#paper_opt').length==1){
866         var paper = $('#paper_opt').val();
867     }else{
868         var paper = 'A4';
869     }
870     if (orientation == 'P') {
871         posa = 'x';
872         posb = 'y';
873     } else {
874         posa = 'y';
875         posb = 'x';
876     }
877     elm.css('width', pdfPaperSize(paper, posa) + 'px');
878     elm.css('height', pdfPaperSize(paper, posb) + 'px');
882   * Show/hide the WYSIWYG scratchboard
883   */
884 function ToggleDragDrop(e)
886     var elm = $('#' + e);
887     if (elm.css('visibility') == 'hidden') {
888         PDFinit(); /* Defined in pdf_pages.php */
889         elm.css('visibility', 'visible');
890         elm.css('display', 'block');
891         $('#showwysiwyg').val('1')
892     } else {
893         elm.css('visibility', 'hidden');
894         elm.css('display', 'none');
895         $('#showwysiwyg').val('0')
896     }
900   * PDF scratchboard: When a position is entered manually, update
901   * the fields inside the scratchboard.
902   */
903 function dragPlace(no, axis, value)
905     var elm = $('#table_' + no);
906     if (axis == 'x') {
907         elm.css('left', value + 'px');
908     } else {
909         elm.css('top', value + 'px');
910     }
914  * Returns paper sizes for a given format
915  */
916 function pdfPaperSize(format, axis)
918     switch (format.toUpperCase()) {
919         case '4A0':
920             if (axis == 'x') return 4767.87; else return 6740.79;
921             break;
922         case '2A0':
923             if (axis == 'x') return 3370.39; else return 4767.87;
924             break;
925         case 'A0':
926             if (axis == 'x') return 2383.94; else return 3370.39;
927             break;
928         case 'A1':
929             if (axis == 'x') return 1683.78; else return 2383.94;
930             break;
931         case 'A2':
932             if (axis == 'x') return 1190.55; else return 1683.78;
933             break;
934         case 'A3':
935             if (axis == 'x') return 841.89; else return 1190.55;
936             break;
937         case 'A4':
938             if (axis == 'x') return 595.28; else return 841.89;
939             break;
940         case 'A5':
941             if (axis == 'x') return 419.53; else return 595.28;
942             break;
943         case 'A6':
944             if (axis == 'x') return 297.64; else return 419.53;
945             break;
946         case 'A7':
947             if (axis == 'x') return 209.76; else return 297.64;
948             break;
949         case 'A8':
950             if (axis == 'x') return 147.40; else return 209.76;
951             break;
952         case 'A9':
953             if (axis == 'x') return 104.88; else return 147.40;
954             break;
955         case 'A10':
956             if (axis == 'x') return 73.70; else return 104.88;
957             break;
958         case 'B0':
959             if (axis == 'x') return 2834.65; else return 4008.19;
960             break;
961         case 'B1':
962             if (axis == 'x') return 2004.09; else return 2834.65;
963             break;
964         case 'B2':
965             if (axis == 'x') return 1417.32; else return 2004.09;
966             break;
967         case 'B3':
968             if (axis == 'x') return 1000.63; else return 1417.32;
969             break;
970         case 'B4':
971             if (axis == 'x') return 708.66; else return 1000.63;
972             break;
973         case 'B5':
974             if (axis == 'x') return 498.90; else return 708.66;
975             break;
976         case 'B6':
977             if (axis == 'x') return 354.33; else return 498.90;
978             break;
979         case 'B7':
980             if (axis == 'x') return 249.45; else return 354.33;
981             break;
982         case 'B8':
983             if (axis == 'x') return 175.75; else return 249.45;
984             break;
985         case 'B9':
986             if (axis == 'x') return 124.72; else return 175.75;
987             break;
988         case 'B10':
989             if (axis == 'x') return 87.87; else return 124.72;
990             break;
991         case 'C0':
992             if (axis == 'x') return 2599.37; else return 3676.54;
993             break;
994         case 'C1':
995             if (axis == 'x') return 1836.85; else return 2599.37;
996             break;
997         case 'C2':
998             if (axis == 'x') return 1298.27; else return 1836.85;
999             break;
1000         case 'C3':
1001             if (axis == 'x') return 918.43; else return 1298.27;
1002             break;
1003         case 'C4':
1004             if (axis == 'x') return 649.13; else return 918.43;
1005             break;
1006         case 'C5':
1007             if (axis == 'x') return 459.21; else return 649.13;
1008             break;
1009         case 'C6':
1010             if (axis == 'x') return 323.15; else return 459.21;
1011             break;
1012         case 'C7':
1013             if (axis == 'x') return 229.61; else return 323.15;
1014             break;
1015         case 'C8':
1016             if (axis == 'x') return 161.57; else return 229.61;
1017             break;
1018         case 'C9':
1019             if (axis == 'x') return 113.39; else return 161.57;
1020             break;
1021         case 'C10':
1022             if (axis == 'x') return 79.37; else return 113.39;
1023             break;
1024         case 'RA0':
1025             if (axis == 'x') return 2437.80; else return 3458.27;
1026             break;
1027         case 'RA1':
1028             if (axis == 'x') return 1729.13; else return 2437.80;
1029             break;
1030         case 'RA2':
1031             if (axis == 'x') return 1218.90; else return 1729.13;
1032             break;
1033         case 'RA3':
1034             if (axis == 'x') return 864.57; else return 1218.90;
1035             break;
1036         case 'RA4':
1037             if (axis == 'x') return 609.45; else return 864.57;
1038             break;
1039         case 'SRA0':
1040             if (axis == 'x') return 2551.18; else return 3628.35;
1041             break;
1042         case 'SRA1':
1043             if (axis == 'x') return 1814.17; else return 2551.18;
1044             break;
1045         case 'SRA2':
1046             if (axis == 'x') return 1275.59; else return 1814.17;
1047             break;
1048         case 'SRA3':
1049             if (axis == 'x') return 907.09; else return 1275.59;
1050             break;
1051         case 'SRA4':
1052             if (axis == 'x') return 637.80; else return 907.09;
1053             break;
1054         case 'LETTER':
1055             if (axis == 'x') return 612.00; else return 792.00;
1056             break;
1057         case 'LEGAL':
1058             if (axis == 'x') return 612.00; else return 1008.00;
1059             break;
1060         case 'EXECUTIVE':
1061             if (axis == 'x') return 521.86; else return 756.00;
1062             break;
1063         case 'FOLIO':
1064             if (axis == 'x') return 612.00; else return 936.00;
1065             break;
1066     } // end switch
1068     return 0;
1072  * for playing media from the BLOB repository
1074  * @param   var
1075  * @param   var     url_params  main purpose is to pass the token
1076  * @param   var     bs_ref      BLOB repository reference
1077  * @param   var     m_type      type of BLOB repository media
1078  * @param   var     w_width     width of popup window
1079  * @param   var     w_height    height of popup window
1080  */
1081 function popupBSMedia(url_params, bs_ref, m_type, is_cust_type, w_width, w_height)
1083     // if width not specified, use default
1084     if (w_width == undefined) {
1085         w_width = 640;
1086     }
1088     // if height not specified, use default
1089     if (w_height == undefined) {
1090         w_height = 480;
1091     }
1093     // open popup window (for displaying video/playing audio)
1094     var mediaWin = window.open('bs_play_media.php?' + url_params + '&bs_reference=' + bs_ref + '&media_type=' + m_type + '&custom_type=' + is_cust_type, 'viewBSMedia', 'width=' + w_width + ', height=' + w_height + ', resizable=1, scrollbars=1, status=0');
1098  * popups a request for changing MIME types for files in the BLOB repository
1100  * @param   var     db                      database name
1101  * @param   var     table                   table name
1102  * @param   var     reference               BLOB repository reference
1103  * @param   var     current_mime_type       current MIME type associated with BLOB repository reference
1104  */
1105 function requestMIMETypeChange(db, table, reference, current_mime_type)
1107     // no mime type specified, set to default (nothing)
1108     if (undefined == current_mime_type) {
1109         current_mime_type = "";
1110     }
1112     // prompt user for new mime type
1113     var new_mime_type = prompt("Enter custom MIME type", current_mime_type);
1115     // if new mime_type is specified and is not the same as the previous type, request for mime type change
1116     if (new_mime_type && new_mime_type != current_mime_type) {
1117         changeMIMEType(db, table, reference, new_mime_type);
1118     }
1122  * changes MIME types for files in the BLOB repository
1124  * @param   var     db              database name
1125  * @param   var     table           table name
1126  * @param   var     reference       BLOB repository reference
1127  * @param   var     mime_type       new MIME type to be associated with BLOB repository reference
1128  */
1129 function changeMIMEType(db, table, reference, mime_type)
1131     // specify url and parameters for jQuery POST
1132     var mime_chg_url = 'bs_change_mime_type.php';
1133     var params = {bs_db: db, bs_table: table, bs_reference: reference, bs_new_mime_type: mime_type};
1135     // jQuery POST
1136     jQuery.post(mime_chg_url, params);
1140  * Jquery Coding for inline editing SQL_QUERY
1141  */
1142 $(document).ready(function(){
1143     $(".inline_edit_sql").live('click', function(){
1144         var $form = $(this).prev();
1145         var sql_query  = $form.find("input[name='sql_query']").val();
1146         var $inner_sql = $(this).parent().prev().find('.inner_sql');
1147         var old_text   = $inner_sql.html();
1149         var new_content = "<textarea name=\"sql_query_edit\" id=\"sql_query_edit\">" + sql_query + "</textarea>\n";
1150         new_content    += "<input type=\"button\" class=\"btnSave\" value=\"" + PMA_messages['strGo'] + "\">\n";
1151         new_content    += "<input type=\"button\" class=\"btnDiscard\" value=\"" + PMA_messages['strCancel'] + "\">\n";
1152         $inner_sql.replaceWith(new_content);
1154         // These settings are duplicated from the .ready()function in functions.js
1155         var height = $('#sql_query_edit').css('height');
1156         codemirror_editor = CodeMirror.fromTextArea($('textarea[name="sql_query_edit"]')[0], {
1157             lineNumbers: true,
1158             matchBrackets: true,
1159             indentUnit: 4,
1160             mode: "text/x-mysql",
1161             lineWrapping: true
1162         });
1163         codemirror_editor.getScrollerElement().style.height = height;
1164         codemirror_editor.refresh();
1166         $(".btnSave").click(function(){
1167             if (codemirror_editor !== undefined) {
1168                 var sql_query = codemirror_editor.getValue();
1169             } else {
1170                 var sql_query = $(this).prev().val();
1171             }
1172             var $fake_form = $('<form>', {action: 'import.php', method: 'post'})
1173                     .append($form.find("input[name=server], input[name=db], input[name=table], input[name=token]").clone())
1174                     .append($('<input>', {type: 'hidden', name: 'show_query', value: 1}))
1175                     .append($('<input>', {type: 'hidden', name: 'sql_query', value: sql_query}));
1176             $fake_form.appendTo($('body')).submit();
1177         });
1178         $(".btnDiscard").click(function(){
1179             $(this).closest(".sql").html("<span class=\"syntax\"><span class=\"inner_sql\">" + old_text + "</span></span>");
1180         });
1181         return false;
1182     });
1184     $('.sqlbutton').click(function(evt){
1185         insertQuery(evt.target.id);
1186         return false;
1187     });
1189     $("#export_type").change(function(){
1190         if($("#export_type").val()=='svg'){
1191             $("#show_grid_opt").attr("disabled","disabled");
1192             $("#orientation_opt").attr("disabled","disabled");
1193             $("#with_doc").attr("disabled","disabled");
1194             $("#show_table_dim_opt").removeAttr("disabled");
1195             $("#all_table_same_wide").removeAttr("disabled");
1196             $("#paper_opt").removeAttr("disabled","disabled");
1197             $("#show_color_opt").removeAttr("disabled","disabled");
1198             //$(this).css("background-color","yellow");
1199         }else if($("#export_type").val()=='dia'){
1200             $("#show_grid_opt").attr("disabled","disabled");
1201             $("#with_doc").attr("disabled","disabled");
1202             $("#show_table_dim_opt").attr("disabled","disabled");
1203             $("#all_table_same_wide").attr("disabled","disabled");
1204             $("#paper_opt").removeAttr("disabled","disabled");
1205             $("#show_color_opt").removeAttr("disabled","disabled");
1206             $("#orientation_opt").removeAttr("disabled","disabled");
1207         }else if($("#export_type").val()=='eps'){
1208             $("#show_grid_opt").attr("disabled","disabled");
1209             $("#orientation_opt").removeAttr("disabled");
1210             $("#with_doc").attr("disabled","disabled");
1211             $("#show_table_dim_opt").attr("disabled","disabled");
1212             $("#all_table_same_wide").attr("disabled","disabled");
1213             $("#paper_opt").attr("disabled","disabled");
1214             $("#show_color_opt").attr("disabled","disabled");
1216         }else if($("#export_type").val()=='pdf'){
1217             $("#show_grid_opt").removeAttr("disabled");
1218             $("#orientation_opt").removeAttr("disabled");
1219             $("#with_doc").removeAttr("disabled","disabled");
1220             $("#show_table_dim_opt").removeAttr("disabled","disabled");
1221             $("#all_table_same_wide").removeAttr("disabled","disabled");
1222             $("#paper_opt").removeAttr("disabled","disabled");
1223             $("#show_color_opt").removeAttr("disabled","disabled");
1224         }else{
1225             // nothing
1226         }
1227     });
1229     $('#sqlquery').focus().keydown(function (e) {
1230         if (e.ctrlKey && e.keyCode == 13) {
1231             $("#sqlqueryform").submit();
1232         }
1233     });
1235     if ($('#input_username')) {
1236         if ($('#input_username').val() == '') {
1237             $('#input_username').focus();
1238         } else {
1239             $('#input_password').focus();
1240         }
1241     }
1245  * Show a message on the top of the page for an Ajax request
1247  * Sample usage:
1249  * 1) var $msg = PMA_ajaxShowMessage();
1250  * This will show a message that reads "Loading...". Such a message will not
1251  * disappear automatically and cannot be dismissed by the user. To remove this
1252  * message either the PMA_ajaxRemoveMessage($msg) function must be called or
1253  * another message must be show with PMA_ajaxShowMessage() function.
1255  * 2) var $msg = PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
1256  * This is a special case. The behaviour is same as above,
1257  * just with a different message
1259  * 3) var $msg = PMA_ajaxShowMessage('The operation was successful');
1260  * This will show a message that will disappear automatically and it can also
1261  * be dismissed by the user.
1263  * 4) var $msg = PMA_ajaxShowMessage('Some error', false);
1264  * This will show a message that will not disappear automatically, but it
1265  * can be dismissed by the user after he has finished reading it.
1267  * @param   string  message     string containing the message to be shown.
1268  *                              optional, defaults to 'Loading...'
1269  * @param   mixed   timeout     number of milliseconds for the message to be visible
1270  *                              optional, defaults to 5000. If set to 'false', the
1271  *                              notification will never disappear
1272  * @return  jQuery object       jQuery Element that holds the message div
1273  *                              this object can be passed to PMA_ajaxRemoveMessage()
1274  *                              to remove the notification
1275  */
1276 function PMA_ajaxShowMessage(message, timeout)
1278     /**
1279      * @var self_closing Whether the notification will automatically disappear
1280      */
1281     var self_closing = true;
1282     /**
1283      * @var dismissable Whether the user will be able to remove
1284      *                  the notification by clicking on it
1285      */
1286     var dismissable = true;
1287     // Handle the case when a empty data.message is passed.
1288     // We don't want the empty message
1289     if (message == '') {
1290         return true;
1291     } else if (! message) {
1292         // If the message is undefined, show the default
1293         message = PMA_messages['strLoading'];
1294         dismissable = false;
1295         self_closing = false;
1296     } else if (message == PMA_messages['strProcessingRequest']) {
1297         // This is another case where the message should not disappear
1298         dismissable = false;
1299         self_closing = false;
1300     }
1301     // Figure out whether (or after how long) to remove the notification
1302     if (timeout == undefined) {
1303         timeout = 5000;
1304     } else if (timeout === false) {
1305         self_closing = false;
1306     }
1307     // Create a parent element for the AJAX messages, if necessary
1308     if ($('#loading_parent').length == 0) {
1309         $('<div id="loading_parent"></div>')
1310         .prependTo("body");
1311     }
1312     // Update message count to create distinct message elements every time
1313     ajax_message_count++;
1314     // Remove all old messages, if any
1315     $(".ajax_notification[id^=ajax_message_num]").remove();
1316     /**
1317      * @var    $retval    a jQuery object containing the reference
1318      *                    to the created AJAX message
1319      */
1320     var $retval = $(
1321             '<span class="ajax_notification" id="ajax_message_num_'
1322             + ajax_message_count +
1323             '"></span>'
1324     )
1325     .hide()
1326     .appendTo("#loading_parent")
1327     .html(message)
1328     .fadeIn('medium');
1329     // If the notification is self-closing we should create a callback to remove it
1330     if (self_closing) {
1331         $retval
1332         .delay(timeout)
1333         .fadeOut('medium', function() {
1334             if ($(this).is('.dismissable')) {
1335                 // Here we should destroy the qtip instance, but
1336                 // due to a bug in qtip's implementation we can
1337                 // only hide it without throwing JS errors.
1338                 $(this).qtip('hide');
1339             }
1340             // Remove the notification
1341             $(this).remove();
1342         });
1343     }
1344     // If the notification is dismissable we need to add the relevant class to it
1345     // and add a tooltip so that the users know that it can be removed
1346     if (dismissable) {
1347         $retval.addClass('dismissable').css('cursor', 'pointer');
1348         /**
1349          * @var qOpts Options for "Dismiss notification" tooltip
1350          */
1351         var qOpts = {
1352             show: {
1353                 effect: { length: 0 },
1354                 delay: 0
1355             },
1356             hide: {
1357                 effect: { length: 0 },
1358                 delay: 0
1359             }
1360         };
1361         /**
1362          * Add a tooltip to the notification to let the user know that (s)he
1363          * can dismiss the ajax notification by clicking on it.
1364          */
1365         PMA_createqTip($retval, PMA_messages['strDismiss'], qOpts);
1366     }
1368     return $retval;
1372  * Removes the message shown for an Ajax operation when it's completed
1374  * @param  jQuery object   jQuery Element that holds the notification
1376  * @return nothing
1377  */
1378 function PMA_ajaxRemoveMessage($this_msgbox)
1380     if ($this_msgbox != undefined && $this_msgbox instanceof jQuery) {
1381         $this_msgbox
1382         .stop(true, true)
1383         .fadeOut('medium');
1384         if ($this_msgbox.is('.dismissable')) {
1385             // Here we should destroy the qtip instance, but
1386             // due to a bug in qtip's implementation we can
1387             // only hide it without throwing JS errors.
1388             $this_msgbox.qtip('hide');
1389         } else {
1390             $this_msgbox.remove();
1391         }
1392     }
1395 $(document).ready(function() {
1396     /**
1397      * Allows the user to dismiss a notification
1398      * created with PMA_ajaxShowMessage()
1399      */
1400     $('.ajax_notification.dismissable').live('click', function () {
1401         PMA_ajaxRemoveMessage($(this));
1402     });
1403     /**
1404      * The below two functions hide the "Dismiss notification" tooltip when a user
1405      * is hovering a link or button that is inside an ajax message
1406      */
1407     $('.ajax_notification a, .ajax_notification button, .ajax_notification input')
1408     .live('mouseover', function () {
1409         $(this).parents('.ajax_notification').qtip('hide');
1410     });
1411     $('.ajax_notification a, .ajax_notification button, .ajax_notification input')
1412     .live('mouseout', function () {
1413         $(this).parents('.ajax_notification').qtip('show');
1414     });
1418  * Hides/shows the "Open in ENUM/SET editor" message, depending on the data type of the column currently selected
1419  */
1420 function PMA_showNoticeForEnum(selectElement)
1422     var enum_notice_id = selectElement.attr("id").split("_")[1];
1423     enum_notice_id += "_" + (parseInt(selectElement.attr("id").split("_")[2]) + 1);
1424     var selectedType = selectElement.val();
1425     if (selectedType == "ENUM" || selectedType == "SET") {
1426         $("p[id='enum_notice_" + enum_notice_id + "']").show();
1427     } else {
1428         $("p[id='enum_notice_" + enum_notice_id + "']").hide();
1429     }
1433  * Generates a dialog box to pop up the create_table form
1434  */
1435 function PMA_createTableDialog( $div, url , target)
1437      /**
1438      *  @var    button_options  Object that stores the options passed to jQueryUI
1439      *                          dialog
1440      */
1441      var button_options = {};
1442      // in the following function we need to use $(this)
1443      button_options[PMA_messages['strCancel']] = function() {$(this).closest('.ui-dialog-content').dialog('close').remove();}
1445      var button_options_error = {};
1446      button_options_error[PMA_messages['strOK']] = function() {$(this).closest('.ui-dialog-content').dialog('close').remove();}
1448      var $msgbox = PMA_ajaxShowMessage();
1450      $.get( target , url ,  function(data) {
1451          //in the case of an error, show the error message returned.
1452          if (data.success != undefined && data.success == false) {
1453              $div
1454              .append(data.error)
1455              .dialog({
1456                  height: 230,
1457                  width: 900,
1458                  open: PMA_verifyColumnsProperties,
1459                  buttons : button_options_error
1460              })// end dialog options
1461              //remove the redundant [Back] link in the error message.
1462              .find('fieldset').remove();
1463          } else {
1464              var size = getWindowSize();
1465              var timeout;
1466              $div
1467              .append(data)
1468              .dialog({
1469                  dialogClass: 'create-table',
1470                  resizable: false,
1471                  draggable: false,
1472                  modal: true,
1473                  stack: false,
1474                  position: ['left','top'],
1475                  width: size.width-10,
1476                  height: size.height-10,
1477                  open: function() {
1478                      var dialog_id = $(this).attr('id');
1479                      $(window).bind('resize.dialog-resizer', function() {
1480                          clearTimeout(timeout);
1481                          timeout = setTimeout(function() {
1482                              var size = getWindowSize();
1483                              $('#'+dialog_id).dialog('option', {
1484                                  width: size.width-10,
1485                                  height: size.height-10
1486                              });
1487                          }, 50);
1488                      });
1490                      var $wrapper = $('<div>', {'id': 'content-hide'}).hide();
1491                      $('body > *:not(.ui-dialog)').wrapAll($wrapper);
1493                      $(this)
1494                          .scrollTop(0) // for Chrome
1495                          .closest('.ui-dialog').css({
1496                              left: 0,
1497                              top: 0
1498                          });
1500                      PMA_verifyColumnsProperties();
1502                      // move the Cancel button next to the Save button
1503                      var $button_pane = $('.ui-dialog-buttonpane');
1504                      var $cancel_button = $button_pane.find('.ui-button');
1505                      var $save_button  = $('#create_table_form').find("input[name='do_save_data']");
1506                      $cancel_button.insertAfter($save_button);
1507                      $button_pane.hide();
1508                  },
1509                  close: function() {
1510                      $(window).unbind('resize.dialog-resizer');
1511                      $('#content-hide > *').unwrap();
1512                  },
1513                  buttons: button_options
1514              }); // end dialog options
1515          }
1516          PMA_convertFootnotesToTooltips($div);
1517          PMA_ajaxRemoveMessage($msgbox);
1518      }); // end $.get()
1523  * Creates a highcharts chart in the given container
1525  * @param   var     settings    object with highcharts properties that should be applied. (See also http://www.highcharts.com/ref/)
1526  *                              requires at least settings.chart.renderTo and settings.series to be set.
1527  *                              In addition there may be an additional property object 'realtime' that allows for realtime charting:
1528  *                              realtime: {
1529  *                                  url: adress to get the data from (will always add token, ajax_request=1 and chart_data=1 to the GET request)
1530  *                                  type: the GET request will also add type=[value of the type property] to the request
1531  *                                  callback: Callback function that should draw the point, it's called with 4 parameters in this order:
1532  *                                      - the chart object
1533  *                                      - the current response value of the GET request, JSON parsed
1534  *                                      - the previous response value of the GET request, JSON parsed
1535  *                                      - the number of added points
1536  *                                  error: Callback function when the get request fails. TODO: Apply callback on timeouts aswell
1537  *                              }
1539  * @return  object   The created highcharts instance
1540  */
1541 function PMA_createChart(passedSettings)
1543     var container = passedSettings.chart.renderTo;
1545     var settings = {
1546         chart: {
1547             type: 'spline',
1548             marginRight: 10,
1549             backgroundColor: 'none',
1550             events: {
1551                 /* Live charting support */
1552                 load: function() {
1553                     var thisChart = this;
1554                     var lastValue = null, curValue = null;
1555                     var numLoadedPoints = 0, otherSum = 0;
1556                     var diff;
1558                     // No realtime updates for graphs that are being exported, and disabled when realtime is not set
1559                     // Also don't do live charting if we don't have the server time
1560                     if(thisChart.options.chart.forExport == true ||
1561                         ! thisChart.options.realtime ||
1562                         ! thisChart.options.realtime.callback ||
1563                         ! server_time_diff) return;
1565                     thisChart.options.realtime.timeoutCallBack = function() {
1566                         thisChart.options.realtime.postRequest = $.post(
1567                             thisChart.options.realtime.url,
1568                             thisChart.options.realtime.postData,
1569                             function(data) {
1570                                 try {
1571                                     curValue = jQuery.parseJSON(data);
1572                                 } catch (err) {
1573                                     if(thisChart.options.realtime.error)
1574                                         thisChart.options.realtime.error(err);
1575                                     return;
1576                                 }
1578                                 if (lastValue==null) {
1579                                     diff = curValue.x - thisChart.xAxis[0].getExtremes().max;
1580                                 } else {
1581                                     diff = parseInt(curValue.x - lastValue.x);
1582                                 }
1584                                 thisChart.xAxis[0].setExtremes(
1585                                     thisChart.xAxis[0].getExtremes().min+diff,
1586                                     thisChart.xAxis[0].getExtremes().max+diff,
1587                                     false
1588                                 );
1590                                 thisChart.options.realtime.callback(thisChart,curValue,lastValue,numLoadedPoints);
1592                                 lastValue = curValue;
1593                                 numLoadedPoints++;
1595                                 // Timeout has been cleared => don't start a new timeout
1596                                 if (chart_activeTimeouts[container] == null) {
1597                                     return;
1598                                 }
1600                                 chart_activeTimeouts[container] = setTimeout(
1601                                     thisChart.options.realtime.timeoutCallBack,
1602                                     thisChart.options.realtime.refreshRate
1603                                 );
1604                         });
1605                     }
1607                     chart_activeTimeouts[container] = setTimeout(thisChart.options.realtime.timeoutCallBack, 5);
1608                 }
1609             }
1610         },
1611         plotOptions: {
1612             series: {
1613                 marker: {
1614                     radius: 3
1615                 }
1616             }
1617         },
1618         credits: {
1619             enabled:false
1620         },
1621         xAxis: {
1622             type: 'datetime'
1623         },
1624         yAxis: {
1625             min: 0,
1626             title: {
1627                 text: PMA_messages['strTotalCount']
1628             },
1629             plotLines: [{
1630                 value: 0,
1631                 width: 1,
1632                 color: '#808080'
1633             }]
1634         },
1635         tooltip: {
1636             formatter: function() {
1637                     return '<b>' + this.series.name +'</b><br/>' +
1638                     Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '<br/>' +
1639                     Highcharts.numberFormat(this.y, 2);
1640             }
1641         },
1642         exporting: {
1643             enabled: true
1644         },
1645         series: []
1646     }
1648     /* Set/Get realtime chart default values */
1649     if(passedSettings.realtime) {
1650         if(!passedSettings.realtime.refreshRate) {
1651             passedSettings.realtime.refreshRate = 5000;
1652         }
1654         if(!passedSettings.realtime.numMaxPoints) {
1655             passedSettings.realtime.numMaxPoints = 30;
1656         }
1658         // Allow custom POST vars to be added
1659         passedSettings.realtime.postData = $.extend(false,{ ajax_request: true, chart_data: 1, type: passedSettings.realtime.type },passedSettings.realtime.postData);
1661         if(server_time_diff) {
1662             settings.xAxis.min = new Date().getTime() - server_time_diff - passedSettings.realtime.numMaxPoints * passedSettings.realtime.refreshRate;
1663             settings.xAxis.max = new Date().getTime() - server_time_diff + passedSettings.realtime.refreshRate;
1664         }
1665     }
1667     // Overwrite/Merge default settings with passedsettings
1668     $.extend(true,settings,passedSettings);
1670     return new Highcharts.Chart(settings);
1675  * Creates a Profiling Chart. Used in sql.php and server_status.js
1676  */
1677 function PMA_createProfilingChart(data, options)
1679     return PMA_createChart($.extend(true, {
1680         chart: {
1681             renderTo: 'profilingchart',
1682             type: 'pie'
1683         },
1684         title: { text:'', margin:0 },
1685         series: [{
1686             type: 'pie',
1687             name: PMA_messages['strQueryExecutionTime'],
1688             data: data
1689         }],
1690         plotOptions: {
1691             pie: {
1692                 allowPointSelect: true,
1693                 cursor: 'pointer',
1694                 dataLabels: {
1695                     enabled: true,
1696                     distance: 35,
1697                     formatter: function() {
1698                         return '<b>'+ this.point.name +'</b><br/>'+ Highcharts.numberFormat(this.percentage, 2) +' %';
1699                    }
1700                 }
1701             }
1702         },
1703         tooltip: {
1704             formatter: function() {
1705                 return '<b>'+ this.point.name +'</b><br/>'+PMA_prettyProfilingNum(this.y)+'<br/>('+Highcharts.numberFormat(this.percentage, 2) +' %)';
1706             }
1707         }
1708     },options));
1712  * Formats a profiling duration nicely (in us and ms time). Used in PMA_createProfilingChart() and server_status.js
1714  * @param   integer     Number to be formatted, should be in the range of microsecond to second
1715  * @param   integer     Acuracy, how many numbers right to the comma should be
1716  * @return  string      The formatted number
1717  */
1718 function PMA_prettyProfilingNum(num, acc)
1720     if (!acc) {
1721         acc = 2;
1722     }
1723     acc = Math.pow(10,acc);
1724     if (num * 1000 < 0.1) {
1725         num = Math.round(acc * (num * 1000 * 1000)) / acc + 'µ';
1726     } else if (num < 0.1) {
1727         num = Math.round(acc * (num * 1000)) / acc + 'm';
1728     } else {
1729         num = Math.round(acc * num) / acc;
1730     }
1732     return num + 's';
1737  * Formats a SQL Query nicely with newlines and indentation. Depends on Codemirror and MySQL Mode!
1739  * @param   string      Query to be formatted
1740  * @return  string      The formatted query
1741  */
1742 function PMA_SQLPrettyPrint(string)
1744     var mode = CodeMirror.getMode({},"text/x-mysql");
1745     var stream = new CodeMirror.StringStream(string);
1746     var state = mode.startState();
1747     var token, tokens = [];
1748     var output = '';
1749     var tabs = function(cnt) {
1750         var ret = '';
1751         for (var i=0; i<4*cnt; i++)
1752             ret += " ";
1753         return ret;
1754     };
1756     // "root-level" statements
1757     var statements = {
1758         'select': ['select', 'from','on','where','having','limit','order by','group by'],
1759         'update': ['update', 'set','where'],
1760         'insert into': ['insert into', 'values']
1761     };
1762     // don't put spaces before these tokens
1763     var spaceExceptionsBefore = { ';':true, ',': true, '.': true, '(': true };
1764     // don't put spaces after these tokens
1765     var spaceExceptionsAfter = { '.': true };
1767     // Populate tokens array
1768     var str='';
1769     while (! stream.eol()) {
1770         stream.start = stream.pos;
1771         token = mode.token(stream, state);
1772         if(token != null) {
1773             tokens.push([token, stream.current().toLowerCase()]);
1774         }
1775     }
1777     var currentStatement = tokens[0][1];
1779     if(! statements[currentStatement]) {
1780         return string;
1781     }
1782     // Holds all currently opened code blocks (statement, function or generic)
1783     var blockStack = [];
1784     // Holds the type of block from last iteration (the current is in blockStack[0])
1785     var previousBlock;
1786     // If a new code block is found, newBlock contains its type for one iteration and vice versa for endBlock
1787     var newBlock, endBlock;
1788     // How much to indent in the current line
1789     var indentLevel = 0;
1790     // Holds the "root-level" statements
1791     var statementPart, lastStatementPart = statements[currentStatement][0];
1793     blockStack.unshift('statement');
1795     // Iterate through every token and format accordingly
1796     for (var i = 0; i < tokens.length; i++) {
1797         previousBlock = blockStack[0];
1799         // New block => push to stack
1800         if (tokens[i][1] == '(') {
1801             if (i < tokens.length - 1 && tokens[i+1][0] == 'statement-verb') {
1802                 blockStack.unshift(newBlock = 'statement');
1803             } else if (i > 0 && tokens[i-1][0] == 'builtin') {
1804                 blockStack.unshift(newBlock = 'function');
1805             } else {
1806                 blockStack.unshift(newBlock = 'generic');
1807             }
1808         } else {
1809             newBlock = null;
1810         }
1812         // Block end => pop from stack
1813         if (tokens[i][1] == ')') {
1814             endBlock = blockStack[0];
1815             blockStack.shift();
1816         } else {
1817             endBlock = null;
1818         }
1820         // A subquery is starting
1821         if (i > 0 && newBlock == 'statement') {
1822             indentLevel++;
1823             output += "\n" + tabs(indentLevel) + tokens[i][1] + ' ' + tokens[i+1][1].toUpperCase() + "\n" + tabs(indentLevel + 1);
1824             currentStatement = tokens[i+1][1];
1825             i++;
1826             continue;
1827         }
1829         // A subquery is ending
1830         if (endBlock == 'statement' && indentLevel > 0) {
1831             output += "\n" + tabs(indentLevel);
1832             indentLevel--;
1833         }
1835         // One less indentation for statement parts (from, where, order by, etc.) and a newline
1836         statementPart = statements[currentStatement].indexOf(tokens[i][1]);
1837         if (statementPart != -1) {
1838             if (i > 0) output += "\n";
1839             output += tabs(indentLevel) + tokens[i][1].toUpperCase();
1840             output += "\n" + tabs(indentLevel + 1);
1841             lastStatementPart = tokens[i][1];
1842         }
1843         // Normal indentatin and spaces for everything else
1844         else {
1845             if (! spaceExceptionsBefore[tokens[i][1]]
1846                && ! (i > 0 && spaceExceptionsAfter[tokens[i-1][1]])
1847                && output.charAt(output.length -1) != ' ' ) {
1848                     output += " ";
1849             }
1850             if (tokens[i][0] == 'keyword') {
1851                 output += tokens[i][1].toUpperCase();
1852             } else {
1853                 output += tokens[i][1];
1854             }
1855         }
1857         // split columns in select and 'update set' clauses, but only inside statements blocks
1858         if (( lastStatementPart == 'select' || lastStatementPart == 'where'  || lastStatementPart == 'set')
1859             && tokens[i][1]==',' && blockStack[0] == 'statement') {
1861             output += "\n" + tabs(indentLevel + 1);
1862         }
1864         // split conditions in where clauses, but only inside statements blocks
1865         if (lastStatementPart == 'where'
1866             && (tokens[i][1]=='and' || tokens[i][1]=='or' || tokens[i][1]=='xor')) {
1868             if (blockStack[0] == 'statement') {
1869                 output += "\n" + tabs(indentLevel + 1);
1870             }
1871             // Todo: Also split and or blocks in newlines & identation++
1872             //if(blockStack[0] == 'generic')
1873              //   output += ...
1874         }
1875     }
1876     return output;
1880  * jQuery function that uses jQueryUI's dialogs to confirm with user. Does not
1881  *  return a jQuery object yet and hence cannot be chained
1883  * @param   string      question
1884  * @param   string      url         URL to be passed to the callbackFn to make
1885  *                                  an Ajax call to
1886  * @param   function    callbackFn  callback to execute after user clicks on OK
1887  */
1889 jQuery.fn.PMA_confirm = function(question, url, callbackFn) {
1890     if (PMA_messages['strDoYouReally'] == '') {
1891         return true;
1892     }
1894     /**
1895      *  @var    button_options  Object that stores the options passed to jQueryUI
1896      *                          dialog
1897      */
1898     var button_options = {};
1899     button_options[PMA_messages['strOK']] = function(){
1900                                                 $(this).dialog("close").remove();
1902                                                 if($.isFunction(callbackFn)) {
1903                                                     callbackFn.call(this, url);
1904                                                 }
1905                                             };
1906     button_options[PMA_messages['strCancel']] = function() {$(this).dialog("close").remove();}
1908     $('<div id="confirm_dialog"></div>')
1909     .prepend(question)
1910     .dialog({buttons: button_options});
1914  * jQuery function to sort a table's body after a new row has been appended to it.
1915  * Also fixes the even/odd classes of the table rows at the end.
1917  * @param   string      text_selector   string to select the sortKey's text
1919  * @return  jQuery Object for chaining purposes
1920  */
1921 jQuery.fn.PMA_sort_table = function(text_selector) {
1922     return this.each(function() {
1924         /**
1925          * @var table_body  Object referring to the table's <tbody> element
1926          */
1927         var table_body = $(this);
1928         /**
1929          * @var rows    Object referring to the collection of rows in {@link table_body}
1930          */
1931         var rows = $(this).find('tr').get();
1933         //get the text of the field that we will sort by
1934         $.each(rows, function(index, row) {
1935             row.sortKey = $.trim($(row).find(text_selector).text().toLowerCase());
1936         })
1938         //get the sorted order
1939         rows.sort(function(a,b) {
1940             if(a.sortKey < b.sortKey) {
1941                 return -1;
1942             }
1943             if(a.sortKey > b.sortKey) {
1944                 return 1;
1945             }
1946             return 0;
1947         })
1949         //pull out each row from the table and then append it according to it's order
1950         $.each(rows, function(index, row) {
1951             $(table_body).append(row);
1952             row.sortKey = null;
1953         })
1955         //Re-check the classes of each row
1956         $(this).find('tr:odd')
1957         .removeClass('even').addClass('odd')
1958         .end()
1959         .find('tr:even')
1960         .removeClass('odd').addClass('even');
1961     })
1965  * jQuery coding for 'Create Table'.  Used on db_operations.php,
1966  * db_structure.php and db_tracking.php (i.e., wherever
1967  * libraries/display_create_table.lib.php is used)
1969  * Attach Ajax Event handlers for Create Table
1970  */
1971 $(document).ready(function() {
1973      /**
1974      * Attach event handler to the submit action of the create table minimal form
1975      * and retrieve the full table form and display it in a dialog
1976      */
1977     $("#create_table_form_minimal.ajax").live('submit', function(event) {
1978         event.preventDefault();
1979         $form = $(this);
1980         PMA_prepareForAjaxRequest($form);
1982         /*variables which stores the common attributes*/
1983         var url = $form.serialize();
1984         var action = $form.attr('action');
1985         var $div =  $('<div id="create_table_dialog"></div>');
1987         /*Calling to the createTableDialog function*/
1988         PMA_createTableDialog($div, url, action);
1990         // empty table name and number of columns from the minimal form
1991         $form.find('input[name=table],input[name=num_fields]').val('');
1992     });
1994     /**
1995      * Attach event handler for submission of create table form (save)
1996      *
1997      * @uses    PMA_ajaxShowMessage()
1998      * @uses    $.PMA_sort_table()
1999      *
2000      */
2001     // .live() must be called after a selector, see http://api.jquery.com/live
2002     $("#create_table_form input[name=do_save_data]").live('click', function(event) {
2003         event.preventDefault();
2005         /**
2006          *  @var    the_form    object referring to the create table form
2007          */
2008         var $form = $("#create_table_form");
2010         /*
2011          * First validate the form; if there is a problem, avoid submitting it
2012          *
2013          * checkTableEditForm() needs a pure element and not a jQuery object,
2014          * this is why we pass $form[0] as a parameter (the jQuery object
2015          * is actually an array of DOM elements)
2016          */
2018         if (checkTableEditForm($form[0], $form.find('input[name=orig_num_fields]').val())) {
2019             // OK, form passed validation step
2020             if ($form.hasClass('ajax')) {
2021                 PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
2022                 PMA_prepareForAjaxRequest($form);
2023                 //User wants to submit the form
2024                 $.post($form.attr('action'), $form.serialize() + "&do_save_data=" + $(this).val(), function(data) {
2025                     if(data.success == true) {
2026                         $('#properties_message')
2027                          .removeClass('error')
2028                          .html('');
2029                         PMA_ajaxShowMessage(data.message);
2030                         // Only if the create table dialog (distinct panel) exists
2031                         if ($("#create_table_dialog").length > 0) {
2032                             $("#create_table_dialog").dialog("close").remove();
2033                         }
2035                         /**
2036                          * @var tables_table    Object referring to the <tbody> element that holds the list of tables
2037                          */
2038                         var tables_table = $("#tablesForm").find("tbody").not("#tbl_summary_row");
2039                         // this is the first table created in this db
2040                         if (tables_table.length == 0) {
2041                             if (window.parent && window.parent.frame_content) {
2042                                 window.parent.frame_content.location.reload();
2043                             }
2044                         } else {
2045                             /**
2046                              * @var curr_last_row   Object referring to the last <tr> element in {@link tables_table}
2047                              */
2048                             var curr_last_row = $(tables_table).find('tr:last');
2049                             /**
2050                              * @var curr_last_row_index_string   String containing the index of {@link curr_last_row}
2051                              */
2052                             var curr_last_row_index_string = $(curr_last_row).find('input:checkbox').attr('id').match(/\d+/)[0];
2053                             /**
2054                              * @var curr_last_row_index Index of {@link curr_last_row}
2055                              */
2056                             var curr_last_row_index = parseFloat(curr_last_row_index_string);
2057                             /**
2058                              * @var new_last_row_index   Index of the new row to be appended to {@link tables_table}
2059                              */
2060                             var new_last_row_index = curr_last_row_index + 1;
2061                             /**
2062                              * @var new_last_row_id String containing the id of the row to be appended to {@link tables_table}
2063                              */
2064                             var new_last_row_id = 'checkbox_tbl_' + new_last_row_index;
2066                             data.new_table_string = data.new_table_string.replace(/checkbox_tbl_/, new_last_row_id);
2067                             //append to table
2068                             $(data.new_table_string)
2069                              .appendTo(tables_table);
2071                             //Sort the table
2072                             $(tables_table).PMA_sort_table('th');
2074                             // Adjust summary row
2075                             PMA_adjustTotals();
2076                         }
2078                         //Refresh navigation frame as a new table has been added
2079                         if (window.parent && window.parent.frame_navigation) {
2080                             window.parent.frame_navigation.location.reload();
2081                         }
2082                     } else {
2083                         $('#properties_message')
2084                          .addClass('error')
2085                          .html(data.error);
2086                         // scroll to the div containing the error message
2087                         $('#properties_message')[0].scrollIntoView();
2088                     }
2089                 }) // end $.post()
2090             } // end if ($form.hasClass('ajax')
2091             else {
2092                 // non-Ajax submit
2093                 $form.append('<input type="hidden" name="do_save_data" value="save" />');
2094                 $form.submit();
2095             }
2096         } // end if (checkTableEditForm() )
2097     }) // end create table form (save)
2099     /**
2100      * Attach event handler for create table form (add fields)
2101      *
2102      * @uses    PMA_ajaxShowMessage()
2103      * @uses    $.PMA_sort_table()
2104      * @uses    window.parent.refreshNavigation()
2105      *
2106      */
2107     // .live() must be called after a selector, see http://api.jquery.com/live
2108     $("#create_table_form.ajax input[name=submit_num_fields]").live('click', function(event) {
2109         event.preventDefault();
2111         /**
2112          *  @var    the_form    object referring to the create table form
2113          */
2114         var $form = $("#create_table_form");
2116         var $msgbox = PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
2117         PMA_prepareForAjaxRequest($form);
2119         //User wants to add more fields to the table
2120         $.post($form.attr('action'), $form.serialize() + "&submit_num_fields=" + $(this).val(), function(data) {
2121             // if 'create_table_dialog' exists
2122             if ($("#create_table_dialog").length > 0) {
2123                 $("#create_table_dialog").html(data);
2124             }
2125             // if 'create_table_div' exists
2126             if ($("#create_table_div").length > 0) {
2127                 $("#create_table_div").html(data);
2128             }
2129             PMA_verifyColumnsProperties();
2130             PMA_ajaxRemoveMessage($msgbox);
2131         }) //end $.post()
2133     }) // end create table form (add fields)
2135 }, 'top.frame_content'); //end $(document).ready for 'Create Table'
2138  * jQuery coding for 'Change Table' and 'Add Column'.  Used on tbl_structure.php *
2139  * Attach Ajax Event handlers for Change Table
2140  */
2141 $(document).ready(function() {
2142     /**
2143      *Ajax action for submitting the "Column Change" and "Add Column" form
2144     **/
2145     $("#append_fields_form input[name=do_save_data]").live('click', function(event) {
2146         event.preventDefault();
2147         /**
2148          *  @var    the_form    object referring to the export form
2149          */
2150         var $form = $("#append_fields_form");
2152         /*
2153          * First validate the form; if there is a problem, avoid submitting it
2154          *
2155          * checkTableEditForm() needs a pure element and not a jQuery object,
2156          * this is why we pass $form[0] as a parameter (the jQuery object
2157          * is actually an array of DOM elements)
2158          */
2159         if (checkTableEditForm($form[0], $form.find('input[name=orig_num_fields]').val())) {
2160             // OK, form passed validation step
2161             if ($form.hasClass('ajax')) {
2162                 PMA_prepareForAjaxRequest($form);
2163                 //User wants to submit the form
2164                 $.post($form.attr('action'), $form.serialize()+"&do_save_data=Save", function(data) {
2165                     if ($("#sqlqueryresults").length != 0) {
2166                         $("#sqlqueryresults").remove();
2167                     } else if ($(".error").length != 0) {
2168                         $(".error").remove();
2169                     }
2170                     if (data.success == true) {
2171                         PMA_ajaxShowMessage(data.message);
2172                         $("<div id='sqlqueryresults'></div>").insertAfter("#floating_menubar");
2173                         $("#sqlqueryresults").html(data.sql_query);
2174                         $("#result_query .notice").remove();
2175                         $("#result_query").prepend((data.message));
2176                         if ($("#change_column_dialog").length > 0) {
2177                             $("#change_column_dialog").dialog("close").remove();
2178                         } else if ($("#add_columns").length > 0) {
2179                             $("#add_columns").dialog("close").remove();
2180                         }
2181                         /*Reload the field form*/
2182                         $.post($("#fieldsForm").attr('action'), $("#fieldsForm").serialize()+"&ajax_request=true", function(form_data) {
2183                             $("#fieldsForm").remove();
2184                             $("#addColumns").remove();
2185                             var $temp_div = $("<div id='temp_div'><div>").append(form_data);
2186                             if ($("#sqlqueryresults").length != 0) {
2187                                 $temp_div.find("#fieldsForm").insertAfter("#sqlqueryresults");
2188                             } else {
2189                                 $temp_div.find("#fieldsForm").insertAfter(".error");
2190                             }
2191                             $temp_div.find("#addColumns").insertBefore("iframe.IE_hack");
2192                             /*Call the function to display the more options in table*/
2193                             displayMoreTableOpts();
2194                         });
2195                     } else {
2196                         var $temp_div = $("<div id='temp_div'><div>").append(data);
2197                         var $error = $temp_div.find(".error code").addClass("error");
2198                         PMA_ajaxShowMessage($error, false);
2199                     }
2200                 }) // end $.post()
2201             } else {
2202                 // non-Ajax submit
2203                 $form.append('<input type="hidden" name="do_save_data" value="Save" />');
2204                 $form.submit();
2205             }
2206         }
2207     }) // end change table button "do_save_data"
2209 }, 'top.frame_content'); //end $(document).ready for 'Change Table'
2212  * jQuery coding for 'Table operations'.  Used on tbl_operations.php
2213  * Attach Ajax Event handlers for Table operations
2214  */
2215 $(document).ready(function() {
2216     /**
2217      *Ajax action for submitting the "Alter table order by"
2218     **/
2219     $("#alterTableOrderby.ajax").live('submit', function(event) {
2220         event.preventDefault();
2221         var $form = $(this);
2223         PMA_prepareForAjaxRequest($form);
2224         /*variables which stores the common attributes*/
2225         $.post($form.attr('action'), $form.serialize()+"&submitorderby=Go", function(data) {
2226             if ($("#sqlqueryresults").length != 0) {
2227                 $("#sqlqueryresults").remove();
2228             }
2229             if ($("#result_query").length != 0) {
2230                 $("#result_query").remove();
2231             }
2232             if (data.success == true) {
2233                 PMA_ajaxShowMessage(data.message);
2234                 $("<div id='sqlqueryresults'></div>").insertAfter("#floating_menubar");
2235                 $("#sqlqueryresults").html(data.sql_query);
2236                 $("#result_query .notice").remove();
2237                 $("#result_query").prepend((data.message));
2238             } else {
2239                 var $temp_div = $("<div id='temp_div'></div>")
2240                 $temp_div.html(data.error);
2241                 var $error = $temp_div.find("code").addClass("error");
2242                 PMA_ajaxShowMessage($error, false);
2243             }
2244         }) // end $.post()
2245     });//end of alterTableOrderby ajax submit
2247     /**
2248      *Ajax action for submitting the "Copy table"
2249     **/
2250     $("#copyTable.ajax input[name='submit_copy']").live('click', function(event) {
2251         event.preventDefault();
2252         var $form = $("#copyTable");
2253         if($form.find("input[name='switch_to_new']").attr('checked')) {
2254             $form.append('<input type="hidden" name="submit_copy" value="Go" />');
2255             $form.removeClass('ajax');
2256             $form.find("#ajax_request_hidden").remove();
2257             $form.submit();
2258         } else {
2259             PMA_prepareForAjaxRequest($form);
2260             /*variables which stores the common attributes*/
2261             $.post($form.attr('action'), $form.serialize()+"&submit_copy=Go", function(data) {
2262                 if ($("#sqlqueryresults").length != 0) {
2263                     $("#sqlqueryresults").remove();
2264                 }
2265                 if ($("#result_query").length != 0) {
2266                     $("#result_query").remove();
2267                 }
2268                 if (data.success == true) {
2269                     PMA_ajaxShowMessage(data.message);
2270                     $("<div id='sqlqueryresults'></div>").insertAfter("#floating_menubar");
2271                     $("#sqlqueryresults").html(data.sql_query);
2272                     $("#result_query .notice").remove();
2273                     $("#result_query").prepend((data.message));
2274                     $("#copyTable").find("select[name='target_db'] option").filterByValue(data.db).attr('selected', 'selected');
2276                     //Refresh navigation frame when the table is coppied
2277                     if (window.parent && window.parent.frame_navigation) {
2278                         window.parent.frame_navigation.location.reload();
2279                     }
2280                 } else {
2281                     var $temp_div = $("<div id='temp_div'></div>");
2282                     $temp_div.html(data.error);
2283                     var $error = $temp_div.find("code").addClass("error");
2284                     PMA_ajaxShowMessage($error, false);
2285                 }
2286             }) // end $.post()
2287         }
2288     });//end of copyTable ajax submit
2290     /**
2291      *Ajax events for actions in the "Table maintenance"
2292     **/
2293     $("#tbl_maintenance.ajax li a.maintain_action").live('click', function(event) {
2294         event.preventDefault();
2295         var $link = $(this);
2296         var href = $link.attr("href");
2297         href = href.split('?');
2298         if ($("#sqlqueryresults").length != 0) {
2299             $("#sqlqueryresults").remove();
2300         }
2301         if ($("#result_query").length != 0) {
2302             $("#result_query").remove();
2303         }
2304         //variables which stores the common attributes
2305         $.post(href[0], href[1]+"&ajax_request=true", function(data) {
2306             if (data.success == undefined) {
2307                 var $temp_div = $("<div id='temp_div'></div>");
2308                 $temp_div.html(data);
2309                 var $success = $temp_div.find("#result_query .success");
2310                 PMA_ajaxShowMessage($success);
2311                 $("<div id='sqlqueryresults' class='ajax'></div>").insertAfter("#floating_menubar");
2312                 $("#sqlqueryresults").html(data);
2313                 PMA_init_slider();
2314                 $("#sqlqueryresults").children("fieldset").remove();
2315             } else if (data.success == true ) {
2316                 PMA_ajaxShowMessage(data.message);
2317                 $("<div id='sqlqueryresults' class='ajax'></div>").insertAfter("#floating_menubar");
2318                 $("#sqlqueryresults").html(data.sql_query);
2319             } else {
2320                 var $temp_div = $("<div id='temp_div'></div>");
2321                 $temp_div.html(data.error);
2322                 var $error = $temp_div.find("code").addClass("error");
2323                 PMA_ajaxShowMessage($error, false);
2324             }
2325         }) // end $.post()
2326     });//end of table maintanance ajax click
2328 }, 'top.frame_content'); //end $(document).ready for 'Table operations'
2332  * Attach Ajax event handlers for Drop Database. Moved here from db_structure.js
2333  * as it was also required on db_create.php
2335  * @uses    $.PMA_confirm()
2336  * @uses    PMA_ajaxShowMessage()
2337  * @uses    window.parent.refreshNavigation()
2338  * @uses    window.parent.refreshMain()
2339  * @see $cfg['AjaxEnable']
2340  */
2341 $(document).ready(function() {
2342     $("#drop_db_anchor").live('click', function(event) {
2343         event.preventDefault();
2345         //context is top.frame_content, so we need to use window.parent.db to access the db var
2346         /**
2347          * @var question    String containing the question to be asked for confirmation
2348          */
2349         var question = PMA_messages['strDropDatabaseStrongWarning'] + '\n' + PMA_messages['strDoYouReally'] + ' :\n' + 'DROP DATABASE ' + escapeHtml(window.parent.db);
2351         $(this).PMA_confirm(question, $(this).attr('href') ,function(url) {
2353             PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
2354             $.get(url, {'is_js_confirmed': '1', 'ajax_request': true}, function(data) {
2355                 //Database deleted successfully, refresh both the frames
2356                 window.parent.refreshNavigation();
2357                 window.parent.refreshMain();
2358             }) // end $.get()
2359         }); // end $.PMA_confirm()
2360     }); //end of Drop Database Ajax action
2361 }) // end of $(document).ready() for Drop Database
2364  * Attach Ajax event handlers for 'Create Database'.  Used wherever libraries/
2365  * display_create_database.lib.php is used, ie main.php and server_databases.php
2367  * @uses    PMA_ajaxShowMessage()
2368  * @see $cfg['AjaxEnable']
2369  */
2370 $(document).ready(function() {
2372     $('#create_database_form.ajax').live('submit', function(event) {
2373         event.preventDefault();
2375         $form = $(this);
2377         PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
2378         PMA_prepareForAjaxRequest($form);
2380         $.post($form.attr('action'), $form.serialize(), function(data) {
2381             if(data.success == true) {
2382                 PMA_ajaxShowMessage(data.message);
2384                 //Append database's row to table
2385                 $("#tabledatabases")
2386                 .find('tbody')
2387                 .append(data.new_db_string)
2388                 .PMA_sort_table('.name')
2389                 .find('#db_summary_row')
2390                 .appendTo('#tabledatabases tbody')
2391                 .removeClass('odd even');
2393                 var $databases_count_object = $('#databases_count');
2394                 var databases_count = parseInt($databases_count_object.text());
2395                 $databases_count_object.text(++databases_count);
2396                 //Refresh navigation frame as a new database has been added
2397                 if (window.parent && window.parent.frame_navigation) {
2398                     window.parent.frame_navigation.location.reload();
2399                 }
2400             }
2401             else {
2402                 PMA_ajaxShowMessage(data.error, false);
2403             }
2404         }) // end $.post()
2405     }) // end $().live()
2406 })  // end $(document).ready() for Create Database
2409  * Attach Ajax event handlers for 'Change Password' on main.php
2410  */
2411 $(document).ready(function() {
2413     /**
2414      * Attach Ajax event handler on the change password anchor
2415      * @see $cfg['AjaxEnable']
2416      */
2417     $('#change_password_anchor.dialog_active').live('click',function(event) {
2418         event.preventDefault();
2419         return false;
2420         });
2421     $('#change_password_anchor.ajax').live('click', function(event) {
2422         event.preventDefault();
2423         $(this).removeClass('ajax').addClass('dialog_active');
2424         /**
2425          * @var button_options  Object containing options to be passed to jQueryUI's dialog
2426          */
2427         var button_options = {};
2428         button_options[PMA_messages['strCancel']] = function() {$(this).dialog('close').remove();}
2429         $.get($(this).attr('href'), {'ajax_request': true}, function(data) {
2430             $('<div id="change_password_dialog"></div>')
2431             .dialog({
2432                 title: PMA_messages['strChangePassword'],
2433                 width: 600,
2434                 close: function(ev,ui) {$(this).remove();},
2435                 buttons : button_options,
2436                 beforeClose: function(ev,ui){ $('#change_password_anchor.dialog_active').removeClass('dialog_active').addClass('ajax')}
2437             })
2438             .append(data);
2439             displayPasswordGenerateButton();
2440         }) // end $.get()
2441     }) // end handler for change password anchor
2443     /**
2444      * Attach Ajax event handler for Change Password form submission
2445      *
2446      * @uses    PMA_ajaxShowMessage()
2447      * @see $cfg['AjaxEnable']
2448      */
2449     $("#change_password_form.ajax").find('input[name=change_pw]').live('click', function(event) {
2450         event.preventDefault();
2452         /**
2453          * @var the_form    Object referring to the change password form
2454          */
2455         var the_form = $("#change_password_form");
2457         /**
2458          * @var this_value  String containing the value of the submit button.
2459          * Need to append this for the change password form on Server Privileges
2460          * page to work
2461          */
2462         var this_value = $(this).val();
2464         var $msgbox = PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
2465         $(the_form).append('<input type="hidden" name="ajax_request" value="true" />');
2467         $.post($(the_form).attr('action'), $(the_form).serialize() + '&change_pw='+ this_value, function(data) {
2468             if(data.success == true) {
2469                 $("#floating_menubar").after(data.sql_query);
2470                 $("#change_password_dialog").hide().remove();
2471                 $("#edit_user_dialog").dialog("close").remove();
2472                 $('#change_password_anchor.dialog_active').removeClass('dialog_active').addClass('ajax');
2473                 PMA_ajaxRemoveMessage($msgbox);
2474             }
2475             else {
2476                 PMA_ajaxShowMessage(data.error, false);
2477             }
2478         }) // end $.post()
2479     }) // end handler for Change Password form submission
2480 }) // end $(document).ready() for Change Password
2483  * Toggle the hiding/showing of the "Open in ENUM/SET editor" message when
2484  * the page loads and when the selected data type changes
2485  */
2486 $(document).ready(function() {
2487     // is called here for normal page loads and also when opening
2488     // the Create table dialog
2489     PMA_verifyColumnsProperties();
2490     //
2491     // needs live() to work also in the Create Table dialog
2492     $("select[class='column_type']").live('change', function() {
2493         PMA_showNoticeForEnum($(this));
2494     });
2495     $(".default_type").live('change', function() {
2496         PMA_hideShowDefaultValue($(this));
2497     });
2500 function PMA_verifyColumnsProperties()
2502     $("select[class='column_type']").each(function() {
2503         PMA_showNoticeForEnum($(this));
2504     });
2505     $(".default_type").each(function() {
2506         PMA_hideShowDefaultValue($(this));
2507     });
2511  * Hides/shows the default value input field, depending on the default type
2512  */
2513 function PMA_hideShowDefaultValue($default_type)
2515     if ($default_type.val() == 'USER_DEFINED') {
2516         $default_type.siblings('.default_value').show().focus();
2517     } else {
2518         $default_type.siblings('.default_value').hide();
2519     }
2523  * @var $enum_editor_dialog An object that points to the jQuery
2524  *                          dialog of the ENUM/SET editor
2525  */
2526 var $enum_editor_dialog = null;
2528  * Opens the ENUM/SET editor and controls its functions
2529  */
2530 $(document).ready(function() {
2531     $("a.open_enum_editor").live('click', function() {
2532         // Get the name of the column that is being edited
2533         var colname = $(this).closest('tr').find('input:first').val();
2534         // And use it to make up a title for the page
2535         if (colname.length < 1) {
2536             var title = PMA_messages['enum_newColumnVals'];
2537         } else {
2538             var title = PMA_messages['enum_columnVals'].replace(
2539                 /%s/,
2540                 '"' + decodeURIComponent(colname) + '"'
2541             );
2542         }
2543         // Get the values as a string
2544         var inputstring = $(this)
2545             .closest('td')
2546             .find("input")
2547             .val();
2548         // Escape html entities
2549         inputstring = $('<div/>')
2550             .text(inputstring)
2551             .html();
2552         // Parse the values, escaping quotes and
2553         // slashes on the fly, into an array
2554         //
2555         // There is a PHP port of the below parser in enum_editor.php
2556         // If you are fixing something here, you need to also update the PHP port.
2557         var values = [];
2558         var in_string = false;
2559         var curr, next, buffer = '';
2560         for (var i=0; i<inputstring.length; i++) {
2561             curr = inputstring.charAt(i);
2562             next = i == inputstring.length ? '' : inputstring.charAt(i+1);
2563             if (! in_string && curr == "'") {
2564                 in_string = true;
2565             } else if (in_string && curr == "\\" && next == "\\") {
2566                 buffer += "&#92;";
2567                 i++;
2568             } else if (in_string && next == "'" && (curr == "'" || curr == "\\")) {
2569                 buffer += "&#39;";
2570                 i++;
2571             } else if (in_string && curr == "'") {
2572                 in_string = false;
2573                 values.push(buffer);
2574                 buffer = '';
2575             } else if (in_string) {
2576                  buffer += curr;
2577             }
2578         }
2579         if (buffer.length > 0) {
2580             // The leftovers in the buffer are the last value (if any)
2581             values.push(buffer);
2582         }
2583         var fields = '';
2584         // If there are no values, maybe the user is about to make a
2585         // new list so we add a few for him/her to get started with.
2586         if (values.length == 0) {
2587             values.push('','','','');
2588         }
2589         // Add the parsed values to the editor
2590         var drop_icon = PMA_getImage('b_drop.png');
2591         for (var i=0; i<values.length; i++) {
2592             fields += "<tr><td>"
2593                    + "<input type='text' value='" + values[i] + "'/>"
2594                    + "</td><td class='drop'>"
2595                    + drop_icon
2596                    + "</td></tr>";
2597         }
2598         /**
2599          * @var dialog HTML code for the ENUM/SET dialog
2600          */
2601         var dialog = "<div id='enum_editor'>"
2602                    + "<fieldset>"
2603                    + "<legend>" + title + "</legend>"
2604                    + "<p>" + PMA_getImage('s_notice.png')
2605                    + PMA_messages['enum_hint'] + "</p>"
2606                    + "<table class='values'>" + fields + "</table>"
2607                    + "</fieldset><fieldset class='tblFooters'>"
2608                    + "<table class='add'><tr><td>"
2609                    + "<div class='slider'></div>"
2610                    + "</td><td>"
2611                    + "<form><div><input type='submit' class='add_value' value='"
2612                    + PMA_messages['enum_addValue'].replace(/%d/, 1)
2613                    + "'/></div></form>"
2614                    + "</td></tr></table>"
2615                    + "<input type='hidden' value='" // So we know which column's data is being edited
2616                    + $(this).closest('td').find("input").attr("id")
2617                    + "' />"
2618                    + "</fieldset>";
2619                    + "</div>";
2620         /**
2621          * @var  Defines functions to be called when the buttons in
2622          * the buttonOptions jQuery dialog bar are pressed
2623          */
2624         var buttonOptions = {};
2625         buttonOptions[PMA_messages['strGo']] = function () {
2626             // When the submit button is clicked,
2627             // put the data back into the original form
2628             var value_array = new Array();
2629             $(this).find(".values input").each(function(index, elm) {
2630                 var val = elm.value.replace(/\\/g, '\\\\').replace(/'/g, "''");
2631                 value_array.push("'" + val + "'");
2632             });
2633             // get the Length/Values text field where this value belongs
2634             var values_id = $(this).find("input[type='hidden']").attr("value");
2635             $("input[id='" + values_id + "']").attr("value", value_array.join(","));
2636             $(this).dialog("close");
2637         };
2638         buttonOptions[PMA_messages['strClose']] = function () {
2639             $(this).dialog("close");
2640         };
2641         // Show the dialog
2642         var width = parseInt(
2643             (parseInt($('html').css('font-size'), 10)/13)*340,
2644             10
2645         );
2646         if (! width) {
2647             width = 340;
2648         }
2649         $enum_editor_dialog = $(dialog).dialog({
2650             minWidth: width,
2651             modal: true,
2652             title: PMA_messages['enum_editor'],
2653             buttons: buttonOptions,
2654             open: function() {
2655                 // Focus the "Go" button after opening the dialog
2656                 $(this).closest('.ui-dialog').find('.ui-dialog-buttonpane button:first').focus();
2657             },
2658             close: function() {
2659                 $(this).remove();
2660             }
2661         });
2662         // slider for choosing how many fields to add
2663         $enum_editor_dialog.find(".slider").slider({
2664             animate: true,
2665             range: "min",
2666             value: 1,
2667             min: 1,
2668             max: 9,
2669             slide: function( event, ui ) {
2670                 $(this).closest('table').find('input[type=submit]').val(
2671                     PMA_messages['enum_addValue'].replace(/%d/, ui.value)
2672                 );
2673             }
2674         });
2675         // Focus the slider, otherwise it looks nearly transparent
2676         $('.ui-slider-handle').addClass('ui-state-focus');
2677         return false;
2678     });
2680     // When "add a new value" is clicked, append an empty text field
2681     $("input.add_value").live('click', function(e) {
2682         e.preventDefault();
2683         var num_new_rows = $enum_editor_dialog.find("div.slider").slider('value');
2684         while (num_new_rows--) {
2685             $enum_editor_dialog.find('.values')
2686                 .append(
2687                     "<tr style='display: none;'><td>"
2688                   + "<input type='text' />"
2689                   + "</td><td class='drop'>"
2690                   + PMA_getImage('b_drop.png')
2691                   + "</td></tr>"
2692                 )
2693                 .find('tr:last')
2694                 .show('fast');
2695         }
2696     });
2698     // Removes the specified row from the enum editor
2699     $("#enum_editor td.drop").live('click', function() {
2700         $(this).closest('tr').hide('fast', function () {
2701             $(this).remove();
2702         });
2703     });
2707  * Hides certain table structure actions, replacing them
2708  * with the word "More". They are displayed in a dropdown
2709  * menu when the user hovers over the word "More."
2710  */
2711 $(document).ready(function() {
2712     displayMoreTableOpts();
2715 function displayMoreTableOpts()
2717     // Remove the actions from the table cells (they are available by default for JavaScript-disabled browsers)
2718     // if the table is not a view or information_schema (otherwise there is only one action to hide and there's no point)
2719     if($("input[type='hidden'][name='table_type']").val() == "table") {
2720         var $table = $("table[id='tablestructure']");
2721         $table.find("td[class='browse']").remove();
2722         $table.find("td[class='primary']").remove();
2723         $table.find("td[class='unique']").remove();
2724         $table.find("td[class='index']").remove();
2725         $table.find("td[class='fulltext']").remove();
2726         $table.find("td[class='spatial']").remove();
2727         $table.find("th[class='action']").attr("colspan", 3);
2729         // Display the "more" text
2730         $table.find("td[class='more_opts']").show();
2732         // Position the dropdown
2733         $(".structure_actions_dropdown").each(function() {
2734             // Optimize DOM querying
2735             var $this_dropdown = $(this);
2736              // The top offset must be set for IE even if it didn't change
2737             var cell_right_edge_offset = $this_dropdown.parent().position().left + $this_dropdown.parent().innerWidth();
2738             var left_offset = cell_right_edge_offset - $this_dropdown.innerWidth();
2739             var top_offset = $this_dropdown.parent().position().top + $this_dropdown.parent().innerHeight();
2740             $this_dropdown.offset({ top: top_offset, left: left_offset });
2741         });
2743         // A hack for IE6 to prevent the after_field select element from being displayed on top of the dropdown by
2744         // positioning an iframe directly on top of it
2745         var $after_field = $("select[name='after_field']");
2746         $("iframe[class='IE_hack']")
2747             .width($after_field.width())
2748             .height($after_field.height())
2749             .offset({
2750                 top: $after_field.offset().top,
2751                 left: $after_field.offset().left
2752             });
2754         // When "more" is hovered over, show the hidden actions
2755         $table.find("td[class='more_opts']")
2756             .mouseenter(function() {
2757                 if($.browser.msie && $.browser.version == "6.0") {
2758                     $("iframe[class='IE_hack']")
2759                         .show()
2760                         .width($after_field.width()+4)
2761                         .height($after_field.height()+4)
2762                         .offset({
2763                             top: $after_field.offset().top,
2764                             left: $after_field.offset().left
2765                         });
2766                 }
2767                 $(".structure_actions_dropdown").hide(); // Hide all the other ones that may be open
2768                 $(this).children(".structure_actions_dropdown").show();
2769                 // Need to do this again for IE otherwise the offset is wrong
2770                 if($.browser.msie) {
2771                     var left_offset_IE = $(this).offset().left + $(this).innerWidth() - $(this).children(".structure_actions_dropdown").innerWidth();
2772                     var top_offset_IE = $(this).offset().top + $(this).innerHeight();
2773                     $(this).children(".structure_actions_dropdown").offset({
2774                         top: top_offset_IE,
2775                         left: left_offset_IE });
2776                 }
2777             })
2778             .mouseleave(function() {
2779                 $(this).children(".structure_actions_dropdown").hide();
2780                 if($.browser.msie && $.browser.version == "6.0") {
2781                     $("iframe[class='IE_hack']").hide();
2782                 }
2783             });
2784     }
2787 $(document).ready(function(){
2788     PMA_convertFootnotesToTooltips();
2792  * Ensures indexes names are valid according to their type and, for a primary
2793  * key, lock index name to 'PRIMARY'
2794  * @param   string   form_id  Variable which parses the form name as
2795  *                            the input
2796  * @return  boolean  false    if there is no index form, true else
2797  */
2798 function checkIndexName(form_id)
2800     if ($("#"+form_id).length == 0) {
2801         return false;
2802     }
2804     // Gets the elements pointers
2805     var $the_idx_name = $("#input_index_name");
2806     var $the_idx_type = $("#select_index_type");
2808     // Index is a primary key
2809     if ($the_idx_type.find("option:selected").attr("value") == 'PRIMARY') {
2810         $the_idx_name.attr("value", 'PRIMARY');
2811         $the_idx_name.attr("disabled", true);
2812     }
2814     // Other cases
2815     else {
2816         if ($the_idx_name.attr("value") == 'PRIMARY') {
2817             $the_idx_name.attr("value",  '');
2818         }
2819         $the_idx_name.attr("disabled", false);
2820     }
2822     return true;
2823 } // end of the 'checkIndexName()' function
2826  * function to convert the footnotes to tooltips
2828  * @param   jquery-Object   $div    a div jquery object which specifies the
2829  *                                  domain for searching footnootes. If we
2830  *                                  ommit this parameter the function searches
2831  *                                  the footnotes in the whole body
2832  **/
2833 function PMA_convertFootnotesToTooltips($div)
2835     // Hide the footnotes from the footer (which are displayed for
2836     // JavaScript-disabled browsers) since the tooltip is sufficient
2838     if ($div == undefined || ! $div instanceof jQuery || $div.length == 0) {
2839         $div = $("body");
2840     }
2842     $footnotes = $div.find(".footnotes");
2844     $footnotes.hide();
2845     $footnotes.find('span').each(function() {
2846         $(this).children("sup").remove();
2847     });
2848     // The border and padding must be removed otherwise a thin yellow box remains visible
2849     $footnotes.css("border", "none");
2850     $footnotes.css("padding", "0px");
2852     // Replace the superscripts with the help icon
2853     $div.find("sup.footnotemarker").hide();
2854     $div.find("img.footnotemarker").show();
2856     $div.find("img.footnotemarker").each(function() {
2857         var img_class = $(this).attr("class");
2858         /** img contains two classes, as example "footnotemarker footnote_1".
2859          *  We split it by second class and take it for the id of span
2860         */
2861         img_class = img_class.split(" ");
2862         for (i = 0; i < img_class.length; i++) {
2863             if (img_class[i].split("_")[0] == "footnote") {
2864                 var span_id = img_class[i].split("_")[1];
2865             }
2866         }
2867         /**
2868          * Now we get the #id of the span with span_id variable. As an example if we
2869          * initially get the img class as "footnotemarker footnote_2", now we get
2870          * #2 as the span_id. Using that we can find footnote_2 in footnotes.
2871          * */
2872         var tooltip_text = $footnotes.find("span[id='footnote_" + span_id + "']").html();
2873         $(this).qtip({
2874             content: tooltip_text,
2875             show: { delay: 0 },
2876             hide: { delay: 1000 },
2877             style: { background: '#ffffcc' }
2878         });
2879     });
2883  * This function handles the resizing of the content frame
2884  * and adjusts the top menu according to the new size of the frame
2885  */
2886 function menuResize()
2888     var $cnt = $('#topmenu');
2889     var wmax = $cnt.innerWidth() - 5; // 5 px margin for jumping menu in Chrome
2890     var $submenu = $cnt.find('.submenu');
2891     var submenu_w = $submenu.outerWidth(true);
2892     var $submenu_ul = $submenu.find('ul');
2893     var $li = $cnt.find('> li');
2894     var $li2 = $submenu_ul.find('li');
2895     var more_shown = $li2.length > 0;
2897     // Calculate the total width used by all the shown tabs
2898     var total_len = more_shown ? submenu_w : 0;
2899     for (var i = 0; i < $li.length-1; i++) {
2900         total_len += $($li[i]).outerWidth(true);
2901     }
2903     // Now hide menu elements that don't fit into the menubar
2904     var i = $li.length-1;
2905     var hidden = false; // Whether we have hidden any tabs
2906     while (total_len >= wmax && --i >= 0) { // Process the tabs backwards
2907         hidden = true;
2908         var el = $($li[i]);
2909         var el_width = el.outerWidth(true);
2910         el.data('width', el_width);
2911         if (! more_shown) {
2912             total_len -= el_width;
2913             el.prependTo($submenu_ul);
2914             total_len += submenu_w;
2915             more_shown = true;
2916         } else {
2917             total_len -= el_width;
2918             el.prependTo($submenu_ul);
2919         }
2920     }
2922     // If we didn't hide any tabs, then there might be some space to show some
2923     if (! hidden) {
2924         // Show menu elements that do fit into the menubar
2925         for (var i = 0; i < $li2.length; i++) {
2926             total_len += $($li2[i]).data('width');
2927             // item fits or (it is the last item
2928             // and it would fit if More got removed)
2929             if (total_len < wmax
2930                 || (i == $li2.length - 1 && total_len - submenu_w < wmax)
2931             ) {
2932                 $($li2[i]).insertBefore($submenu);
2933             } else {
2934                 break;
2935             }
2936         }
2937     }
2939     // Show/hide the "More" tab as needed
2940     if ($submenu_ul.find('li').length > 0) {
2941         $submenu.addClass('shown');
2942     } else {
2943         $submenu.removeClass('shown');
2944     }
2946     if ($cnt.find('> li').length == 1) {
2947         // If there is only the "More" tab left, then we need
2948         // to align the submenu to the left edge of the tab
2949         $submenu_ul.removeClass().addClass('only');
2950     } else {
2951         // Otherwise we align the submenu to the right edge of the tab
2952         $submenu_ul.removeClass().addClass('notonly');
2953     }
2955     if ($submenu.find('.tabactive').length) {
2956         $submenu.addClass('active').find('> a').removeClass('tab').addClass('tabactive');
2957     } else {
2958         $submenu.removeClass('active').find('> a').addClass('tab').removeClass('tabactive');
2959     }
2962 $(function() {
2963     var topmenu = $('#topmenu');
2964     if (topmenu.length == 0) {
2965         return;
2966     }
2967     // create submenu container
2968     var link = $('<a />', {href: '#', 'class': 'tab'})
2969         .text(PMA_messages['strMore'])
2970         .click(function(e) {
2971             e.preventDefault();
2972         });
2973     var img = topmenu.find('li:first-child img');
2974     if (img.length) {
2975         $(PMA_getImage('b_more.png').toString()).prependTo(link);
2976     }
2977     var submenu = $('<li />', {'class': 'submenu'})
2978         .append(link)
2979         .append($('<ul />'))
2980         .mouseenter(function() {
2981             if ($(this).find('ul .tabactive').length == 0) {
2982                 $(this).addClass('submenuhover').find('> a').addClass('tabactive');
2983             }
2984         })
2985         .mouseleave(function() {
2986             if ($(this).find('ul .tabactive').length == 0) {
2987                 $(this).removeClass('submenuhover').find('> a').removeClass('tabactive');
2988             }
2989         });
2990     topmenu.append(submenu);
2992     // populate submenu and register resize event
2993     menuResize();
2994     $(window).resize(menuResize);
2998  * Get the row number from the classlist (for example, row_1)
2999  */
3000 function PMA_getRowNumber(classlist)
3002     return parseInt(classlist.split(/\s+row_/)[1]);
3006  * Changes status of slider
3007  */
3008 function PMA_set_status_label($element)
3010     var text = $element.css('display') == 'none'
3011         ? '+ '
3012         : '- ';
3013     $element.closest('.slide-wrapper').prev().find('span').text(text);
3017  * Initializes slider effect.
3018  */
3019 function PMA_init_slider()
3021     $('.pma_auto_slider').each(function() {
3022         var $this = $(this);
3024         if ($this.hasClass('slider_init_done')) {
3025             return;
3026         }
3027         $this.addClass('slider_init_done');
3029         var $wrapper = $('<div>', {'class': 'slide-wrapper'});
3030         $wrapper.toggle($this.is(':visible'));
3031         $('<a>', {href: '#'+this.id})
3032             .text(this.title)
3033             .prepend($('<span>'))
3034             .insertBefore($this)
3035             .click(function() {
3036                 var $wrapper = $this.closest('.slide-wrapper');
3037                 var visible = $this.is(':visible');
3038                 if (!visible) {
3039                     $wrapper.show();
3040                 }
3041                 $this[visible ? 'hide' : 'show']('blind', function() {
3042                     $wrapper.toggle(!visible);
3043                     PMA_set_status_label($this);
3044                 });
3045                 return false;
3046             });
3047         $this.wrap($wrapper);
3048         PMA_set_status_label($this);
3049     });
3053  * var  toggleButton  This is a function that creates a toggle
3054  *                    sliding button given a jQuery reference
3055  *                    to the correct DOM element
3056  */
3057 var toggleButton = function ($obj) {
3058     // In rtl mode the toggle switch is flipped horizontally
3059     // so we need to take that into account
3060     if ($('.text_direction', $obj).text() == 'ltr') {
3061         var right = 'right';
3062     } else {
3063         var right = 'left';
3064     }
3065     /**
3066      *  var  h  Height of the button, used to scale the
3067      *          background image and position the layers
3068      */
3069     var h = $obj.height();
3070     $('img', $obj).height(h);
3071     $('table', $obj).css('bottom', h-1);
3072     /**
3073      *  var  on   Width of the "ON" part of the toggle switch
3074      *  var  off  Width of the "OFF" part of the toggle switch
3075      */
3076     var on  = $('.toggleOn', $obj).width();
3077     var off = $('.toggleOff', $obj).width();
3078     // Make the "ON" and "OFF" parts of the switch the same size
3079     // + 2 pixels to avoid overflowed
3080     $('.toggleOn > div', $obj).width(Math.max(on, off) + 2);
3081     $('.toggleOff > div', $obj).width(Math.max(on, off) + 2);
3082     /**
3083      *  var  w  Width of the central part of the switch
3084      */
3085     var w = parseInt(($('img', $obj).height() / 16) * 22, 10);
3086     // Resize the central part of the switch on the top
3087     // layer to match the background
3088     $('table td:nth-child(2) > div', $obj).width(w);
3089     /**
3090      *  var  imgw    Width of the background image
3091      *  var  tblw    Width of the foreground layer
3092      *  var  offset  By how many pixels to move the background
3093      *               image, so that it matches the top layer
3094      */
3095     var imgw = $('img', $obj).width();
3096     var tblw = $('table', $obj).width();
3097     var offset = parseInt(((imgw - tblw) / 2), 10);
3098     // Move the background to match the layout of the top layer
3099     $obj.find('img').css(right, offset);
3100     /**
3101      *  var  offw    Outer width of the "ON" part of the toggle switch
3102      *  var  btnw    Outer width of the central part of the switch
3103      */
3104     var offw = $('.toggleOff', $obj).outerWidth();
3105     var btnw = $('table td:nth-child(2)', $obj).outerWidth();
3106     // Resize the main div so that exactly one side of
3107     // the switch plus the central part fit into it.
3108     $obj.width(offw + btnw + 2);
3109     /**
3110      *  var  move  How many pixels to move the
3111      *             switch by when toggling
3112      */
3113     var move = $('.toggleOff', $obj).outerWidth();
3114     // If the switch is initialized to the
3115     // OFF state we need to move it now.
3116     if ($('.container', $obj).hasClass('off')) {
3117         if (right == 'right') {
3118             $('table, img', $obj).animate({'left': '-=' + move + 'px'}, 0);
3119         } else {
3120             $('table, img', $obj).animate({'left': '+=' + move + 'px'}, 0);
3121         }
3122     }
3123     // Attach an 'onclick' event to the switch
3124     $('.container', $obj).click(function () {
3125         if ($(this).hasClass('isActive')) {
3126             return false;
3127         } else {
3128             $(this).addClass('isActive');
3129         }
3130         var $msg = PMA_ajaxShowMessage();
3131         var $container = $(this);
3132         var callback = $('.callback', this).text();
3133         // Perform the actual toggle
3134         if ($(this).hasClass('on')) {
3135             if (right == 'right') {
3136                 var operator = '-=';
3137             } else {
3138                 var operator = '+=';
3139             }
3140             var url = $(this).find('.toggleOff > span').text();
3141             var removeClass = 'on';
3142             var addClass = 'off';
3143         } else {
3144             if (right == 'right') {
3145                 var operator = '+=';
3146             } else {
3147                 var operator = '-=';
3148             }
3149             var url = $(this).find('.toggleOn > span').text();
3150             var removeClass = 'off';
3151             var addClass = 'on';
3152         }
3153         $.post(url, {'ajax_request': true}, function(data) {
3154             if(data.success == true) {
3155                 PMA_ajaxRemoveMessage($msg);
3156                 $container
3157                 .removeClass(removeClass)
3158                 .addClass(addClass)
3159                 .animate({'left': operator + move + 'px'}, function () {
3160                     $container.removeClass('isActive');
3161                 });
3162                 eval(callback);
3163             } else {
3164                 PMA_ajaxShowMessage(data.error, false);
3165                 $container.removeClass('isActive');
3166             }
3167         });
3168     });
3172  * Initialise all toggle buttons
3173  */
3174 $(window).load(function () {
3175     $('.toggleAjax').each(function () {
3176         $(this)
3177         .show()
3178         .find('.toggleButton')
3179         toggleButton($(this));
3180     });
3184  * Vertical pointer
3185  */
3186 $(document).ready(function() {
3187     $('.vpointer').live('hover',
3188         //handlerInOut
3189         function(e) {
3190             var $this_td = $(this);
3191             var row_num = PMA_getRowNumber($this_td.attr('class'));
3192             // for all td of the same vertical row, toggle hover
3193             $('.vpointer').filter('.row_' + row_num).toggleClass('hover');
3194         }
3195         );
3196 }) // end of $(document).ready() for vertical pointer
3198 $(document).ready(function() {
3199     /**
3200      * Vertical marker
3201      */
3202     $('.vmarker').live('click', function(e) {
3203         // do not trigger when clicked on anchor
3204         if ($(e.target).is('a, img, a *')) {
3205             return;
3206         }
3208         var $this_td = $(this);
3209         var row_num = PMA_getRowNumber($this_td.attr('class'));
3211         // XXX: FF fires two click events for <label> (label and checkbox), so we need to handle this differently
3212         var $tr = $(this);
3213         var $checkbox = $('.vmarker').filter('.row_' + row_num + ':first').find(':checkbox');
3214         if ($checkbox.length) {
3215             // checkbox in a row, add or remove class depending on checkbox state
3216             var checked = $checkbox.attr('checked');
3217             if (!$(e.target).is(':checkbox, label')) {
3218                 checked = !checked;
3219                 $checkbox.attr('checked', checked);
3220             }
3221             // for all td of the same vertical row, toggle the marked class
3222             if (checked) {
3223                 $('.vmarker').filter('.row_' + row_num).addClass('marked');
3224             } else {
3225                 $('.vmarker').filter('.row_' + row_num).removeClass('marked');
3226             }
3227         } else {
3228             // normaln data table, just toggle class
3229             $('.vmarker').filter('.row_' + row_num).toggleClass('marked');
3230         }
3231     });
3233     /**
3234      * Reveal visual builder anchor
3235      */
3237     $('#visual_builder_anchor').show();
3239     /**
3240      * Page selector in db Structure (non-AJAX)
3241      */
3242     $('#tableslistcontainer').find('#pageselector').live('change', function() {
3243         $(this).parent("form").submit();
3244     });
3246     /**
3247      * Page selector in navi panel (non-AJAX)
3248      */
3249     $('#navidbpageselector').find('#pageselector').live('change', function() {
3250         $(this).parent("form").submit();
3251     });
3253     /**
3254      * Page selector in browse_foreigners windows (non-AJAX)
3255      */
3256     $('#body_browse_foreigners').find('#pageselector').live('change', function() {
3257         $(this).closest("form").submit();
3258     });
3260     /**
3261      * Load version information asynchronously.
3262      */
3263     if ($('.jsversioncheck').length > 0) {
3264         $.getScript('http://www.phpmyadmin.net/home_page/version.js', PMA_current_version);
3265     }
3267     /**
3268      * Slider effect.
3269      */
3270     PMA_init_slider();
3272     /**
3273      * Enables the text generated by PMA_linkOrButton() to be clickable
3274      */
3275     $('a[class~="formLinkSubmit"]').live('click',function(e) {
3277         if($(this).attr('href').indexOf('=') != -1) {
3278             var data = $(this).attr('href').substr($(this).attr('href').indexOf('#')+1).split('=',2);
3279             $(this).parents('form').append('<input type="hidden" name="' + data[0] + '" value="' + data[1] + '"/>');
3280         }
3281         $(this).parents('form').submit();
3282         return false;
3283     });
3285     $('#update_recent_tables').ready(function() {
3286         if (window.parent.frame_navigation != undefined
3287             && window.parent.frame_navigation.PMA_reloadRecentTable != undefined)
3288         {
3289             window.parent.frame_navigation.PMA_reloadRecentTable();
3290         }
3291     });
3293 }) // end of $(document).ready()
3296  * Creates a message inside an object with a sliding effect
3298  * @param   msg    A string containing the text to display
3299  * @param   $obj   a jQuery object containing the reference
3300  *                 to the element where to put the message
3301  *                 This is optional, if no element is
3302  *                 provided, one will be created below the
3303  *                 navigation links at the top of the page
3305  * @return  bool   True on success, false on failure
3306  */
3307 function PMA_slidingMessage(msg, $obj)
3309     if (msg == undefined || msg.length == 0) {
3310         // Don't show an empty message
3311         return false;
3312     }
3313     if ($obj == undefined || ! $obj instanceof jQuery || $obj.length == 0) {
3314         // If the second argument was not supplied,
3315         // we might have to create a new DOM node.
3316         if ($('#PMA_slidingMessage').length == 0) {
3317             $('#floating_menubar')
3318             .after('<span id="PMA_slidingMessage" '
3319                  + 'style="display: inline-block;"></span>');
3320         }
3321         $obj = $('#PMA_slidingMessage');
3322     }
3323     if ($obj.has('div').length > 0) {
3324         // If there already is a message inside the
3325         // target object, we must get rid of it
3326         $obj
3327         .find('div')
3328         .first()
3329         .fadeOut(function () {
3330             $obj
3331             .children()
3332             .remove();
3333             $obj
3334             .append('<div style="display: none;">' + msg + '</div>')
3335             .animate({
3336                 height: $obj.find('div').first().height()
3337             })
3338             .find('div')
3339             .first()
3340             .fadeIn();
3341         });
3342     } else {
3343         // Object does not already have a message
3344         // inside it, so we simply slide it down
3345         var h = $obj
3346                 .width('100%')
3347                 .html('<div style="display: none;">' + msg + '</div>')
3348                 .find('div')
3349                 .first()
3350                 .height();
3351         $obj
3352         .find('div')
3353         .first()
3354         .css('height', 0)
3355         .show()
3356         .animate({
3357                 height: h
3358             }, function() {
3359             // Set the height of the parent
3360             // to the height of the child
3361             $obj
3362             .height(
3363                 $obj
3364                 .find('div')
3365                 .first()
3366                 .height()
3367             );
3368         });
3369     }
3370     return true;
3371 } // end PMA_slidingMessage()
3374  * Attach Ajax event handlers for Drop Table.
3376  * @uses    $.PMA_confirm()
3377  * @uses    PMA_ajaxShowMessage()
3378  * @uses    window.parent.refreshNavigation()
3379  * @uses    window.parent.refreshMain()
3380  * @see $cfg['AjaxEnable']
3381  */
3382 $(document).ready(function() {
3383     $("#drop_tbl_anchor").live('click', function(event) {
3384         event.preventDefault();
3386         //context is top.frame_content, so we need to use window.parent.table to access the table var
3387         /**
3388          * @var question    String containing the question to be asked for confirmation
3389          */
3390         var question = PMA_messages['strDropTableStrongWarning'] + '\n' + PMA_messages['strDoYouReally'] + ' :\n' + 'DROP TABLE ' + window.parent.table;
3392         $(this).PMA_confirm(question, $(this).attr('href') ,function(url) {
3394             PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
3395             $.get(url, {'is_js_confirmed': '1', 'ajax_request': true}, function(data) {
3396                 //Database deleted successfully, refresh both the frames
3397                 window.parent.refreshNavigation();
3398                 window.parent.refreshMain();
3399             }) // end $.get()
3400         }); // end $.PMA_confirm()
3401     }); //end of Drop Table Ajax action
3402 }) // end of $(document).ready() for Drop Table
3405  * Attach Ajax event handlers for Truncate Table.
3407  * @uses    $.PMA_confirm()
3408  * @uses    PMA_ajaxShowMessage()
3409  * @uses    window.parent.refreshNavigation()
3410  * @uses    window.parent.refreshMain()
3411  * @see $cfg['AjaxEnable']
3412  */
3413 $(document).ready(function() {
3414     $("#truncate_tbl_anchor.ajax").live('click', function(event) {
3415         event.preventDefault();
3417       //context is top.frame_content, so we need to use window.parent.table to access the table var
3418         /**
3419          * @var question    String containing the question to be asked for confirmation
3420          */
3421         var question = PMA_messages['strTruncateTableStrongWarning'] + '\n' + PMA_messages['strDoYouReally'] + ' :\n' + 'TRUNCATE TABLE ' + window.parent.table;
3423         $(this).PMA_confirm(question, $(this).attr('href') ,function(url) {
3425             PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
3426             $.get(url, {'is_js_confirmed': '1', 'ajax_request': true}, function(data) {
3427                 if ($("#sqlqueryresults").length != 0) {
3428                     $("#sqlqueryresults").remove();
3429                 }
3430                 if ($("#result_query").length != 0) {
3431                     $("#result_query").remove();
3432                 }
3433                 if (data.success == true) {
3434                     PMA_ajaxShowMessage(data.message);
3435                     $("<div id='sqlqueryresults'></div>").insertAfter("#floating_menubar");
3436                     $("#sqlqueryresults").html(data.sql_query);
3437                 } else {
3438                     var $temp_div = $("<div id='temp_div'></div>")
3439                     $temp_div.html(data.error);
3440                     var $error = $temp_div.find("code").addClass("error");
3441                     PMA_ajaxShowMessage($error, false);
3442                 }
3443             }) // end $.get()
3444         }); // end $.PMA_confirm()
3445     }); //end of Truncate Table Ajax action
3446 }) // end of $(document).ready() for Truncate Table
3449  * Attach CodeMirror2 editor to SQL edit area.
3450  */
3451 $(document).ready(function() {
3452     var elm = $('#sqlquery');
3453     if (elm.length > 0 && typeof CodeMirror != 'undefined') {
3454         codemirror_editor = CodeMirror.fromTextArea(elm[0], {
3455             lineNumbers: true,
3456             matchBrackets: true,
3457             indentUnit: 4,
3458             mode: "text/x-mysql",
3459             lineWrapping: true
3460         });
3461     }
3465  * jQuery plugin to cancel selection in HTML code.
3466  */
3467 (function ($) {
3468     $.fn.noSelect = function (p) { //no select plugin by Paulo P.Marinas
3469         var prevent = (p == null) ? true : p;
3470         if (prevent) {
3471             return this.each(function () {
3472                 if ($.browser.msie || $.browser.safari) $(this).bind('selectstart', function () {
3473                     return false;
3474                 });
3475                 else if ($.browser.mozilla) {
3476                     $(this).css('MozUserSelect', 'none');
3477                     $('body').trigger('focus');
3478                 } else if ($.browser.opera) $(this).bind('mousedown', function () {
3479                     return false;
3480                 });
3481                 else $(this).attr('unselectable', 'on');
3482             });
3483         } else {
3484             return this.each(function () {
3485                 if ($.browser.msie || $.browser.safari) $(this).unbind('selectstart');
3486                 else if ($.browser.mozilla) $(this).css('MozUserSelect', 'inherit');
3487                 else if ($.browser.opera) $(this).unbind('mousedown');
3488                 else $(this).removeAttr('unselectable', 'on');
3489             });
3490         }
3491     }; //end noSelect
3492 })(jQuery);
3495  * jQuery plugin to correctly filter input fields by value, needed
3496  * because some nasty values may break selector syntax
3497  */
3498 (function ($) {
3499     $.fn.filterByValue = function (value) {
3500         return this.filter(function () {
3501             return $(this).val() === value
3502         });
3503     };
3504 })(jQuery);
3507  * Create default PMA tooltip for the element specified. The default appearance
3508  * can be overriden by specifying optional "options" parameter (see qTip options).
3509  */
3510 function PMA_createqTip($elements, content, options)
3512     if ($('#no_hint').length > 0) {
3513         return;
3514     }
3516     var o = {
3517         content: content,
3518         style: {
3519             classes: {
3520                 tooltip: 'normalqTip',
3521                 content: 'normalqTipContent'
3522             },
3523             name: 'dark'
3524         },
3525         position: {
3526             target: 'mouse',
3527             corner: { target: 'rightMiddle', tooltip: 'leftMiddle' },
3528             adjust: { x: 10, y: 20 }
3529         },
3530         show: {
3531             delay: 0,
3532             effect: {
3533                 type: 'grow',
3534                 length: 150
3535             }
3536         },
3537         hide: {
3538             effect: {
3539                 type: 'grow',
3540                 length: 200
3541             }
3542         }
3543     }
3545     $elements.qtip($.extend(true, o, options));
3549  * Return value of a cell in a table.
3550  */
3551 function PMA_getCellValue(td) {
3552     if ($(td).is('.null')) {
3553         return '';
3554     } else if (! $(td).is('.to_be_saved') && $(td).data('original_data')) {
3555         return $(td).data('original_data');
3556     } else {
3557         return $(td).text();
3558     }
3561 /* Loads a js file, an array may be passed as well */
3562 loadJavascript=function(file) {
3563     if($.isArray(file)) {
3564         for(var i=0; i<file.length; i++) {
3565             $('head').append('<script type="text/javascript" src="'+file[i]+'"></script>');
3566         }
3567     } else {
3568         $('head').append('<script type="text/javascript" src="'+file+'"></script>');
3569     }
3572 $(document).ready(function() {
3573     /**
3574      * Theme selector.
3575      */
3576     $('a.themeselect').live('click', function(e) {
3577         window.open(
3578             e.target,
3579             'themes',
3580             'left=10,top=20,width=510,height=350,scrollbars=yes,status=yes,resizable=yes'
3581             );
3582         return false;
3583     });
3585     /**
3586      * Automatic form submission on change.
3587      */
3588     $('.autosubmit').change(function(e) {
3589         e.target.form.submit();
3590     });
3592     /**
3593      * Theme changer.
3594      */
3595     $('.take_theme').click(function(e) {
3596         var what = this.name;
3597         if (window.opener && window.opener.document.forms['setTheme'].elements['set_theme']) {
3598             window.opener.document.forms['setTheme'].elements['set_theme'].value = what;
3599             window.opener.document.forms['setTheme'].submit();
3600             window.close();
3601             return false;
3602         }
3603         return true;
3604     });
3608  * Clear text selection
3609  */
3610 function PMA_clearSelection() {
3611     if(document.selection && document.selection.empty) {
3612         document.selection.empty();
3613     } else if(window.getSelection) {
3614         var sel = window.getSelection();
3615         if(sel.empty) sel.empty();
3616         if(sel.removeAllRanges) sel.removeAllRanges();
3617     }
3621  * HTML escaping
3622  */
3623 function escapeHtml(unsafe) {
3624     return unsafe
3625         .replace(/&/g, "&amp;")
3626         .replace(/</g, "&lt;")
3627         .replace(/>/g, "&gt;")
3628         .replace(/"/g, "&quot;")
3629         .replace(/'/g, "&#039;");
3633  * Print button
3634  */
3635 function printPage()
3637     // Do print the page
3638     if (typeof(window.print) != 'undefined') {
3639         window.print();
3640     }
3643 $(document).ready(function() {
3644     $('input#print').click(printPage);
3648  * Makes the breadcrumbs and the menu bar float at the top of the viewport
3649  */
3650 $(document).ready(function () {
3651     if ($("#floating_menubar").length && $('#PMA_disable_floating_menubar').length == 0) {
3652         $("#floating_menubar")
3653             .css({
3654                 'position': 'fixed',
3655                 'top': 0,
3656                 'left': 0,
3657                 'width': '100%',
3658                 'z-index': 500
3659             })
3660             .append($('#serverinfo'))
3661             .append($('#topmenucontainer'));
3662         $('body').css(
3663             'padding-top',
3664             $('#floating_menubar').outerHeight(true)
3665         );
3666     }
3670  * Toggles row colors of a set of 'tr' elements starting from a given element
3672  * @param $start Starting element
3673  */
3674 function toggleRowColors($start)
3676     for (var $curr_row = $start; $curr_row.length > 0; $curr_row = $curr_row.next()) {
3677         if ($curr_row.hasClass('odd')) {
3678             $curr_row.removeClass('odd').addClass('even');
3679         } else if ($curr_row.hasClass('even')) {
3680             $curr_row.removeClass('even').addClass('odd');
3681         }
3682     }