Translated using Weblate.
[phpmyadmin.git] / js / functions.js
blob6d8a9dcb2164c7dbce53885916432fa008bcd903
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(data)
133     var current = parseVersionString(pmaversion);
134     var latest = parseVersionString(data['version']);
135     var version_information_message = PMA_messages['strLatestAvailable'] + ' ' + escapeHtml(data['version']);
136     if (latest > current) {
137         var message = $.sprintf(PMA_messages['strNewerVersion'], escapeHtml(data['version']), escapeHtml(data['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         onClose: function(dateText, dp_inst) {
200             // The value is no more from the date picker
201             $this_element.data('comes_from', '');
202         }
203     };
205     $this_element.datetimepicker($.extend(defaultOptions, options));
209  * selects the content of a given object, f.e. a textarea
211  * @param   object  element     element of which the content will be selected
212  * @param   var     lock        variable which holds the lock for this element
213  *                              or true, if no lock exists
214  * @param   boolean only_once   if true this is only done once
215  *                              f.e. only on first focus
216  */
217 function selectContent( element, lock, only_once )
219     if ( only_once && only_once_elements[element.name] ) {
220         return;
221     }
223     only_once_elements[element.name] = true;
225     if ( lock  ) {
226         return;
227     }
229     element.select();
233  * Displays a confirmation box before submitting a "DROP/DELETE/ALTER" query.
234  * This function is called while clicking links
236  * @param   object   the link
237  * @param   object   the sql query to submit
239  * @return  boolean  whether to run the query or not
240  */
241 function confirmLink(theLink, theSqlQuery)
243     // Confirmation is not required in the configuration file
244     // or browser is Opera (crappy js implementation)
245     if (PMA_messages['strDoYouReally'] == '' || typeof(window.opera) != 'undefined') {
246         return true;
247     }
249     var is_confirmed = confirm(PMA_messages['strDoYouReally'] + ' :\n' + theSqlQuery);
250     if (is_confirmed) {
251         if ( $(theLink).hasClass('formLinkSubmit') ) {
252             var name = 'is_js_confirmed';
253             if ($(theLink).attr('href').indexOf('usesubform') != -1) {
254                 name = 'subform[' + $(theLink).attr('href').substr('#').match(/usesubform\[(\d+)\]/i)[1] + '][is_js_confirmed]';
255             }
257             $(theLink).parents('form').append('<input type="hidden" name="' + name + '" value="1" />');
258         } else if ( typeof(theLink.href) != 'undefined' ) {
259             theLink.href += '&is_js_confirmed=1';
260         } else if ( typeof(theLink.form) != 'undefined' ) {
261             theLink.form.action += '?is_js_confirmed=1';
262         }
263     }
265     return is_confirmed;
266 } // end of the 'confirmLink()' function
269  * Displays an error message if a "DROP DATABASE" statement is submitted
270  * while it isn't allowed, else confirms a "DROP/DELETE/ALTER" query before
271  * sumitting it if required.
272  * This function is called by the 'checkSqlQuery()' js function.
274  * @param   object   the form
275  * @param   object   the sql query textarea
277  * @return  boolean  whether to run the query or not
279  * @see     checkSqlQuery()
280  */
281 function confirmQuery(theForm1, sqlQuery1)
283     // Confirmation is not required in the configuration file
284     if (PMA_messages['strDoYouReally'] == '') {
285         return true;
286     }
288     // "DROP DATABASE" statement isn't allowed
289     if (PMA_messages['strNoDropDatabases'] != '') {
290         var drop_re = new RegExp('(^|;)\\s*DROP\\s+(IF EXISTS\\s+)?DATABASE\\s', 'i');
291         if (drop_re.test(sqlQuery1.value)) {
292             alert(PMA_messages['strNoDropDatabases']);
293             theForm1.reset();
294             sqlQuery1.focus();
295             return false;
296         } // end if
297     } // end if
299     // Confirms a "DROP/DELETE/ALTER/TRUNCATE" statement
300     //
301     // TODO: find a way (if possible) to use the parser-analyser
302     // for this kind of verification
303     // For now, I just added a ^ to check for the statement at
304     // beginning of expression
306     var do_confirm_re_0 = new RegExp('^\\s*DROP\\s+(IF EXISTS\\s+)?(TABLE|DATABASE|PROCEDURE)\\s', 'i');
307     var do_confirm_re_1 = new RegExp('^\\s*ALTER\\s+TABLE\\s+((`[^`]+`)|([A-Za-z0-9_$]+))\\s+DROP\\s', 'i');
308     var do_confirm_re_2 = new RegExp('^\\s*DELETE\\s+FROM\\s', 'i');
309     var do_confirm_re_3 = new RegExp('^\\s*TRUNCATE\\s', 'i');
311     if (do_confirm_re_0.test(sqlQuery1.value)
312         || do_confirm_re_1.test(sqlQuery1.value)
313         || do_confirm_re_2.test(sqlQuery1.value)
314         || do_confirm_re_3.test(sqlQuery1.value)) {
315         var message      = (sqlQuery1.value.length > 100)
316                          ? sqlQuery1.value.substr(0, 100) + '\n    ...'
317                          : sqlQuery1.value;
318         var is_confirmed = confirm(PMA_messages['strDoYouReally'] + ' :\n' + message);
319         // statement is confirmed -> update the
320         // "is_js_confirmed" form field so the confirm test won't be
321         // run on the server side and allows to submit the form
322         if (is_confirmed) {
323             theForm1.elements['is_js_confirmed'].value = 1;
324             return true;
325         }
326         // statement is rejected -> do not submit the form
327         else {
328             window.focus();
329             sqlQuery1.focus();
330             return false;
331         } // end if (handle confirm box result)
332     } // end if (display confirm box)
334     return true;
335 } // end of the 'confirmQuery()' function
339  * Displays a confirmation box before disabling the BLOB repository for a given database.
340  * This function is called while clicking links
342  * @param   object   the database
344  * @return  boolean  whether to disable the repository or not
345  */
346 function confirmDisableRepository(theDB)
348     // Confirmation is not required in the configuration file
349     // or browser is Opera (crappy js implementation)
350     if (PMA_messages['strDoYouReally'] == '' || typeof(window.opera) != 'undefined') {
351         return true;
352     }
354     var is_confirmed = confirm(PMA_messages['strBLOBRepositoryDisableStrongWarning'] + '\n' + PMA_messages['strBLOBRepositoryDisableAreYouSure']);
356     return is_confirmed;
357 } // end of the 'confirmDisableBLOBRepository()' function
361  * Displays an error message if the user submitted the sql query form with no
362  * sql query, else checks for "DROP/DELETE/ALTER" statements
364  * @param   object   the form
366  * @return  boolean  always false
368  * @see     confirmQuery()
369  */
370 function checkSqlQuery(theForm)
372     var sqlQuery = theForm.elements['sql_query'];
373     var isEmpty  = 1;
375     var space_re = new RegExp('\\s+');
376     if (typeof(theForm.elements['sql_file']) != 'undefined' &&
377             theForm.elements['sql_file'].value.replace(space_re, '') != '') {
378         return true;
379     }
380     if (typeof(theForm.elements['sql_localfile']) != 'undefined' &&
381             theForm.elements['sql_localfile'].value.replace(space_re, '') != '') {
382         return true;
383     }
384     if (isEmpty && typeof(theForm.elements['id_bookmark']) != 'undefined' &&
385             (theForm.elements['id_bookmark'].value != null || theForm.elements['id_bookmark'].value != '') &&
386             theForm.elements['id_bookmark'].selectedIndex != 0
387             ) {
388         return true;
389     }
390     // Checks for "DROP/DELETE/ALTER" statements
391     if (sqlQuery.value.replace(space_re, '') != '') {
392         if (confirmQuery(theForm, sqlQuery)) {
393             return true;
394         } else {
395             return false;
396         }
397     }
398     theForm.reset();
399     isEmpty = 1;
401     if (isEmpty) {
402         sqlQuery.select();
403         alert(PMA_messages['strFormEmpty']);
404         sqlQuery.focus();
405         return false;
406     }
408     return true;
409 } // end of the 'checkSqlQuery()' function
412  * Check if a form's element is empty.
413  * An element containing only spaces is also considered empty
415  * @param   object   the form
416  * @param   string   the name of the form field to put the focus on
418  * @return  boolean  whether the form field is empty or not
419  */
420 function emptyCheckTheField(theForm, theFieldName)
422     var theField = theForm.elements[theFieldName];
423     var space_re = new RegExp('\\s+');
424     return (theField.value.replace(space_re, '') == '') ? 1 : 0;
425 } // end of the 'emptyCheckTheField()' function
429  * Check whether a form field is empty or not
431  * @param   object   the form
432  * @param   string   the name of the form field to put the focus on
434  * @return  boolean  whether the form field is empty or not
435  */
436 function emptyFormElements(theForm, theFieldName)
438     var theField = theForm.elements[theFieldName];
439     var isEmpty = emptyCheckTheField(theForm, theFieldName);
442     return isEmpty;
443 } // end of the 'emptyFormElements()' function
447  * Ensures a value submitted in a form is numeric and is in a range
449  * @param   object   the form
450  * @param   string   the name of the form field to check
451  * @param   integer  the minimum authorized value
452  * @param   integer  the maximum authorized value
454  * @return  boolean  whether a valid number has been submitted or not
455  */
456 function checkFormElementInRange(theForm, theFieldName, message, min, max)
458     var theField         = theForm.elements[theFieldName];
459     var val              = parseInt(theField.value);
461     if (typeof(min) == 'undefined') {
462         min = 0;
463     }
464     if (typeof(max) == 'undefined') {
465         max = Number.MAX_VALUE;
466     }
468     // It's not a number
469     if (isNaN(val)) {
470         theField.select();
471         alert(PMA_messages['strNotNumber']);
472         theField.focus();
473         return false;
474     }
475     // It's a number but it is not between min and max
476     else if (val < min || val > max) {
477         theField.select();
478         alert(message.replace('%d', val));
479         theField.focus();
480         return false;
481     }
482     // It's a valid number
483     else {
484         theField.value = val;
485     }
486     return true;
488 } // end of the 'checkFormElementInRange()' function
491 function checkTableEditForm(theForm, fieldsCnt)
493     // TODO: avoid sending a message if user just wants to add a line
494     // on the form but has not completed at least one field name
496     var atLeastOneField = 0;
497     var i, elm, elm2, elm3, val, id;
499     for (i=0; i<fieldsCnt; i++)
500     {
501         id = "#field_" + i + "_2";
502         elm = $(id);
503         val = elm.val()
504         if (val == 'VARCHAR' || val == 'CHAR' || val == 'BIT' || val == 'VARBINARY' || val == 'BINARY') {
505             elm2 = $("#field_" + i + "_3");
506             val = parseInt(elm2.val());
507             elm3 = $("#field_" + i + "_1");
508             if (isNaN(val) && elm3.val() != "") {
509                 elm2.select();
510                 alert(PMA_messages['strNotNumber']);
511                 elm2.focus();
512                 return false;
513             }
514         }
516         if (atLeastOneField == 0) {
517             id = "field_" + i + "_1";
518             if (!emptyCheckTheField(theForm, id)) {
519                 atLeastOneField = 1;
520             }
521         }
522     }
523     if (atLeastOneField == 0) {
524         var theField = theForm.elements["field_0_1"];
525         alert(PMA_messages['strFormEmpty']);
526         theField.focus();
527         return false;
528     }
530     // at least this section is under jQuery
531     if ($("input.textfield[name='table']").val() == "") {
532         alert(PMA_messages['strFormEmpty']);
533         $("input.textfield[name='table']").focus();
534         return false;
535     }
538     return true;
539 } // enf of the 'checkTableEditForm()' function
541 $(document).ready(function() {
542     /**
543      * Row marking in horizontal mode (use "live" so that it works also for
544      * next pages reached via AJAX); a tr may have the class noclick to remove
545      * this behavior.
546      */
547     $('table:not(.noclick) tr.odd:not(.noclick), table:not(.noclick) tr.even:not(.noclick)').live('click',function(e) {
548         // do not trigger when clicked on anchor
549         if ($(e.target).is('a, img, a *')) {
550             return;
551         }
552         var $tr = $(this);
554         // make the table unselectable (to prevent default highlighting when shift+click)
555         //$tr.parents('table').noSelect();
557         if (!e.shiftKey || last_clicked_row == -1) {
558             // usual click
560             // XXX: FF fires two click events for <label> (label and checkbox), so we need to handle this differently
561             var $checkbox = $tr.find(':checkbox');
562             if ($checkbox.length) {
563                 // checkbox in a row, add or remove class depending on checkbox state
564                 var checked = $checkbox.attr('checked');
565                 if (!$(e.target).is(':checkbox, label')) {
566                     checked = !checked;
567                     $checkbox.attr('checked', checked);
568                 }
569                 if (checked) {
570                     $tr.addClass('marked');
571                 } else {
572                     $tr.removeClass('marked');
573                 }
574                 last_click_checked = checked;
575             } else {
576                 // normaln data table, just toggle class
577                 $tr.toggleClass('marked');
578                 last_click_checked = false;
579             }
581             // remember the last clicked row
582             last_clicked_row = last_click_checked ? $('tr.odd:not(.noclick), tr.even:not(.noclick)').index(this) : -1;
583             last_shift_clicked_row = -1;
584         } else {
585             // handle the shift click
586             PMA_clearSelection();
587             var start, end;
589             // clear last shift click result
590             if (last_shift_clicked_row >= 0) {
591                 if (last_shift_clicked_row >= last_clicked_row) {
592                     start = last_clicked_row;
593                     end = last_shift_clicked_row;
594                 } else {
595                     start = last_shift_clicked_row;
596                     end = last_clicked_row;
597                 }
598                 $tr.parent().find('tr.odd:not(.noclick), tr.even:not(.noclick)')
599                     .slice(start, end + 1)
600                     .removeClass('marked')
601                     .find(':checkbox')
602                     .attr('checked', false);
603             }
605             // handle new shift click
606             var curr_row = $('tr.odd:not(.noclick), tr.even:not(.noclick)').index(this);
607             if (curr_row >= last_clicked_row) {
608                 start = last_clicked_row;
609                 end = curr_row;
610             } else {
611                 start = curr_row;
612                 end = last_clicked_row;
613             }
614             $tr.parent().find('tr.odd:not(.noclick), tr.even:not(.noclick)')
615                 .slice(start, end + 1)
616                 .addClass('marked')
617                 .find(':checkbox')
618                 .attr('checked', true);
620             // remember the last shift clicked row
621             last_shift_clicked_row = curr_row;
622         }
623     });
625     /**
626      * Add a date/time picker to each element that needs it
627      * (only when timepicker.js is loaded)
628      */
629     if ($.timepicker != undefined) {
630         $('.datefield, .datetimefield').each(function() {
631             PMA_addDatepicker($(this));
632             });
633     }
637  * True if last click is to check a row.
638  */
639 var last_click_checked = false;
642  * Zero-based index of last clicked row.
643  * Used to handle the shift + click event in the code above.
644  */
645 var last_clicked_row = -1;
648  * Zero-based index of last shift clicked row.
649  */
650 var last_shift_clicked_row = -1;
653  * Row highlighting in horizontal mode (use "live"
654  * so that it works also for pages reached via AJAX)
655  */
656 /*$(document).ready(function() {
657     $('tr.odd, tr.even').live('hover',function(event) {
658         var $tr = $(this);
659         $tr.toggleClass('hover',event.type=='mouseover');
660         $tr.children().toggleClass('hover',event.type=='mouseover');
661     });
662 })*/
665  * This array is used to remember mark status of rows in browse mode
666  */
667 var marked_row = new Array;
670  * marks all rows and selects its first checkbox inside the given element
671  * the given element is usaly a table or a div containing the table or tables
673  * @param    container    DOM element
674  */
675 function markAllRows( container_id )
678     $("#"+container_id).find("input:checkbox:enabled").attr('checked', 'checked')
679     .parents("tr").addClass("marked");
680     return true;
684  * marks all rows and selects its first checkbox inside the given element
685  * the given element is usaly a table or a div containing the table or tables
687  * @param    container    DOM element
688  */
689 function unMarkAllRows( container_id )
692     $("#"+container_id).find("input:checkbox:enabled").removeAttr('checked')
693     .parents("tr").removeClass("marked");
694     return true;
698  * Checks/unchecks all checkbox in given conainer (f.e. a form, fieldset or div)
700  * @param   string   container_id  the container id
701  * @param   boolean  state         new value for checkbox (true or false)
702  * @return  boolean  always true
703  */
704 function setCheckboxes( container_id, state )
707     if(state) {
708         $("#"+container_id).find("input:checkbox").attr('checked', 'checked');
709     }
710     else {
711         $("#"+container_id).find("input:checkbox").removeAttr('checked');
712     }
714     return true;
715 } // end of the 'setCheckboxes()' function
718   * Checks/unchecks all options of a <select> element
719   *
720   * @param   string   the form name
721   * @param   string   the element name
722   * @param   boolean  whether to check or to uncheck options
723   *
724   * @return  boolean  always true
725   */
726 function setSelectOptions(the_form, the_select, do_check)
728     $("form[name='"+ the_form +"'] select[name='"+the_select+"']").find("option").attr('selected', do_check);
729     return true;
730 } // end of the 'setSelectOptions()' function
733  * Sets current value for query box.
734  */
735 function setQuery(query)
737     if (codemirror_editor) {
738         codemirror_editor.setValue(query);
739     } else {
740         document.sqlform.sql_query.value = query;
741     }
746   * Create quick sql statements.
747   *
748   */
749 function insertQuery(queryType)
751     if (queryType == "clear") {
752         setQuery('');
753         return;
754     }
756     var myQuery = document.sqlform.sql_query;
757     var query = "";
758     var myListBox = document.sqlform.dummy;
759     var table = document.sqlform.table.value;
761     if (myListBox.options.length > 0) {
762         sql_box_locked = true;
763         var chaineAj = "";
764         var valDis = "";
765         var editDis = "";
766         var NbSelect = 0;
767         for (var i=0; i < myListBox.options.length; i++) {
768             NbSelect++;
769             if (NbSelect > 1) {
770                 chaineAj += ", ";
771                 valDis += ",";
772                 editDis += ",";
773             }
774             chaineAj += myListBox.options[i].value;
775             valDis += "[value-" + NbSelect + "]";
776             editDis += myListBox.options[i].value + "=[value-" + NbSelect + "]";
777         }
778         if (queryType == "selectall") {
779             query = "SELECT * FROM `" + table + "` WHERE 1";
780         } else if (queryType == "select") {
781             query = "SELECT " + chaineAj + " FROM `" + table + "` WHERE 1";
782         } else if (queryType == "insert") {
783                query = "INSERT INTO `" + table + "`(" + chaineAj + ") VALUES (" + valDis + ")";
784         } else if (queryType == "update") {
785             query = "UPDATE `" + table + "` SET " + editDis + " WHERE 1";
786         } else if(queryType == "delete") {
787             query = "DELETE FROM `" + table + "` WHERE 1";
788         }
789         setQuery(query);
790         sql_box_locked = false;
791     }
796   * Inserts multiple fields.
797   *
798   */
799 function insertValueQuery()
801     var myQuery = document.sqlform.sql_query;
802     var myListBox = document.sqlform.dummy;
804     if(myListBox.options.length > 0) {
805         sql_box_locked = true;
806         var chaineAj = "";
807         var NbSelect = 0;
808         for(var i=0; i<myListBox.options.length; i++) {
809             if (myListBox.options[i].selected) {
810                 NbSelect++;
811                 if (NbSelect > 1) {
812                     chaineAj += ", ";
813                 }
814                 chaineAj += myListBox.options[i].value;
815             }
816         }
818         /* CodeMirror support */
819         if (codemirror_editor) {
820             codemirror_editor.replaceSelection(chaineAj);
821         //IE support
822         } else if (document.selection) {
823             myQuery.focus();
824             sel = document.selection.createRange();
825             sel.text = chaineAj;
826             document.sqlform.insert.focus();
827         }
828         //MOZILLA/NETSCAPE support
829         else if (document.sqlform.sql_query.selectionStart || document.sqlform.sql_query.selectionStart == "0") {
830             var startPos = document.sqlform.sql_query.selectionStart;
831             var endPos = document.sqlform.sql_query.selectionEnd;
832             var chaineSql = document.sqlform.sql_query.value;
834             myQuery.value = chaineSql.substring(0, startPos) + chaineAj + chaineSql.substring(endPos, chaineSql.length);
835         } else {
836             myQuery.value += chaineAj;
837         }
838         sql_box_locked = false;
839     }
843   * listbox redirection
844   */
845 function goToUrl(selObj, goToLocation)
847     eval("document.location.href = '" + goToLocation + "pos=" + selObj.options[selObj.selectedIndex].value + "'");
851   * Refresh the WYSIWYG scratchboard after changes have been made
852   */
853 function refreshDragOption(e)
855     var elm = $('#' + e);
856     if (elm.css('visibility') == 'visible') {
857         refreshLayout();
858         TableDragInit();
859     }
863   * Refresh/resize the WYSIWYG scratchboard
864   */
865 function refreshLayout()
867     var elm = $('#pdflayout')
868     var orientation = $('#orientation_opt').val();
869     if($('#paper_opt').length==1){
870         var paper = $('#paper_opt').val();
871     }else{
872         var paper = 'A4';
873     }
874     if (orientation == 'P') {
875         posa = 'x';
876         posb = 'y';
877     } else {
878         posa = 'y';
879         posb = 'x';
880     }
881     elm.css('width', pdfPaperSize(paper, posa) + 'px');
882     elm.css('height', pdfPaperSize(paper, posb) + 'px');
886   * Show/hide the WYSIWYG scratchboard
887   */
888 function ToggleDragDrop(e)
890     var elm = $('#' + e);
891     if (elm.css('visibility') == 'hidden') {
892         PDFinit(); /* Defined in pdf_pages.php */
893         elm.css('visibility', 'visible');
894         elm.css('display', 'block');
895         $('#showwysiwyg').val('1')
896     } else {
897         elm.css('visibility', 'hidden');
898         elm.css('display', 'none');
899         $('#showwysiwyg').val('0')
900     }
904   * PDF scratchboard: When a position is entered manually, update
905   * the fields inside the scratchboard.
906   */
907 function dragPlace(no, axis, value)
909     var elm = $('#table_' + no);
910     if (axis == 'x') {
911         elm.css('left', value + 'px');
912     } else {
913         elm.css('top', value + 'px');
914     }
918  * Returns paper sizes for a given format
919  */
920 function pdfPaperSize(format, axis)
922     switch (format.toUpperCase()) {
923         case '4A0':
924             if (axis == 'x') return 4767.87; else return 6740.79;
925             break;
926         case '2A0':
927             if (axis == 'x') return 3370.39; else return 4767.87;
928             break;
929         case 'A0':
930             if (axis == 'x') return 2383.94; else return 3370.39;
931             break;
932         case 'A1':
933             if (axis == 'x') return 1683.78; else return 2383.94;
934             break;
935         case 'A2':
936             if (axis == 'x') return 1190.55; else return 1683.78;
937             break;
938         case 'A3':
939             if (axis == 'x') return 841.89; else return 1190.55;
940             break;
941         case 'A4':
942             if (axis == 'x') return 595.28; else return 841.89;
943             break;
944         case 'A5':
945             if (axis == 'x') return 419.53; else return 595.28;
946             break;
947         case 'A6':
948             if (axis == 'x') return 297.64; else return 419.53;
949             break;
950         case 'A7':
951             if (axis == 'x') return 209.76; else return 297.64;
952             break;
953         case 'A8':
954             if (axis == 'x') return 147.40; else return 209.76;
955             break;
956         case 'A9':
957             if (axis == 'x') return 104.88; else return 147.40;
958             break;
959         case 'A10':
960             if (axis == 'x') return 73.70; else return 104.88;
961             break;
962         case 'B0':
963             if (axis == 'x') return 2834.65; else return 4008.19;
964             break;
965         case 'B1':
966             if (axis == 'x') return 2004.09; else return 2834.65;
967             break;
968         case 'B2':
969             if (axis == 'x') return 1417.32; else return 2004.09;
970             break;
971         case 'B3':
972             if (axis == 'x') return 1000.63; else return 1417.32;
973             break;
974         case 'B4':
975             if (axis == 'x') return 708.66; else return 1000.63;
976             break;
977         case 'B5':
978             if (axis == 'x') return 498.90; else return 708.66;
979             break;
980         case 'B6':
981             if (axis == 'x') return 354.33; else return 498.90;
982             break;
983         case 'B7':
984             if (axis == 'x') return 249.45; else return 354.33;
985             break;
986         case 'B8':
987             if (axis == 'x') return 175.75; else return 249.45;
988             break;
989         case 'B9':
990             if (axis == 'x') return 124.72; else return 175.75;
991             break;
992         case 'B10':
993             if (axis == 'x') return 87.87; else return 124.72;
994             break;
995         case 'C0':
996             if (axis == 'x') return 2599.37; else return 3676.54;
997             break;
998         case 'C1':
999             if (axis == 'x') return 1836.85; else return 2599.37;
1000             break;
1001         case 'C2':
1002             if (axis == 'x') return 1298.27; else return 1836.85;
1003             break;
1004         case 'C3':
1005             if (axis == 'x') return 918.43; else return 1298.27;
1006             break;
1007         case 'C4':
1008             if (axis == 'x') return 649.13; else return 918.43;
1009             break;
1010         case 'C5':
1011             if (axis == 'x') return 459.21; else return 649.13;
1012             break;
1013         case 'C6':
1014             if (axis == 'x') return 323.15; else return 459.21;
1015             break;
1016         case 'C7':
1017             if (axis == 'x') return 229.61; else return 323.15;
1018             break;
1019         case 'C8':
1020             if (axis == 'x') return 161.57; else return 229.61;
1021             break;
1022         case 'C9':
1023             if (axis == 'x') return 113.39; else return 161.57;
1024             break;
1025         case 'C10':
1026             if (axis == 'x') return 79.37; else return 113.39;
1027             break;
1028         case 'RA0':
1029             if (axis == 'x') return 2437.80; else return 3458.27;
1030             break;
1031         case 'RA1':
1032             if (axis == 'x') return 1729.13; else return 2437.80;
1033             break;
1034         case 'RA2':
1035             if (axis == 'x') return 1218.90; else return 1729.13;
1036             break;
1037         case 'RA3':
1038             if (axis == 'x') return 864.57; else return 1218.90;
1039             break;
1040         case 'RA4':
1041             if (axis == 'x') return 609.45; else return 864.57;
1042             break;
1043         case 'SRA0':
1044             if (axis == 'x') return 2551.18; else return 3628.35;
1045             break;
1046         case 'SRA1':
1047             if (axis == 'x') return 1814.17; else return 2551.18;
1048             break;
1049         case 'SRA2':
1050             if (axis == 'x') return 1275.59; else return 1814.17;
1051             break;
1052         case 'SRA3':
1053             if (axis == 'x') return 907.09; else return 1275.59;
1054             break;
1055         case 'SRA4':
1056             if (axis == 'x') return 637.80; else return 907.09;
1057             break;
1058         case 'LETTER':
1059             if (axis == 'x') return 612.00; else return 792.00;
1060             break;
1061         case 'LEGAL':
1062             if (axis == 'x') return 612.00; else return 1008.00;
1063             break;
1064         case 'EXECUTIVE':
1065             if (axis == 'x') return 521.86; else return 756.00;
1066             break;
1067         case 'FOLIO':
1068             if (axis == 'x') return 612.00; else return 936.00;
1069             break;
1070     } // end switch
1072     return 0;
1076  * for playing media from the BLOB repository
1078  * @param   var
1079  * @param   var     url_params  main purpose is to pass the token
1080  * @param   var     bs_ref      BLOB repository reference
1081  * @param   var     m_type      type of BLOB repository media
1082  * @param   var     w_width     width of popup window
1083  * @param   var     w_height    height of popup window
1084  */
1085 function popupBSMedia(url_params, bs_ref, m_type, is_cust_type, w_width, w_height)
1087     // if width not specified, use default
1088     if (w_width == undefined) {
1089         w_width = 640;
1090     }
1092     // if height not specified, use default
1093     if (w_height == undefined) {
1094         w_height = 480;
1095     }
1097     // open popup window (for displaying video/playing audio)
1098     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');
1102  * popups a request for changing MIME types for files in the BLOB repository
1104  * @param   var     db                      database name
1105  * @param   var     table                   table name
1106  * @param   var     reference               BLOB repository reference
1107  * @param   var     current_mime_type       current MIME type associated with BLOB repository reference
1108  */
1109 function requestMIMETypeChange(db, table, reference, current_mime_type)
1111     // no mime type specified, set to default (nothing)
1112     if (undefined == current_mime_type) {
1113         current_mime_type = "";
1114     }
1116     // prompt user for new mime type
1117     var new_mime_type = prompt("Enter custom MIME type", current_mime_type);
1119     // if new mime_type is specified and is not the same as the previous type, request for mime type change
1120     if (new_mime_type && new_mime_type != current_mime_type) {
1121         changeMIMEType(db, table, reference, new_mime_type);
1122     }
1126  * changes MIME types for files in the BLOB repository
1128  * @param   var     db              database name
1129  * @param   var     table           table name
1130  * @param   var     reference       BLOB repository reference
1131  * @param   var     mime_type       new MIME type to be associated with BLOB repository reference
1132  */
1133 function changeMIMEType(db, table, reference, mime_type)
1135     // specify url and parameters for jQuery POST
1136     var mime_chg_url = 'bs_change_mime_type.php';
1137     var params = {bs_db: db, bs_table: table, bs_reference: reference, bs_new_mime_type: mime_type};
1139     // jQuery POST
1140     jQuery.post(mime_chg_url, params);
1144  * Jquery Coding for inline editing SQL_QUERY
1145  */
1146 $(document).ready(function(){
1147     $(".inline_edit_sql").live('click', function(){
1148         if ($('#sql_query_edit').length) {
1149             // An inline query editor is already open,
1150             // we don't want another copy of it
1151             return false;
1152         }
1154         var $form = $(this).prev();
1155         var sql_query  = $form.find("input[name='sql_query']").val();
1156         var $inner_sql = $(this).parent().prev().find('.inner_sql');
1157         var old_text   = $inner_sql.html();
1159         var new_content = "<textarea name=\"sql_query_edit\" id=\"sql_query_edit\">" + sql_query + "</textarea>\n";
1160         new_content    += "<input type=\"button\" class=\"btnSave\" value=\"" + PMA_messages['strGo'] + "\">\n";
1161         new_content    += "<input type=\"button\" class=\"btnDiscard\" value=\"" + PMA_messages['strCancel'] + "\">\n";
1162         $inner_sql.replaceWith(new_content);
1164         // These settings are duplicated from the .ready()function in functions.js
1165         var height = $('#sql_query_edit').css('height');
1166         codemirror_editor = CodeMirror.fromTextArea($('textarea[name="sql_query_edit"]')[0], {
1167             lineNumbers: true,
1168             matchBrackets: true,
1169             indentUnit: 4,
1170             mode: "text/x-mysql",
1171             lineWrapping: true
1172         });
1173         codemirror_editor.getScrollerElement().style.height = height;
1174         codemirror_editor.refresh();
1176         $(".btnSave").click(function(){
1177             if (codemirror_editor !== undefined) {
1178                 var sql_query = codemirror_editor.getValue();
1179             } else {
1180                 var sql_query = $(this).prev().val();
1181             }
1182             var $fake_form = $('<form>', {action: 'import.php', method: 'post'})
1183                     .append($form.find("input[name=server], input[name=db], input[name=table], input[name=token]").clone())
1184                     .append($('<input>', {type: 'hidden', name: 'show_query', value: 1}))
1185                     .append($('<input>', {type: 'hidden', name: 'sql_query', value: sql_query}));
1186             $fake_form.appendTo($('body')).submit();
1187         });
1188         $(".btnDiscard").click(function(){
1189             $(this).closest(".sql").html("<span class=\"syntax\"><span class=\"inner_sql\">" + old_text + "</span></span>");
1190         });
1191         return false;
1192     });
1194     $('.sqlbutton').click(function(evt){
1195         insertQuery(evt.target.id);
1196         return false;
1197     });
1199     $("#export_type").change(function(){
1200         if($("#export_type").val()=='svg'){
1201             $("#show_grid_opt").attr("disabled","disabled");
1202             $("#orientation_opt").attr("disabled","disabled");
1203             $("#with_doc").attr("disabled","disabled");
1204             $("#show_table_dim_opt").removeAttr("disabled");
1205             $("#all_table_same_wide").removeAttr("disabled");
1206             $("#paper_opt").removeAttr("disabled","disabled");
1207             $("#show_color_opt").removeAttr("disabled","disabled");
1208             //$(this).css("background-color","yellow");
1209         }else if($("#export_type").val()=='dia'){
1210             $("#show_grid_opt").attr("disabled","disabled");
1211             $("#with_doc").attr("disabled","disabled");
1212             $("#show_table_dim_opt").attr("disabled","disabled");
1213             $("#all_table_same_wide").attr("disabled","disabled");
1214             $("#paper_opt").removeAttr("disabled","disabled");
1215             $("#show_color_opt").removeAttr("disabled","disabled");
1216             $("#orientation_opt").removeAttr("disabled","disabled");
1217         }else if($("#export_type").val()=='eps'){
1218             $("#show_grid_opt").attr("disabled","disabled");
1219             $("#orientation_opt").removeAttr("disabled");
1220             $("#with_doc").attr("disabled","disabled");
1221             $("#show_table_dim_opt").attr("disabled","disabled");
1222             $("#all_table_same_wide").attr("disabled","disabled");
1223             $("#paper_opt").attr("disabled","disabled");
1224             $("#show_color_opt").attr("disabled","disabled");
1226         }else if($("#export_type").val()=='pdf'){
1227             $("#show_grid_opt").removeAttr("disabled");
1228             $("#orientation_opt").removeAttr("disabled");
1229             $("#with_doc").removeAttr("disabled","disabled");
1230             $("#show_table_dim_opt").removeAttr("disabled","disabled");
1231             $("#all_table_same_wide").removeAttr("disabled","disabled");
1232             $("#paper_opt").removeAttr("disabled","disabled");
1233             $("#show_color_opt").removeAttr("disabled","disabled");
1234         }else{
1235             // nothing
1236         }
1237     });
1239     $('#sqlquery').focus().keydown(function (e) {
1240         if (e.ctrlKey && e.keyCode == 13) {
1241             $("#sqlqueryform").submit();
1242         }
1243     });
1245     if ($('#input_username')) {
1246         if ($('#input_username').val() == '') {
1247             $('#input_username').focus();
1248         } else {
1249             $('#input_password').focus();
1250         }
1251     }
1255  * Show a message on the top of the page for an Ajax request
1257  * Sample usage:
1259  * 1) var $msg = PMA_ajaxShowMessage();
1260  * This will show a message that reads "Loading...". Such a message will not
1261  * disappear automatically and cannot be dismissed by the user. To remove this
1262  * message either the PMA_ajaxRemoveMessage($msg) function must be called or
1263  * another message must be show with PMA_ajaxShowMessage() function.
1265  * 2) var $msg = PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
1266  * This is a special case. The behaviour is same as above,
1267  * just with a different message
1269  * 3) var $msg = PMA_ajaxShowMessage('The operation was successful');
1270  * This will show a message that will disappear automatically and it can also
1271  * be dismissed by the user.
1273  * 4) var $msg = PMA_ajaxShowMessage('Some error', false);
1274  * This will show a message that will not disappear automatically, but it
1275  * can be dismissed by the user after he has finished reading it.
1277  * @param   string  message     string containing the message to be shown.
1278  *                              optional, defaults to 'Loading...'
1279  * @param   mixed   timeout     number of milliseconds for the message to be visible
1280  *                              optional, defaults to 5000. If set to 'false', the
1281  *                              notification will never disappear
1282  * @return  jQuery object       jQuery Element that holds the message div
1283  *                              this object can be passed to PMA_ajaxRemoveMessage()
1284  *                              to remove the notification
1285  */
1286 function PMA_ajaxShowMessage(message, timeout)
1288     /**
1289      * @var self_closing Whether the notification will automatically disappear
1290      */
1291     var self_closing = true;
1292     /**
1293      * @var dismissable Whether the user will be able to remove
1294      *                  the notification by clicking on it
1295      */
1296     var dismissable = true;
1297     // Handle the case when a empty data.message is passed.
1298     // We don't want the empty message
1299     if (message == '') {
1300         return true;
1301     } else if (! message) {
1302         // If the message is undefined, show the default
1303         message = PMA_messages['strLoading'];
1304         dismissable = false;
1305         self_closing = false;
1306     } else if (message == PMA_messages['strProcessingRequest']) {
1307         // This is another case where the message should not disappear
1308         dismissable = false;
1309         self_closing = false;
1310     }
1311     // Figure out whether (or after how long) to remove the notification
1312     if (timeout == undefined) {
1313         timeout = 5000;
1314     } else if (timeout === false) {
1315         self_closing = false;
1316     }
1317     // Create a parent element for the AJAX messages, if necessary
1318     if ($('#loading_parent').length == 0) {
1319         $('<div id="loading_parent"></div>')
1320         .prependTo("body");
1321     }
1322     // Update message count to create distinct message elements every time
1323     ajax_message_count++;
1324     // Remove all old messages, if any
1325     $(".ajax_notification[id^=ajax_message_num]").remove();
1326     /**
1327      * @var    $retval    a jQuery object containing the reference
1328      *                    to the created AJAX message
1329      */
1330     var $retval = $(
1331             '<span class="ajax_notification" id="ajax_message_num_'
1332             + ajax_message_count +
1333             '"></span>'
1334     )
1335     .hide()
1336     .appendTo("#loading_parent")
1337     .html(message)
1338     .fadeIn('medium');
1339     // If the notification is self-closing we should create a callback to remove it
1340     if (self_closing) {
1341         $retval
1342         .delay(timeout)
1343         .fadeOut('medium', function() {
1344             if ($(this).is('.dismissable')) {
1345                 // Here we should destroy the qtip instance, but
1346                 // due to a bug in qtip's implementation we can
1347                 // only hide it without throwing JS errors.
1348                 $(this).qtip('hide');
1349             }
1350             // Remove the notification
1351             $(this).remove();
1352         });
1353     }
1354     // If the notification is dismissable we need to add the relevant class to it
1355     // and add a tooltip so that the users know that it can be removed
1356     if (dismissable) {
1357         $retval.addClass('dismissable').css('cursor', 'pointer');
1358         /**
1359          * @var qOpts Options for "Dismiss notification" tooltip
1360          */
1361         var qOpts = {
1362             show: {
1363                 effect: { length: 0 },
1364                 delay: 0
1365             },
1366             hide: {
1367                 effect: { length: 0 },
1368                 delay: 0
1369             }
1370         };
1371         /**
1372          * Add a tooltip to the notification to let the user know that (s)he
1373          * can dismiss the ajax notification by clicking on it.
1374          */
1375         PMA_createqTip($retval, PMA_messages['strDismiss'], qOpts);
1376     }
1378     return $retval;
1382  * Removes the message shown for an Ajax operation when it's completed
1384  * @param  jQuery object   jQuery Element that holds the notification
1386  * @return nothing
1387  */
1388 function PMA_ajaxRemoveMessage($this_msgbox)
1390     if ($this_msgbox != undefined && $this_msgbox instanceof jQuery) {
1391         $this_msgbox
1392         .stop(true, true)
1393         .fadeOut('medium');
1394         if ($this_msgbox.is('.dismissable')) {
1395             if ($('#no_hint').length < 0) {
1396                 // Here we should destroy the qtip instance, but
1397                 // due to a bug in qtip's implementation we can
1398                 // only hide it without throwing JS errors.
1399                 $this_msgbox.qtip('hide');
1400             }
1401         } else {
1402             $this_msgbox.remove();
1403         }
1404     }
1407 $(document).ready(function() {
1408     /**
1409      * Allows the user to dismiss a notification
1410      * created with PMA_ajaxShowMessage()
1411      */
1412     $('.ajax_notification.dismissable').live('click', function () {
1413         PMA_ajaxRemoveMessage($(this));
1414     });
1415     /**
1416      * The below two functions hide the "Dismiss notification" tooltip when a user
1417      * is hovering a link or button that is inside an ajax message
1418      */
1419     $('.ajax_notification a, .ajax_notification button, .ajax_notification input')
1420     .live('mouseover', function () {
1421         $(this).parents('.ajax_notification').qtip('hide');
1422     });
1423     $('.ajax_notification a, .ajax_notification button, .ajax_notification input')
1424     .live('mouseout', function () {
1425         $(this).parents('.ajax_notification').qtip('show');
1426     });
1430  * Hides/shows the "Open in ENUM/SET editor" message, depending on the data type of the column currently selected
1431  */
1432 function PMA_showNoticeForEnum(selectElement)
1434     var enum_notice_id = selectElement.attr("id").split("_")[1];
1435     enum_notice_id += "_" + (parseInt(selectElement.attr("id").split("_")[2]) + 1);
1436     var selectedType = selectElement.val();
1437     if (selectedType == "ENUM" || selectedType == "SET") {
1438         $("p[id='enum_notice_" + enum_notice_id + "']").show();
1439     } else {
1440         $("p[id='enum_notice_" + enum_notice_id + "']").hide();
1441     }
1445  * Generates a dialog box to pop up the create_table form
1446  */
1447 function PMA_createTableDialog( $div, url , target)
1449      /**
1450       *  @var    button_options  Object that stores the options passed to jQueryUI
1451       *                          dialog
1452       */
1453      var button_options = {};
1454      // in the following function we need to use $(this)
1455      button_options[PMA_messages['strCancel']] = function() {
1456          $(this).closest('.ui-dialog-content').dialog('close').remove();
1457      };
1459      var button_options_error = {};
1460      button_options_error[PMA_messages['strOK']] = function() {
1461          $(this).closest('.ui-dialog-content').dialog('close').remove();
1462      };
1464      var $msgbox = PMA_ajaxShowMessage();
1466      $.get(target, url, function(data) {
1467       //in the case of an error, show the error message returned.
1468          if (data.success != undefined && data.success == false) {
1469              $div
1470              .append(data.error)
1471              .dialog({
1472                  height: 230,
1473                  width: 900,
1474                  open: PMA_verifyColumnsProperties,
1475                  buttons : button_options_error
1476              })// end dialog options
1477              //remove the redundant [Back] link in the error message.
1478              .find('fieldset').remove();
1479          }
1480          else {
1481              var size = getWindowSize();
1482              var timeout;
1483              $div
1484              .append(data)
1485              .dialog({
1486                  dialogClass: 'create-table',
1487                  resizable: false,
1488                  draggable: false,
1489                  modal: true,
1490                  stack: false,
1491                  position: ['left','top'],
1492                  width: size.width-10,
1493                  height: size.height-10,
1494                  open: function() {
1495                      var dialog_id = $(this).attr('id');
1496                      $(window).bind('resize.dialog-resizer', function() {
1497                          clearTimeout(timeout);
1498                          timeout = setTimeout(function() {
1499                              var size = getWindowSize();
1500                              $('#'+dialog_id).dialog('option', {
1501                                  width: size.width-10,
1502                                  height: size.height-10
1503                              });
1504                          }, 50);
1505                      });
1507                      var $wrapper = $('<div>', {'id': 'content-hide'}).hide();
1508                      $('body > *:not(.ui-dialog)').wrapAll($wrapper);
1510                      $(this)
1511                          .scrollTop(0) // for Chrome
1512                          .closest('.ui-dialog').css({
1513                              left: 0,
1514                              top: 0
1515                          });
1517                      PMA_verifyColumnsProperties();
1519                      // move the Cancel button next to the Save button
1520                      var $button_pane = $('.ui-dialog-buttonpane');
1521                      var $cancel_button = $button_pane.find('.ui-button');
1522                      var $save_button  = $('#create_table_form').find("input[name='do_save_data']");
1523                      $cancel_button.insertAfter($save_button);
1524                      $button_pane.hide();
1525                  },
1526                  close: function() {
1527                      $(window).unbind('resize.dialog-resizer');
1528                      $('#content-hide > *').unwrap();
1529                      // resize topmenu
1530                      menuResize();
1531                      menuResize(); // somehow need to call it twice to work
1532                  },
1533                  buttons: button_options
1534              }); // end dialog options
1535          }
1536         PMA_convertFootnotesToTooltips($div);
1537         PMA_ajaxRemoveMessage($msgbox);
1538      }); // end $.get()
1543  * Creates a Profiling Chart with jqplot. Used in sql.js
1544  * and in server_status_monitor.js
1545  */
1546 function PMA_createProfilingChartJqplot(target, data)
1548     return $.jqplot(target, [data],
1549         {
1550             seriesDefaults: {
1551                 renderer: $.jqplot.PieRenderer,
1552                 rendererOptions: {
1553                     showDataLabels:  true
1554                 }
1555             },
1556             legend: {
1557                 show: true,
1558                 location: 'e'
1559             },
1560             // from http://tango.freedesktop.org/Tango_Icon_Theme_Guidelines#Color_Palette
1561             seriesColors: [
1562              '#fce94f',
1563              '#fcaf3e',
1564              '#e9b96e',
1565              '#8ae234',
1566              '#729fcf',
1567              '#ad7fa8',
1568              '#ef2929',
1569              '#eeeeec',
1570              '#888a85',
1571              '#c4a000',
1572              '#ce5c00',
1573              '#8f5902',
1574              '#4e9a06',
1575              '#204a87',
1576              '#5c3566',
1577              '#a40000',
1578              '#babdb6',
1579              '#2e3436'
1580             ]
1581         }
1582     );
1586  * Formats a profiling duration nicely (in us and ms time). Used in server_status.js
1588  * @param   integer     Number to be formatted, should be in the range of microsecond to second
1589  * @param   integer     Acuracy, how many numbers right to the comma should be
1590  * @return  string      The formatted number
1591  */
1592 function PMA_prettyProfilingNum(num, acc)
1594     if (!acc) {
1595         acc = 2;
1596     }
1597     acc = Math.pow(10,acc);
1598     if (num * 1000 < 0.1) {
1599         num = Math.round(acc * (num * 1000 * 1000)) / acc + 'µ';
1600     } else if (num < 0.1) {
1601         num = Math.round(acc * (num * 1000)) / acc + 'm';
1602     } else {
1603         num = Math.round(acc * num) / acc;
1604     }
1606     return num + 's';
1611  * Formats a SQL Query nicely with newlines and indentation. Depends on Codemirror and MySQL Mode!
1613  * @param   string      Query to be formatted
1614  * @return  string      The formatted query
1615  */
1616 function PMA_SQLPrettyPrint(string)
1618     var mode = CodeMirror.getMode({},"text/x-mysql");
1619     var stream = new CodeMirror.StringStream(string);
1620     var state = mode.startState();
1621     var token, tokens = [];
1622     var output = '';
1623     var tabs = function(cnt) {
1624         var ret = '';
1625         for (var i=0; i<4*cnt; i++)
1626             ret += " ";
1627         return ret;
1628     };
1630     // "root-level" statements
1631     var statements = {
1632         'select': ['select', 'from','on','where','having','limit','order by','group by'],
1633         'update': ['update', 'set','where'],
1634         'insert into': ['insert into', 'values']
1635     };
1636     // don't put spaces before these tokens
1637     var spaceExceptionsBefore = { ';':true, ',': true, '.': true, '(': true };
1638     // don't put spaces after these tokens
1639     var spaceExceptionsAfter = { '.': true };
1641     // Populate tokens array
1642     var str='';
1643     while (! stream.eol()) {
1644         stream.start = stream.pos;
1645         token = mode.token(stream, state);
1646         if(token != null) {
1647             tokens.push([token, stream.current().toLowerCase()]);
1648         }
1649     }
1651     var currentStatement = tokens[0][1];
1653     if(! statements[currentStatement]) {
1654         return string;
1655     }
1656     // Holds all currently opened code blocks (statement, function or generic)
1657     var blockStack = [];
1658     // Holds the type of block from last iteration (the current is in blockStack[0])
1659     var previousBlock;
1660     // If a new code block is found, newBlock contains its type for one iteration and vice versa for endBlock
1661     var newBlock, endBlock;
1662     // How much to indent in the current line
1663     var indentLevel = 0;
1664     // Holds the "root-level" statements
1665     var statementPart, lastStatementPart = statements[currentStatement][0];
1667     blockStack.unshift('statement');
1669     // Iterate through every token and format accordingly
1670     for (var i = 0; i < tokens.length; i++) {
1671         previousBlock = blockStack[0];
1673         // New block => push to stack
1674         if (tokens[i][1] == '(') {
1675             if (i < tokens.length - 1 && tokens[i+1][0] == 'statement-verb') {
1676                 blockStack.unshift(newBlock = 'statement');
1677             } else if (i > 0 && tokens[i-1][0] == 'builtin') {
1678                 blockStack.unshift(newBlock = 'function');
1679             } else {
1680                 blockStack.unshift(newBlock = 'generic');
1681             }
1682         } else {
1683             newBlock = null;
1684         }
1686         // Block end => pop from stack
1687         if (tokens[i][1] == ')') {
1688             endBlock = blockStack[0];
1689             blockStack.shift();
1690         } else {
1691             endBlock = null;
1692         }
1694         // A subquery is starting
1695         if (i > 0 && newBlock == 'statement') {
1696             indentLevel++;
1697             output += "\n" + tabs(indentLevel) + tokens[i][1] + ' ' + tokens[i+1][1].toUpperCase() + "\n" + tabs(indentLevel + 1);
1698             currentStatement = tokens[i+1][1];
1699             i++;
1700             continue;
1701         }
1703         // A subquery is ending
1704         if (endBlock == 'statement' && indentLevel > 0) {
1705             output += "\n" + tabs(indentLevel);
1706             indentLevel--;
1707         }
1709         // One less indentation for statement parts (from, where, order by, etc.) and a newline
1710         statementPart = statements[currentStatement].indexOf(tokens[i][1]);
1711         if (statementPart != -1) {
1712             if (i > 0) output += "\n";
1713             output += tabs(indentLevel) + tokens[i][1].toUpperCase();
1714             output += "\n" + tabs(indentLevel + 1);
1715             lastStatementPart = tokens[i][1];
1716         }
1717         // Normal indentatin and spaces for everything else
1718         else {
1719             if (! spaceExceptionsBefore[tokens[i][1]]
1720                && ! (i > 0 && spaceExceptionsAfter[tokens[i-1][1]])
1721                && output.charAt(output.length -1) != ' ' ) {
1722                     output += " ";
1723             }
1724             if (tokens[i][0] == 'keyword') {
1725                 output += tokens[i][1].toUpperCase();
1726             } else {
1727                 output += tokens[i][1];
1728             }
1729         }
1731         // split columns in select and 'update set' clauses, but only inside statements blocks
1732         if (( lastStatementPart == 'select' || lastStatementPart == 'where'  || lastStatementPart == 'set')
1733             && tokens[i][1]==',' && blockStack[0] == 'statement') {
1735             output += "\n" + tabs(indentLevel + 1);
1736         }
1738         // split conditions in where clauses, but only inside statements blocks
1739         if (lastStatementPart == 'where'
1740             && (tokens[i][1]=='and' || tokens[i][1]=='or' || tokens[i][1]=='xor')) {
1742             if (blockStack[0] == 'statement') {
1743                 output += "\n" + tabs(indentLevel + 1);
1744             }
1745             // Todo: Also split and or blocks in newlines & identation++
1746             //if(blockStack[0] == 'generic')
1747              //   output += ...
1748         }
1749     }
1750     return output;
1754  * jQuery function that uses jQueryUI's dialogs to confirm with user. Does not
1755  *  return a jQuery object yet and hence cannot be chained
1757  * @param   string      question
1758  * @param   string      url         URL to be passed to the callbackFn to make
1759  *                                  an Ajax call to
1760  * @param   function    callbackFn  callback to execute after user clicks on OK
1761  */
1763 jQuery.fn.PMA_confirm = function(question, url, callbackFn) {
1764     if (PMA_messages['strDoYouReally'] == '') {
1765         return true;
1766     }
1768     /**
1769      *  @var    button_options  Object that stores the options passed to jQueryUI
1770      *                          dialog
1771      */
1772     var button_options = {};
1773     button_options[PMA_messages['strOK']] = function(){
1774                                                 $(this).dialog("close").remove();
1776                                                 if($.isFunction(callbackFn)) {
1777                                                     callbackFn.call(this, url);
1778                                                 }
1779                                             };
1780     button_options[PMA_messages['strCancel']] = function() {$(this).dialog("close").remove();}
1782     $('<div id="confirm_dialog"></div>')
1783     .prepend(question)
1784     .dialog({buttons: button_options});
1788  * jQuery function to sort a table's body after a new row has been appended to it.
1789  * Also fixes the even/odd classes of the table rows at the end.
1791  * @param   string      text_selector   string to select the sortKey's text
1793  * @return  jQuery Object for chaining purposes
1794  */
1795 jQuery.fn.PMA_sort_table = function(text_selector) {
1796     return this.each(function() {
1798         /**
1799          * @var table_body  Object referring to the table's <tbody> element
1800          */
1801         var table_body = $(this);
1802         /**
1803          * @var rows    Object referring to the collection of rows in {@link table_body}
1804          */
1805         var rows = $(this).find('tr').get();
1807         //get the text of the field that we will sort by
1808         $.each(rows, function(index, row) {
1809             row.sortKey = $.trim($(row).find(text_selector).text().toLowerCase());
1810         })
1812         //get the sorted order
1813         rows.sort(function(a,b) {
1814             if(a.sortKey < b.sortKey) {
1815                 return -1;
1816             }
1817             if(a.sortKey > b.sortKey) {
1818                 return 1;
1819             }
1820             return 0;
1821         })
1823         //pull out each row from the table and then append it according to it's order
1824         $.each(rows, function(index, row) {
1825             $(table_body).append(row);
1826             row.sortKey = null;
1827         })
1829         //Re-check the classes of each row
1830         $(this).find('tr:odd')
1831         .removeClass('even').addClass('odd')
1832         .end()
1833         .find('tr:even')
1834         .removeClass('odd').addClass('even');
1835     })
1839  * jQuery coding for 'Create Table'.  Used on db_operations.php,
1840  * db_structure.php and db_tracking.php (i.e., wherever
1841  * libraries/display_create_table.lib.php is used)
1843  * Attach Ajax Event handlers for Create Table
1844  */
1845 $(document).ready(function() {
1847      /**
1848      * Attach event handler to the submit action of the create table minimal form
1849      * and retrieve the full table form and display it in a dialog
1850      */
1851     $("#create_table_form_minimal.ajax").live('submit', function(event) {
1852         event.preventDefault();
1853         $form = $(this);
1854         PMA_prepareForAjaxRequest($form);
1856         /*variables which stores the common attributes*/
1857         var url = $form.serialize();
1858         var action = $form.attr('action');
1859         var $div =  $('<div id="create_table_dialog"></div>');
1861         /*Calling to the createTableDialog function*/
1862         PMA_createTableDialog($div, url, action);
1864         // empty table name and number of columns from the minimal form
1865         $form.find('input[name=table],input[name=num_fields]').val('');
1866     });
1868     /**
1869      * Attach event handler for submission of create table form (save)
1870      *
1871      * @uses    PMA_ajaxShowMessage()
1872      * @uses    $.PMA_sort_table()
1873      *
1874      */
1875     // .live() must be called after a selector, see http://api.jquery.com/live
1876     $("#create_table_form input[name=do_save_data]").live('click', function(event) {
1877         event.preventDefault();
1879         /**
1880          *  @var    the_form    object referring to the create table form
1881          */
1882         var $form = $("#create_table_form");
1884         /*
1885          * First validate the form; if there is a problem, avoid submitting it
1886          *
1887          * checkTableEditForm() needs a pure element and not a jQuery object,
1888          * this is why we pass $form[0] as a parameter (the jQuery object
1889          * is actually an array of DOM elements)
1890          */
1892         if (checkTableEditForm($form[0], $form.find('input[name=orig_num_fields]').val())) {
1893             // OK, form passed validation step
1894             if ($form.hasClass('ajax')) {
1895                 PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
1896                 PMA_prepareForAjaxRequest($form);
1897                 //User wants to submit the form
1898                 $.post($form.attr('action'), $form.serialize() + "&do_save_data=" + $(this).val(), function(data) {
1899                     if(data.success == true) {
1900                         $('#properties_message')
1901                          .removeClass('error')
1902                          .html('');
1903                         PMA_ajaxShowMessage(data.message);
1904                         // Only if the create table dialog (distinct panel) exists
1905                         if ($("#create_table_dialog").length > 0) {
1906                             $("#create_table_dialog").dialog("close").remove();
1907                         }
1909                         /**
1910                          * @var tables_table    Object referring to the <tbody> element that holds the list of tables
1911                          */
1912                         var tables_table = $("#tablesForm").find("tbody").not("#tbl_summary_row");
1913                         // this is the first table created in this db
1914                         if (tables_table.length == 0) {
1915                             if (window.parent && window.parent.frame_content) {
1916                                 window.parent.frame_content.location.reload();
1917                             }
1918                         } else {
1919                             /**
1920                              * @var curr_last_row   Object referring to the last <tr> element in {@link tables_table}
1921                              */
1922                             var curr_last_row = $(tables_table).find('tr:last');
1923                             /**
1924                              * @var curr_last_row_index_string   String containing the index of {@link curr_last_row}
1925                              */
1926                             var curr_last_row_index_string = $(curr_last_row).find('input:checkbox').attr('id').match(/\d+/)[0];
1927                             /**
1928                              * @var curr_last_row_index Index of {@link curr_last_row}
1929                              */
1930                             var curr_last_row_index = parseFloat(curr_last_row_index_string);
1931                             /**
1932                              * @var new_last_row_index   Index of the new row to be appended to {@link tables_table}
1933                              */
1934                             var new_last_row_index = curr_last_row_index + 1;
1935                             /**
1936                              * @var new_last_row_id String containing the id of the row to be appended to {@link tables_table}
1937                              */
1938                             var new_last_row_id = 'checkbox_tbl_' + new_last_row_index;
1940                             data.new_table_string = data.new_table_string.replace(/checkbox_tbl_/, new_last_row_id);
1941                             //append to table
1942                             $(data.new_table_string)
1943                              .appendTo(tables_table);
1945                             //Sort the table
1946                             $(tables_table).PMA_sort_table('th');
1948                             // Adjust summary row
1949                             PMA_adjustTotals();
1950                         }
1952                         //Refresh navigation frame as a new table has been added
1953                         if (window.parent && window.parent.frame_navigation) {
1954                             window.parent.frame_navigation.location.reload();
1955                         }
1956                     } else {
1957                         $('#properties_message')
1958                          .addClass('error')
1959                          .html(data.error);
1960                         // scroll to the div containing the error message
1961                         $('#properties_message')[0].scrollIntoView();
1962                     }
1963                 }) // end $.post()
1964             } // end if ($form.hasClass('ajax')
1965             else {
1966                 // non-Ajax submit
1967                 $form.append('<input type="hidden" name="do_save_data" value="save" />');
1968                 $form.submit();
1969             }
1970         } // end if (checkTableEditForm() )
1971     }) // end create table form (save)
1973     /**
1974      * Attach event handler for create table form (add fields)
1975      *
1976      * @uses    PMA_ajaxShowMessage()
1977      * @uses    $.PMA_sort_table()
1978      * @uses    window.parent.refreshNavigation()
1979      *
1980      */
1981     // .live() must be called after a selector, see http://api.jquery.com/live
1982     $("#create_table_form.ajax input[name=submit_num_fields]").live('click', function(event) {
1983         event.preventDefault();
1985         /**
1986          *  @var    the_form    object referring to the create table form
1987          */
1988         var $form = $("#create_table_form");
1990         var $msgbox = PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
1991         PMA_prepareForAjaxRequest($form);
1993         //User wants to add more fields to the table
1994         $.post($form.attr('action'), $form.serialize() + "&submit_num_fields=" + $(this).val(), function(data) {
1995             // if 'create_table_dialog' exists
1996             if ($("#create_table_dialog").length > 0) {
1997                 $("#create_table_dialog").html(data);
1998             }
1999             // if 'create_table_div' exists
2000             if ($("#create_table_div").length > 0) {
2001                 $("#create_table_div").html(data);
2002             }
2003             PMA_verifyColumnsProperties();
2004             PMA_ajaxRemoveMessage($msgbox);
2005         }) //end $.post()
2007     }) // end create table form (add fields)
2009 }, 'top.frame_content'); //end $(document).ready for 'Create Table'
2012  * jQuery coding for 'Table operations'.  Used on tbl_operations.php
2013  * Attach Ajax Event handlers for Table operations
2014  */
2015 $(document).ready(function() {
2016     /**
2017      *Ajax action for submitting the "Alter table order by"
2018     **/
2019     $("#alterTableOrderby.ajax").live('submit', function(event) {
2020         event.preventDefault();
2021         var $form = $(this);
2023         PMA_prepareForAjaxRequest($form);
2024         /*variables which stores the common attributes*/
2025         $.post($form.attr('action'), $form.serialize()+"&submitorderby=Go", function(data) {
2026             if ($("#sqlqueryresults").length != 0) {
2027                 $("#sqlqueryresults").remove();
2028             }
2029             if ($("#result_query").length != 0) {
2030                 $("#result_query").remove();
2031             }
2032             if (data.success == true) {
2033                 PMA_ajaxShowMessage(data.message);
2034                 $("<div id='sqlqueryresults'></div>").insertAfter("#floating_menubar");
2035                 $("#sqlqueryresults").html(data.sql_query);
2036                 $("#result_query .notice").remove();
2037                 $("#result_query").prepend((data.message));
2038             } else {
2039                 var $temp_div = $("<div id='temp_div'></div>")
2040                 $temp_div.html(data.error);
2041                 var $error = $temp_div.find("code").addClass("error");
2042                 PMA_ajaxShowMessage($error, false);
2043             }
2044         }) // end $.post()
2045     });//end of alterTableOrderby ajax submit
2047     /**
2048      *Ajax action for submitting the "Copy table"
2049     **/
2050     $("#copyTable.ajax input[name='submit_copy']").live('click', function(event) {
2051         event.preventDefault();
2052         var $form = $("#copyTable");
2053         if($form.find("input[name='switch_to_new']").attr('checked')) {
2054             $form.append('<input type="hidden" name="submit_copy" value="Go" />');
2055             $form.removeClass('ajax');
2056             $form.find("#ajax_request_hidden").remove();
2057             $form.submit();
2058         } else {
2059             PMA_prepareForAjaxRequest($form);
2060             /*variables which stores the common attributes*/
2061             $.post($form.attr('action'), $form.serialize()+"&submit_copy=Go", function(data) {
2062                 if ($("#sqlqueryresults").length != 0) {
2063                     $("#sqlqueryresults").remove();
2064                 }
2065                 if ($("#result_query").length != 0) {
2066                     $("#result_query").remove();
2067                 }
2068                 if (data.success == true) {
2069                     PMA_ajaxShowMessage(data.message);
2070                     $("<div id='sqlqueryresults'></div>").insertAfter("#floating_menubar");
2071                     $("#sqlqueryresults").html(data.sql_query);
2072                     $("#result_query .notice").remove();
2073                     $("#result_query").prepend((data.message));
2074                     $("#copyTable").find("select[name='target_db'] option").filterByValue(data.db).attr('selected', 'selected');
2076                     //Refresh navigation frame when the table is coppied
2077                     if (window.parent && window.parent.frame_navigation) {
2078                         window.parent.frame_navigation.location.reload();
2079                     }
2080                 } else {
2081                     var $temp_div = $("<div id='temp_div'></div>");
2082                     $temp_div.html(data.error);
2083                     var $error = $temp_div.find("code").addClass("error");
2084                     PMA_ajaxShowMessage($error, false);
2085                 }
2086             }) // end $.post()
2087         }
2088     });//end of copyTable ajax submit
2090     /**
2091      *Ajax events for actions in the "Table maintenance"
2092     **/
2093     $("#tbl_maintenance.ajax li a.maintain_action").live('click', function(event) {
2094         event.preventDefault();
2095         var $link = $(this);
2096         var href = $link.attr("href");
2097         href = href.split('?');
2098         if ($("#sqlqueryresults").length != 0) {
2099             $("#sqlqueryresults").remove();
2100         }
2101         if ($("#result_query").length != 0) {
2102             $("#result_query").remove();
2103         }
2104         //variables which stores the common attributes
2105         $.post(href[0], href[1]+"&ajax_request=true", function(data) {
2106             if (data.success == undefined) {
2107                 var $temp_div = $("<div id='temp_div'></div>");
2108                 $temp_div.html(data);
2109                 var $success = $temp_div.find("#result_query .success");
2110                 PMA_ajaxShowMessage($success);
2111                 $("<div id='sqlqueryresults' class='ajax'></div>").insertAfter("#floating_menubar");
2112                 $("#sqlqueryresults").html(data);
2113                 PMA_init_slider();
2114                 $("#sqlqueryresults").children("fieldset").remove();
2115             } else if (data.success == true ) {
2116                 PMA_ajaxShowMessage(data.message);
2117                 $("<div id='sqlqueryresults' class='ajax'></div>").insertAfter("#floating_menubar");
2118                 $("#sqlqueryresults").html(data.sql_query);
2119             } else {
2120                 var $temp_div = $("<div id='temp_div'></div>");
2121                 $temp_div.html(data.error);
2122                 var $error = $temp_div.find("code").addClass("error");
2123                 PMA_ajaxShowMessage($error, false);
2124             }
2125         }) // end $.post()
2126     });//end of table maintanance ajax click
2128 }, 'top.frame_content'); //end $(document).ready for 'Table operations'
2132  * Attach Ajax event handlers for Drop Database. Moved here from db_structure.js
2133  * as it was also required on db_create.php
2135  * @uses    $.PMA_confirm()
2136  * @uses    PMA_ajaxShowMessage()
2137  * @uses    window.parent.refreshNavigation()
2138  * @uses    window.parent.refreshMain()
2139  * @see $cfg['AjaxEnable']
2140  */
2141 $(document).ready(function() {
2142     $("#drop_db_anchor").live('click', function(event) {
2143         event.preventDefault();
2145         //context is top.frame_content, so we need to use window.parent.db to access the db var
2146         /**
2147          * @var question    String containing the question to be asked for confirmation
2148          */
2149         var question = PMA_messages['strDropDatabaseStrongWarning'] + '\n' + PMA_messages['strDoYouReally'] + ' :\n' + 'DROP DATABASE ' + escapeHtml(window.parent.db);
2151         $(this).PMA_confirm(question, $(this).attr('href') ,function(url) {
2153             PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
2154             $.get(url, {'is_js_confirmed': '1', 'ajax_request': true}, function(data) {
2155                 //Database deleted successfully, refresh both the frames
2156                 window.parent.refreshNavigation();
2157                 window.parent.refreshMain();
2158             }) // end $.get()
2159         }); // end $.PMA_confirm()
2160     }); //end of Drop Database Ajax action
2161 }) // end of $(document).ready() for Drop Database
2164  * Attach Ajax event handlers for 'Create Database'.  Used wherever libraries/
2165  * display_create_database.lib.php is used, ie main.php and server_databases.php
2167  * @uses    PMA_ajaxShowMessage()
2168  * @see $cfg['AjaxEnable']
2169  */
2170 $(document).ready(function() {
2172     $('#create_database_form.ajax').live('submit', function(event) {
2173         event.preventDefault();
2175         $form = $(this);
2177         PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
2178         PMA_prepareForAjaxRequest($form);
2180         $.post($form.attr('action'), $form.serialize(), function(data) {
2181             if(data.success == true) {
2182                 PMA_ajaxShowMessage(data.message);
2184                 //Append database's row to table
2185                 $("#tabledatabases")
2186                 .find('tbody')
2187                 .append(data.new_db_string)
2188                 .PMA_sort_table('.name')
2189                 .find('#db_summary_row')
2190                 .appendTo('#tabledatabases tbody')
2191                 .removeClass('odd even');
2193                 var $databases_count_object = $('#databases_count');
2194                 var databases_count = parseInt($databases_count_object.text());
2195                 $databases_count_object.text(++databases_count);
2196                 //Refresh navigation frame as a new database has been added
2197                 if (window.parent && window.parent.frame_navigation) {
2198                     window.parent.frame_navigation.location.reload();
2199                 }
2200             }
2201             else {
2202                 PMA_ajaxShowMessage(data.error, false);
2203             }
2204         }) // end $.post()
2205     }) // end $().live()
2206 })  // end $(document).ready() for Create Database
2209  * Validates the password field in a form
2211  * @see     PMA_messages['strPasswordEmpty']
2212  * @see     PMA_messages['strPasswordNotSame']
2213  * @param   object   the form
2214  * @return  boolean  whether the field value is valid or not
2215  */
2216 function checkPassword(the_form)
2218     // Did the user select 'no password'?
2219     if (typeof(the_form.elements['nopass']) != 'undefined'
2220      && the_form.elements['nopass'][0].checked) {
2221         return true;
2222     } else if (typeof(the_form.elements['pred_password']) != 'undefined'
2223      && (the_form.elements['pred_password'].value == 'none'
2224       || the_form.elements['pred_password'].value == 'keep')) {
2225         return true;
2226     }
2228     var password = the_form.elements['pma_pw'];
2229     var password_repeat = the_form.elements['pma_pw2'];
2230     var alert_msg = false;
2232     if (password.value == '') {
2233         alert_msg = PMA_messages['strPasswordEmpty'];
2234     } else if (password.value != password_repeat.value) {
2235         alert_msg = PMA_messages['strPasswordNotSame'];
2236     }
2238     if (alert_msg) {
2239         alert(alert_msg);
2240         password.value  = '';
2241         password_repeat.value = '';
2242         password.focus();
2243         return false;
2244     }
2246     return true;
2247 } // end of the 'checkPassword()' function
2250  * Attach Ajax event handlers for 'Change Password' on main.php
2251  */
2252 $(document).ready(function() {
2254     /**
2255      * Attach Ajax event handler on the change password anchor
2256      * @see $cfg['AjaxEnable']
2257      */
2258     $('#change_password_anchor.dialog_active').live('click',function(event) {
2259         event.preventDefault();
2260         return false;
2261         });
2262     $('#change_password_anchor.ajax').live('click', function(event) {
2263         event.preventDefault();
2264         $(this).removeClass('ajax').addClass('dialog_active');
2265         /**
2266          * @var button_options  Object containing options to be passed to jQueryUI's dialog
2267          */
2268         var button_options = {};
2269         button_options[PMA_messages['strCancel']] = function() {$(this).dialog('close').remove();}
2270         $.get($(this).attr('href'), {'ajax_request': true}, function(data) {
2271             $('<div id="change_password_dialog"></div>')
2272             .dialog({
2273                 title: PMA_messages['strChangePassword'],
2274                 width: 600,
2275                 close: function(ev,ui) {$(this).remove();},
2276                 buttons : button_options,
2277                 beforeClose: function(ev,ui){ $('#change_password_anchor.dialog_active').removeClass('dialog_active').addClass('ajax')}
2278             })
2279             .append(data);
2280             displayPasswordGenerateButton();
2282             $('#change_password_form').bind('submit', function (e) {
2283                 e.preventDefault();
2284                 $(this)
2285                     .closest('.ui-dialog')
2286                     .find('.ui-dialog-buttonpane .ui-button')
2287                     .first()
2288                     .click();
2289             });
2290         }) // end $.get()
2291     }) // end handler for change password anchor
2293     /**
2294      * Attach Ajax event handler for Change Password form submission
2295      *
2296      * @uses    PMA_ajaxShowMessage()
2297      * @see $cfg['AjaxEnable']
2298      */
2299     $("#change_password_form.ajax").find('input[name=change_pw]').live('click', function(event) {
2300         event.preventDefault();
2302         /**
2303          * @var the_form    Object referring to the change password form
2304          */
2305         var the_form = $("#change_password_form");
2307         if (! checkPassword(the_form[0])) {
2308             return false;
2309         }
2311         /**
2312          * @var this_value  String containing the value of the submit button.
2313          * Need to append this for the change password form on Server Privileges
2314          * page to work
2315          */
2316         var this_value = $(this).val();
2318         var $msgbox = PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
2319         $(the_form).append('<input type="hidden" name="ajax_request" value="true" />');
2321         $.post($(the_form).attr('action'), $(the_form).serialize() + '&change_pw='+ this_value, function(data) {
2322             if(data.success == true) {
2323                 $("#floating_menubar").after(data.sql_query);
2324                 $("#change_password_dialog").hide().remove();
2325                 $("#edit_user_dialog").dialog("close").remove();
2326                 $('#change_password_anchor.dialog_active').removeClass('dialog_active').addClass('ajax');
2327                 PMA_ajaxRemoveMessage($msgbox);
2328             }
2329             else {
2330                 PMA_ajaxShowMessage(data.error, false);
2331             }
2332         }) // end $.post()
2333     }) // end handler for Change Password form submission
2334 }) // end $(document).ready() for Change Password
2337  * Toggle the hiding/showing of the "Open in ENUM/SET editor" message when
2338  * the page loads and when the selected data type changes
2339  */
2340 $(document).ready(function() {
2341     // is called here for normal page loads and also when opening
2342     // the Create table dialog
2343     PMA_verifyColumnsProperties();
2344     //
2345     // needs live() to work also in the Create Table dialog
2346     $("select[class='column_type']").live('change', function() {
2347         PMA_showNoticeForEnum($(this));
2348     });
2349     $(".default_type").live('change', function() {
2350         PMA_hideShowDefaultValue($(this));
2351     });
2354 function PMA_verifyColumnsProperties()
2356     $("select[class='column_type']").each(function() {
2357         PMA_showNoticeForEnum($(this));
2358     });
2359     $(".default_type").each(function() {
2360         PMA_hideShowDefaultValue($(this));
2361     });
2365  * Hides/shows the default value input field, depending on the default type
2366  */
2367 function PMA_hideShowDefaultValue($default_type)
2369     if ($default_type.val() == 'USER_DEFINED') {
2370         $default_type.siblings('.default_value').show().focus();
2371     } else {
2372         $default_type.siblings('.default_value').hide();
2373     }
2377  * @var $enum_editor_dialog An object that points to the jQuery
2378  *                          dialog of the ENUM/SET editor
2379  */
2380 var $enum_editor_dialog = null;
2382  * Opens the ENUM/SET editor and controls its functions
2383  */
2384 $(document).ready(function() {
2385     $("a.open_enum_editor").live('click', function() {
2386         // Get the name of the column that is being edited
2387         var colname = $(this).closest('tr').find('input:first').val();
2388         // And use it to make up a title for the page
2389         if (colname.length < 1) {
2390             var title = PMA_messages['enum_newColumnVals'];
2391         } else {
2392             var title = PMA_messages['enum_columnVals'].replace(
2393                 /%s/,
2394                 '"' + decodeURIComponent(colname) + '"'
2395             );
2396         }
2397         // Get the values as a string
2398         var inputstring = $(this)
2399             .closest('td')
2400             .find("input")
2401             .val();
2402         // Escape html entities
2403         inputstring = $('<div/>')
2404             .text(inputstring)
2405             .html();
2406         // Parse the values, escaping quotes and
2407         // slashes on the fly, into an array
2408         //
2409         // There is a PHP port of the below parser in enum_editor.php
2410         // If you are fixing something here, you need to also update the PHP port.
2411         var values = [];
2412         var in_string = false;
2413         var curr, next, buffer = '';
2414         for (var i=0; i<inputstring.length; i++) {
2415             curr = inputstring.charAt(i);
2416             next = i == inputstring.length ? '' : inputstring.charAt(i+1);
2417             if (! in_string && curr == "'") {
2418                 in_string = true;
2419             } else if (in_string && curr == "\\" && next == "\\") {
2420                 buffer += "&#92;";
2421                 i++;
2422             } else if (in_string && next == "'" && (curr == "'" || curr == "\\")) {
2423                 buffer += "&#39;";
2424                 i++;
2425             } else if (in_string && curr == "'") {
2426                 in_string = false;
2427                 values.push(buffer);
2428                 buffer = '';
2429             } else if (in_string) {
2430                  buffer += curr;
2431             }
2432         }
2433         if (buffer.length > 0) {
2434             // The leftovers in the buffer are the last value (if any)
2435             values.push(buffer);
2436         }
2437         var fields = '';
2438         // If there are no values, maybe the user is about to make a
2439         // new list so we add a few for him/her to get started with.
2440         if (values.length == 0) {
2441             values.push('','','','');
2442         }
2443         // Add the parsed values to the editor
2444         var drop_icon = PMA_getImage('b_drop.png');
2445         for (var i=0; i<values.length; i++) {
2446             fields += "<tr><td>"
2447                    + "<input type='text' value='" + values[i] + "'/>"
2448                    + "</td><td class='drop'>"
2449                    + drop_icon
2450                    + "</td></tr>";
2451         }
2452         /**
2453          * @var dialog HTML code for the ENUM/SET dialog
2454          */
2455         var dialog = "<div id='enum_editor'>"
2456                    + "<fieldset>"
2457                    + "<legend>" + title + "</legend>"
2458                    + "<p>" + PMA_getImage('s_notice.png')
2459                    + PMA_messages['enum_hint'] + "</p>"
2460                    + "<table class='values'>" + fields + "</table>"
2461                    + "</fieldset><fieldset class='tblFooters'>"
2462                    + "<table class='add'><tr><td>"
2463                    + "<div class='slider'></div>"
2464                    + "</td><td>"
2465                    + "<form><div><input type='submit' class='add_value' value='"
2466                    + PMA_messages['enum_addValue'].replace(/%d/, 1)
2467                    + "'/></div></form>"
2468                    + "</td></tr></table>"
2469                    + "<input type='hidden' value='" // So we know which column's data is being edited
2470                    + $(this).closest('td').find("input").attr("id")
2471                    + "' />"
2472                    + "</fieldset>";
2473                    + "</div>";
2474         /**
2475          * @var  Defines functions to be called when the buttons in
2476          * the buttonOptions jQuery dialog bar are pressed
2477          */
2478         var buttonOptions = {};
2479         buttonOptions[PMA_messages['strGo']] = function () {
2480             // When the submit button is clicked,
2481             // put the data back into the original form
2482             var value_array = new Array();
2483             $(this).find(".values input").each(function(index, elm) {
2484                 var val = elm.value.replace(/\\/g, '\\\\').replace(/'/g, "''");
2485                 value_array.push("'" + val + "'");
2486             });
2487             // get the Length/Values text field where this value belongs
2488             var values_id = $(this).find("input[type='hidden']").attr("value");
2489             $("input[id='" + values_id + "']").attr("value", value_array.join(","));
2490             $(this).dialog("close");
2491         };
2492         buttonOptions[PMA_messages['strClose']] = function () {
2493             $(this).dialog("close");
2494         };
2495         // Show the dialog
2496         var width = parseInt(
2497             (parseInt($('html').css('font-size'), 10)/13)*340,
2498             10
2499         );
2500         if (! width) {
2501             width = 340;
2502         }
2503         $enum_editor_dialog = $(dialog).dialog({
2504             minWidth: width,
2505             modal: true,
2506             title: PMA_messages['enum_editor'],
2507             buttons: buttonOptions,
2508             open: function() {
2509                 // Focus the "Go" button after opening the dialog
2510                 $(this).closest('.ui-dialog').find('.ui-dialog-buttonpane button:first').focus();
2511             },
2512             close: function() {
2513                 $(this).remove();
2514             }
2515         });
2516         // slider for choosing how many fields to add
2517         $enum_editor_dialog.find(".slider").slider({
2518             animate: true,
2519             range: "min",
2520             value: 1,
2521             min: 1,
2522             max: 9,
2523             slide: function( event, ui ) {
2524                 $(this).closest('table').find('input[type=submit]').val(
2525                     PMA_messages['enum_addValue'].replace(/%d/, ui.value)
2526                 );
2527             }
2528         });
2529         // Focus the slider, otherwise it looks nearly transparent
2530         $('.ui-slider-handle').addClass('ui-state-focus');
2531         return false;
2532     });
2534     // When "add a new value" is clicked, append an empty text field
2535     $("input.add_value").live('click', function(e) {
2536         e.preventDefault();
2537         var num_new_rows = $enum_editor_dialog.find("div.slider").slider('value');
2538         while (num_new_rows--) {
2539             $enum_editor_dialog.find('.values')
2540                 .append(
2541                     "<tr style='display: none;'><td>"
2542                   + "<input type='text' />"
2543                   + "</td><td class='drop'>"
2544                   + PMA_getImage('b_drop.png')
2545                   + "</td></tr>"
2546                 )
2547                 .find('tr:last')
2548                 .show('fast');
2549         }
2550     });
2552     // Removes the specified row from the enum editor
2553     $("#enum_editor td.drop").live('click', function() {
2554         $(this).closest('tr').hide('fast', function () {
2555             $(this).remove();
2556         });
2557     });
2560 $(document).ready(function(){
2561     PMA_convertFootnotesToTooltips();
2565  * Ensures indexes names are valid according to their type and, for a primary
2566  * key, lock index name to 'PRIMARY'
2567  * @param   string   form_id  Variable which parses the form name as
2568  *                            the input
2569  * @return  boolean  false    if there is no index form, true else
2570  */
2571 function checkIndexName(form_id)
2573     if ($("#"+form_id).length == 0) {
2574         return false;
2575     }
2577     // Gets the elements pointers
2578     var $the_idx_name = $("#input_index_name");
2579     var $the_idx_type = $("#select_index_type");
2581     // Index is a primary key
2582     if ($the_idx_type.find("option:selected").attr("value") == 'PRIMARY') {
2583         $the_idx_name.attr("value", 'PRIMARY');
2584         $the_idx_name.attr("disabled", true);
2585     }
2587     // Other cases
2588     else {
2589         if ($the_idx_name.attr("value") == 'PRIMARY') {
2590             $the_idx_name.attr("value",  '');
2591         }
2592         $the_idx_name.attr("disabled", false);
2593     }
2595     return true;
2596 } // end of the 'checkIndexName()' function
2599  * function to convert the footnotes to tooltips
2601  * @param   jquery-Object   $div    a div jquery object which specifies the
2602  *                                  domain for searching footnootes. If we
2603  *                                  ommit this parameter the function searches
2604  *                                  the footnotes in the whole body
2605  **/
2606 function PMA_convertFootnotesToTooltips($div)
2608     // Hide the footnotes from the footer (which are displayed for
2609     // JavaScript-disabled browsers) since the tooltip is sufficient
2611     if ($div == undefined || ! $div instanceof jQuery || $div.length == 0) {
2612         $div = $("body");
2613     }
2615     $footnotes = $div.find(".footnotes");
2617     $footnotes.hide();
2618     $footnotes.find('span').each(function() {
2619         $(this).children("sup").remove();
2620     });
2621     // The border and padding must be removed otherwise a thin yellow box remains visible
2622     $footnotes.css("border", "none");
2623     $footnotes.css("padding", "0px");
2625     // Replace the superscripts with the help icon
2626     $div.find("sup.footnotemarker").hide();
2627     $div.find("img.footnotemarker").show();
2629     $div.find("img.footnotemarker").each(function() {
2630         var img_class = $(this).attr("class");
2631         /** img contains two classes, as example "footnotemarker footnote_1".
2632          *  We split it by second class and take it for the id of span
2633         */
2634         img_class = img_class.split(" ");
2635         for (i = 0; i < img_class.length; i++) {
2636             if (img_class[i].split("_")[0] == "footnote") {
2637                 var span_id = img_class[i].split("_")[1];
2638             }
2639         }
2640         /**
2641          * Now we get the #id of the span with span_id variable. As an example if we
2642          * initially get the img class as "footnotemarker footnote_2", now we get
2643          * #2 as the span_id. Using that we can find footnote_2 in footnotes.
2644          * */
2645         var tooltip_text = $footnotes.find("span[id='footnote_" + span_id + "']").html();
2646         $(this).qtip({
2647             content: tooltip_text,
2648             show: { delay: 0 },
2649             hide: { delay: 1000 },
2650             style: { background: '#ffffcc' }
2651         });
2652     });
2656  * This function handles the resizing of the content frame
2657  * and adjusts the top menu according to the new size of the frame
2658  */
2659 function menuResize()
2661     var $cnt = $('#topmenu');
2662     var wmax = $cnt.innerWidth() - 5; // 5 px margin for jumping menu in Chrome
2663     var $submenu = $cnt.find('.submenu');
2664     var submenu_w = $submenu.outerWidth(true);
2665     var $submenu_ul = $submenu.find('ul');
2666     var $li = $cnt.find('> li');
2667     var $li2 = $submenu_ul.find('li');
2668     var more_shown = $li2.length > 0;
2670     // Calculate the total width used by all the shown tabs
2671     var total_len = more_shown ? submenu_w : 0;
2672     for (var i = 0; i < $li.length-1; i++) {
2673         total_len += $($li[i]).outerWidth(true);
2674     }
2676     // Now hide menu elements that don't fit into the menubar
2677     var i = $li.length-1;
2678     var hidden = false; // Whether we have hidden any tabs
2679     while (total_len >= wmax && --i >= 0) { // Process the tabs backwards
2680         hidden = true;
2681         var el = $($li[i]);
2682         var el_width = el.outerWidth(true);
2683         el.data('width', el_width);
2684         if (! more_shown) {
2685             total_len -= el_width;
2686             el.prependTo($submenu_ul);
2687             total_len += submenu_w;
2688             more_shown = true;
2689         } else {
2690             total_len -= el_width;
2691             el.prependTo($submenu_ul);
2692         }
2693     }
2695     // If we didn't hide any tabs, then there might be some space to show some
2696     if (! hidden) {
2697         // Show menu elements that do fit into the menubar
2698         for (var i = 0; i < $li2.length; i++) {
2699             total_len += $($li2[i]).data('width');
2700             // item fits or (it is the last item
2701             // and it would fit if More got removed)
2702             if (total_len < wmax
2703                 || (i == $li2.length - 1 && total_len - submenu_w < wmax)
2704             ) {
2705                 $($li2[i]).insertBefore($submenu);
2706             } else {
2707                 break;
2708             }
2709         }
2710     }
2712     // Show/hide the "More" tab as needed
2713     if ($submenu_ul.find('li').length > 0) {
2714         $submenu.addClass('shown');
2715     } else {
2716         $submenu.removeClass('shown');
2717     }
2719     if ($cnt.find('> li').length == 1) {
2720         // If there is only the "More" tab left, then we need
2721         // to align the submenu to the left edge of the tab
2722         $submenu_ul.removeClass().addClass('only');
2723     } else {
2724         // Otherwise we align the submenu to the right edge of the tab
2725         $submenu_ul.removeClass().addClass('notonly');
2726     }
2728     if ($submenu.find('.tabactive').length) {
2729         $submenu.addClass('active').find('> a').removeClass('tab').addClass('tabactive');
2730     } else {
2731         $submenu.removeClass('active').find('> a').addClass('tab').removeClass('tabactive');
2732     }
2735 $(function() {
2736     var topmenu = $('#topmenu');
2737     if (topmenu.length == 0) {
2738         return;
2739     }
2740     // create submenu container
2741     var link = $('<a />', {href: '#', 'class': 'tab'})
2742         .text(PMA_messages['strMore'])
2743         .click(function(e) {
2744             e.preventDefault();
2745         });
2746     var img = topmenu.find('li:first-child img');
2747     if (img.length) {
2748         $(PMA_getImage('b_more.png').toString()).prependTo(link);
2749     }
2750     var submenu = $('<li />', {'class': 'submenu'})
2751         .append(link)
2752         .append($('<ul />'))
2753         .mouseenter(function() {
2754             if ($(this).find('ul .tabactive').length == 0) {
2755                 $(this).addClass('submenuhover').find('> a').addClass('tabactive');
2756             }
2757         })
2758         .mouseleave(function() {
2759             if ($(this).find('ul .tabactive').length == 0) {
2760                 $(this).removeClass('submenuhover').find('> a').removeClass('tabactive');
2761             }
2762         });
2763     topmenu.append(submenu);
2765     // populate submenu and register resize event
2766     menuResize();
2767     $(window).resize(menuResize);
2771  * Get the row number from the classlist (for example, row_1)
2772  */
2773 function PMA_getRowNumber(classlist)
2775     return parseInt(classlist.split(/\s+row_/)[1]);
2779  * Changes status of slider
2780  */
2781 function PMA_set_status_label($element)
2783     var text = $element.css('display') == 'none'
2784         ? '+ '
2785         : '- ';
2786     $element.closest('.slide-wrapper').prev().find('span').text(text);
2790  * Initializes slider effect.
2791  */
2792 function PMA_init_slider()
2794     $('.pma_auto_slider').each(function() {
2795         var $this = $(this);
2797         if ($this.hasClass('slider_init_done')) {
2798             return;
2799         }
2800         $this.addClass('slider_init_done');
2802         var $wrapper = $('<div>', {'class': 'slide-wrapper'});
2803         $wrapper.toggle($this.is(':visible'));
2804         $('<a>', {href: '#'+this.id})
2805             .text(this.title)
2806             .prepend($('<span>'))
2807             .insertBefore($this)
2808             .click(function() {
2809                 var $wrapper = $this.closest('.slide-wrapper');
2810                 var visible = $this.is(':visible');
2811                 if (!visible) {
2812                     $wrapper.show();
2813                 }
2814                 $this[visible ? 'hide' : 'show']('blind', function() {
2815                     $wrapper.toggle(!visible);
2816                     PMA_set_status_label($this);
2817                 });
2818                 return false;
2819             });
2820         $this.wrap($wrapper);
2821         PMA_set_status_label($this);
2822     });
2826  * var  toggleButton  This is a function that creates a toggle
2827  *                    sliding button given a jQuery reference
2828  *                    to the correct DOM element
2829  */
2830 var toggleButton = function ($obj) {
2831     // In rtl mode the toggle switch is flipped horizontally
2832     // so we need to take that into account
2833     if ($('.text_direction', $obj).text() == 'ltr') {
2834         var right = 'right';
2835     } else {
2836         var right = 'left';
2837     }
2838     /**
2839      *  var  h  Height of the button, used to scale the
2840      *          background image and position the layers
2841      */
2842     var h = $obj.height();
2843     $('img', $obj).height(h);
2844     $('table', $obj).css('bottom', h-1);
2845     /**
2846      *  var  on   Width of the "ON" part of the toggle switch
2847      *  var  off  Width of the "OFF" part of the toggle switch
2848      */
2849     var on  = $('.toggleOn', $obj).width();
2850     var off = $('.toggleOff', $obj).width();
2851     // Make the "ON" and "OFF" parts of the switch the same size
2852     // + 2 pixels to avoid overflowed
2853     $('.toggleOn > div', $obj).width(Math.max(on, off) + 2);
2854     $('.toggleOff > div', $obj).width(Math.max(on, off) + 2);
2855     /**
2856      *  var  w  Width of the central part of the switch
2857      */
2858     var w = parseInt(($('img', $obj).height() / 16) * 22, 10);
2859     // Resize the central part of the switch on the top
2860     // layer to match the background
2861     $('table td:nth-child(2) > div', $obj).width(w);
2862     /**
2863      *  var  imgw    Width of the background image
2864      *  var  tblw    Width of the foreground layer
2865      *  var  offset  By how many pixels to move the background
2866      *               image, so that it matches the top layer
2867      */
2868     var imgw = $('img', $obj).width();
2869     var tblw = $('table', $obj).width();
2870     var offset = parseInt(((imgw - tblw) / 2), 10);
2871     // Move the background to match the layout of the top layer
2872     $obj.find('img').css(right, offset);
2873     /**
2874      *  var  offw    Outer width of the "ON" part of the toggle switch
2875      *  var  btnw    Outer width of the central part of the switch
2876      */
2877     var offw = $('.toggleOff', $obj).outerWidth();
2878     var btnw = $('table td:nth-child(2)', $obj).outerWidth();
2879     // Resize the main div so that exactly one side of
2880     // the switch plus the central part fit into it.
2881     $obj.width(offw + btnw + 2);
2882     /**
2883      *  var  move  How many pixels to move the
2884      *             switch by when toggling
2885      */
2886     var move = $('.toggleOff', $obj).outerWidth();
2887     // If the switch is initialized to the
2888     // OFF state we need to move it now.
2889     if ($('.container', $obj).hasClass('off')) {
2890         if (right == 'right') {
2891             $('table, img', $obj).animate({'left': '-=' + move + 'px'}, 0);
2892         } else {
2893             $('table, img', $obj).animate({'left': '+=' + move + 'px'}, 0);
2894         }
2895     }
2896     // Attach an 'onclick' event to the switch
2897     $('.container', $obj).click(function () {
2898         if ($(this).hasClass('isActive')) {
2899             return false;
2900         } else {
2901             $(this).addClass('isActive');
2902         }
2903         var $msg = PMA_ajaxShowMessage();
2904         var $container = $(this);
2905         var callback = $('.callback', this).text();
2906         // Perform the actual toggle
2907         if ($(this).hasClass('on')) {
2908             if (right == 'right') {
2909                 var operator = '-=';
2910             } else {
2911                 var operator = '+=';
2912             }
2913             var url = $(this).find('.toggleOff > span').text();
2914             var removeClass = 'on';
2915             var addClass = 'off';
2916         } else {
2917             if (right == 'right') {
2918                 var operator = '+=';
2919             } else {
2920                 var operator = '-=';
2921             }
2922             var url = $(this).find('.toggleOn > span').text();
2923             var removeClass = 'off';
2924             var addClass = 'on';
2925         }
2926         $.post(url, {'ajax_request': true}, function(data) {
2927             if(data.success == true) {
2928                 PMA_ajaxRemoveMessage($msg);
2929                 $container
2930                 .removeClass(removeClass)
2931                 .addClass(addClass)
2932                 .animate({'left': operator + move + 'px'}, function () {
2933                     $container.removeClass('isActive');
2934                 });
2935                 eval(callback);
2936             } else {
2937                 PMA_ajaxShowMessage(data.error, false);
2938                 $container.removeClass('isActive');
2939             }
2940         });
2941     });
2945  * Initialise all toggle buttons
2946  */
2947 $(window).load(function () {
2948     $('.toggleAjax').each(function () {
2949         $(this)
2950         .show()
2951         .find('.toggleButton')
2952         toggleButton($(this));
2953     });
2957  * Vertical pointer
2958  */
2959 $(document).ready(function() {
2960     $('.vpointer').live('hover',
2961         //handlerInOut
2962         function(e) {
2963             var $this_td = $(this);
2964             var row_num = PMA_getRowNumber($this_td.attr('class'));
2965             // for all td of the same vertical row, toggle hover
2966             $('.vpointer').filter('.row_' + row_num).toggleClass('hover');
2967         }
2968         );
2969 }) // end of $(document).ready() for vertical pointer
2971 $(document).ready(function() {
2972     /**
2973      * Vertical marker
2974      */
2975     $('.vmarker').live('click', function(e) {
2976         // do not trigger when clicked on anchor
2977         if ($(e.target).is('a, img, a *')) {
2978             return;
2979         }
2981         var $this_td = $(this);
2982         var row_num = PMA_getRowNumber($this_td.attr('class'));
2984         // XXX: FF fires two click events for <label> (label and checkbox), so we need to handle this differently
2985         var $tr = $(this);
2986         var $checkbox = $('.vmarker').filter('.row_' + row_num + ':first').find(':checkbox');
2987         if ($checkbox.length) {
2988             // checkbox in a row, add or remove class depending on checkbox state
2989             var checked = $checkbox.attr('checked');
2990             if (!$(e.target).is(':checkbox, label')) {
2991                 checked = !checked;
2992                 $checkbox.attr('checked', checked);
2993             }
2994             // for all td of the same vertical row, toggle the marked class
2995             if (checked) {
2996                 $('.vmarker').filter('.row_' + row_num).addClass('marked');
2997             } else {
2998                 $('.vmarker').filter('.row_' + row_num).removeClass('marked');
2999             }
3000         } else {
3001             // normaln data table, just toggle class
3002             $('.vmarker').filter('.row_' + row_num).toggleClass('marked');
3003         }
3004     });
3006     /**
3007      * Reveal visual builder anchor
3008      */
3010     $('#visual_builder_anchor').show();
3012     /**
3013      * Page selector in db Structure (non-AJAX)
3014      */
3015     $('#tableslistcontainer').find('#pageselector').live('change', function() {
3016         $(this).parent("form").submit();
3017     });
3019     /**
3020      * Page selector in navi panel (non-AJAX)
3021      */
3022     $('#navidbpageselector').find('#pageselector').live('change', function() {
3023         $(this).parent("form").submit();
3024     });
3026     /**
3027      * Page selector in browse_foreigners windows (non-AJAX)
3028      */
3029     $('#body_browse_foreigners').find('#pageselector').live('change', function() {
3030         $(this).closest("form").submit();
3031     });
3033     /**
3034      * Load version information asynchronously.
3035      */
3036     if ($('.jsversioncheck').length > 0) {
3037         $.getJSON('http://www.phpmyadmin.net/home_page/version.json', {}, PMA_current_version);
3038     }
3040     /**
3041      * Slider effect.
3042      */
3043     PMA_init_slider();
3045     /**
3046      * Enables the text generated by PMA_linkOrButton() to be clickable
3047      */
3048     $('a[class~="formLinkSubmit"]').live('click',function(e) {
3050         if($(this).attr('href').indexOf('=') != -1) {
3051             var data = $(this).attr('href').substr($(this).attr('href').indexOf('#')+1).split('=',2);
3052             $(this).parents('form').append('<input type="hidden" name="' + data[0] + '" value="' + data[1] + '"/>');
3053         }
3054         $(this).parents('form').submit();
3055         return false;
3056     });
3058     $('#update_recent_tables').ready(function() {
3059         if (window.parent.frame_navigation != undefined
3060             && window.parent.frame_navigation.PMA_reloadRecentTable != undefined)
3061         {
3062             window.parent.frame_navigation.PMA_reloadRecentTable();
3063         }
3064     });
3066 }) // end of $(document).ready()
3069  * Creates a message inside an object with a sliding effect
3071  * @param   msg    A string containing the text to display
3072  * @param   $obj   a jQuery object containing the reference
3073  *                 to the element where to put the message
3074  *                 This is optional, if no element is
3075  *                 provided, one will be created below the
3076  *                 navigation links at the top of the page
3078  * @return  bool   True on success, false on failure
3079  */
3080 function PMA_slidingMessage(msg, $obj)
3082     if (msg == undefined || msg.length == 0) {
3083         // Don't show an empty message
3084         return false;
3085     }
3086     if ($obj == undefined || ! $obj instanceof jQuery || $obj.length == 0) {
3087         // If the second argument was not supplied,
3088         // we might have to create a new DOM node.
3089         if ($('#PMA_slidingMessage').length == 0) {
3090             $('#floating_menubar')
3091             .after('<span id="PMA_slidingMessage" '
3092                  + 'style="display: inline-block;"></span>');
3093         }
3094         $obj = $('#PMA_slidingMessage');
3095     }
3096     if ($obj.has('div').length > 0) {
3097         // If there already is a message inside the
3098         // target object, we must get rid of it
3099         $obj
3100         .find('div')
3101         .first()
3102         .fadeOut(function () {
3103             $obj
3104             .children()
3105             .remove();
3106             $obj
3107             .append('<div style="display: none;">' + msg + '</div>')
3108             .animate({
3109                 height: $obj.find('div').first().height()
3110             })
3111             .find('div')
3112             .first()
3113             .fadeIn();
3114         });
3115     } else {
3116         // Object does not already have a message
3117         // inside it, so we simply slide it down
3118         var h = $obj
3119                 .width('100%')
3120                 .html('<div style="display: none;">' + msg + '</div>')
3121                 .find('div')
3122                 .first()
3123                 .height();
3124         $obj
3125         .find('div')
3126         .first()
3127         .css('height', 0)
3128         .show()
3129         .animate({
3130                 height: h
3131             }, function() {
3132             // Set the height of the parent
3133             // to the height of the child
3134             $obj
3135             .height(
3136                 $obj
3137                 .find('div')
3138                 .first()
3139                 .height()
3140             );
3141         });
3142     }
3143     return true;
3144 } // end PMA_slidingMessage()
3147  * Attach Ajax event handlers for Drop Table.
3149  * @uses    $.PMA_confirm()
3150  * @uses    PMA_ajaxShowMessage()
3151  * @uses    window.parent.refreshNavigation()
3152  * @uses    window.parent.refreshMain()
3153  * @see $cfg['AjaxEnable']
3154  */
3155 $(document).ready(function() {
3156     $("#drop_tbl_anchor").live('click', function(event) {
3157         event.preventDefault();
3159         //context is top.frame_content, so we need to use window.parent.table to access the table var
3160         /**
3161          * @var question    String containing the question to be asked for confirmation
3162          */
3163         var question = PMA_messages['strDropTableStrongWarning'] + '\n' + PMA_messages['strDoYouReally'] + ' :\n' + 'DROP TABLE ' + escapeHtml(window.parent.table);
3165         $(this).PMA_confirm(question, $(this).attr('href') ,function(url) {
3167             PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
3168             $.get(url, {'is_js_confirmed': '1', 'ajax_request': true}, function(data) {
3169                 //Database deleted successfully, refresh both the frames
3170                 window.parent.refreshNavigation();
3171                 window.parent.refreshMain();
3172             }) // end $.get()
3173         }); // end $.PMA_confirm()
3174     }); //end of Drop Table Ajax action
3175 }) // end of $(document).ready() for Drop Table
3178  * Attach Ajax event handlers for Truncate Table.
3180  * @uses    $.PMA_confirm()
3181  * @uses    PMA_ajaxShowMessage()
3182  * @uses    window.parent.refreshNavigation()
3183  * @uses    window.parent.refreshMain()
3184  * @see $cfg['AjaxEnable']
3185  */
3186 $(document).ready(function() {
3187     $("#truncate_tbl_anchor.ajax").live('click', function(event) {
3188         event.preventDefault();
3190       //context is top.frame_content, so we need to use window.parent.table to access the table var
3191         /**
3192          * @var question    String containing the question to be asked for confirmation
3193          */
3194         var question = PMA_messages['strTruncateTableStrongWarning'] + '\n' + PMA_messages['strDoYouReally'] + ' :\n' + 'TRUNCATE TABLE ' + escapeHtml(window.parent.table);
3196         $(this).PMA_confirm(question, $(this).attr('href') ,function(url) {
3198             PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
3199             $.get(url, {'is_js_confirmed': '1', 'ajax_request': true}, function(data) {
3200                 if ($("#sqlqueryresults").length != 0) {
3201                     $("#sqlqueryresults").remove();
3202                 }
3203                 if ($("#result_query").length != 0) {
3204                     $("#result_query").remove();
3205                 }
3206                 if (data.success == true) {
3207                     PMA_ajaxShowMessage(data.message);
3208                     $("<div id='sqlqueryresults'></div>").insertAfter("#floating_menubar");
3209                     $("#sqlqueryresults").html(data.sql_query);
3210                 } else {
3211                     var $temp_div = $("<div id='temp_div'></div>")
3212                     $temp_div.html(data.error);
3213                     var $error = $temp_div.find("code").addClass("error");
3214                     PMA_ajaxShowMessage($error, false);
3215                 }
3216             }) // end $.get()
3217         }); // end $.PMA_confirm()
3218     }); //end of Truncate Table Ajax action
3219 }) // end of $(document).ready() for Truncate Table
3222  * Attach CodeMirror2 editor to SQL edit area.
3223  */
3224 $(document).ready(function() {
3225     var elm = $('#sqlquery');
3226     if (elm.length > 0 && typeof CodeMirror != 'undefined') {
3227         codemirror_editor = CodeMirror.fromTextArea(elm[0], {
3228             lineNumbers: true,
3229             matchBrackets: true,
3230             indentUnit: 4,
3231             mode: "text/x-mysql",
3232             lineWrapping: true
3233         });
3234     }
3238  * jQuery plugin to cancel selection in HTML code.
3239  */
3240 (function ($) {
3241     $.fn.noSelect = function (p) { //no select plugin by Paulo P.Marinas
3242         var prevent = (p == null) ? true : p;
3243         if (prevent) {
3244             return this.each(function () {
3245                 if ($.browser.msie || $.browser.safari) $(this).bind('selectstart', function () {
3246                     return false;
3247                 });
3248                 else if ($.browser.mozilla) {
3249                     $(this).css('MozUserSelect', 'none');
3250                     $('body').trigger('focus');
3251                 } else if ($.browser.opera) $(this).bind('mousedown', function () {
3252                     return false;
3253                 });
3254                 else $(this).attr('unselectable', 'on');
3255             });
3256         } else {
3257             return this.each(function () {
3258                 if ($.browser.msie || $.browser.safari) $(this).unbind('selectstart');
3259                 else if ($.browser.mozilla) $(this).css('MozUserSelect', 'inherit');
3260                 else if ($.browser.opera) $(this).unbind('mousedown');
3261                 else $(this).removeAttr('unselectable', 'on');
3262             });
3263         }
3264     }; //end noSelect
3265 })(jQuery);
3268  * jQuery plugin to correctly filter input fields by value, needed
3269  * because some nasty values may break selector syntax
3270  */
3271 (function ($) {
3272     $.fn.filterByValue = function (value) {
3273         return this.filter(function () {
3274             return $(this).val() === value
3275         });
3276     };
3277 })(jQuery);
3280  * Create default PMA tooltip for the element specified. The default appearance
3281  * can be overriden by specifying optional "options" parameter (see qTip options).
3282  */
3283 function PMA_createqTip($elements, content, options)
3285     if ($('#no_hint').length > 0) {
3286         return;
3287     }
3289     var o = {
3290         content: content,
3291         style: {
3292             classes: {
3293                 tooltip: 'normalqTip',
3294                 content: 'normalqTipContent'
3295             },
3296             name: 'dark'
3297         },
3298         position: {
3299             target: 'mouse',
3300             corner: { target: 'rightMiddle', tooltip: 'leftMiddle' },
3301             adjust: { x: 10, y: 20 }
3302         },
3303         show: {
3304             delay: 0,
3305             effect: {
3306                 type: 'grow',
3307                 length: 150
3308             }
3309         },
3310         hide: {
3311             effect: {
3312                 type: 'grow',
3313                 length: 200
3314             }
3315         }
3316     }
3318     $elements.qtip($.extend(true, o, options));
3322  * Return value of a cell in a table.
3323  */
3324 function PMA_getCellValue(td) {
3325     if ($(td).is('.null')) {
3326         return '';
3327     } else if (! $(td).is('.to_be_saved') && $(td).data('original_data')) {
3328         return $(td).data('original_data');
3329     } else {
3330         return $(td).text();
3331     }
3334 /* Loads a js file, an array may be passed as well */
3335 loadJavascript=function(file) {
3336     if($.isArray(file)) {
3337         for(var i=0; i<file.length; i++) {
3338             $('head').append('<script type="text/javascript" src="'+file[i]+'"></script>');
3339         }
3340     } else {
3341         $('head').append('<script type="text/javascript" src="'+file+'"></script>');
3342     }
3345 $(document).ready(function() {
3346     /**
3347      * Theme selector.
3348      */
3349     $('a.themeselect').live('click', function(e) {
3350         window.open(
3351             e.target,
3352             'themes',
3353             'left=10,top=20,width=510,height=350,scrollbars=yes,status=yes,resizable=yes'
3354             );
3355         return false;
3356     });
3358     /**
3359      * Automatic form submission on change.
3360      */
3361     $('.autosubmit').change(function(e) {
3362         e.target.form.submit();
3363     });
3365     /**
3366      * Theme changer.
3367      */
3368     $('.take_theme').click(function(e) {
3369         var what = this.name;
3370         if (window.opener && window.opener.document.forms['setTheme'].elements['set_theme']) {
3371             window.opener.document.forms['setTheme'].elements['set_theme'].value = what;
3372             window.opener.document.forms['setTheme'].submit();
3373             window.close();
3374             return false;
3375         }
3376         return true;
3377     });
3381  * Clear text selection
3382  */
3383 function PMA_clearSelection() {
3384     if(document.selection && document.selection.empty) {
3385         document.selection.empty();
3386     } else if(window.getSelection) {
3387         var sel = window.getSelection();
3388         if(sel.empty) sel.empty();
3389         if(sel.removeAllRanges) sel.removeAllRanges();
3390     }
3394  * HTML escaping
3395  */
3396 function escapeHtml(unsafe) {
3397     return unsafe
3398         .replace(/&/g, "&amp;")
3399         .replace(/</g, "&lt;")
3400         .replace(/>/g, "&gt;")
3401         .replace(/"/g, "&quot;")
3402         .replace(/'/g, "&#039;");
3406  * Print button
3407  */
3408 function printPage()
3410     // Do print the page
3411     if (typeof(window.print) != 'undefined') {
3412         window.print();
3413     }
3416 $(document).ready(function() {
3417     $('input#print').click(printPage);
3421  * Makes the breadcrumbs and the menu bar float at the top of the viewport
3422  */
3423 $(document).ready(function () {
3424     if ($("#floating_menubar").length && $('#PMA_disable_floating_menubar').length == 0) {
3425         $("#floating_menubar")
3426             .css({
3427                 'position': 'fixed',
3428                 'top': 0,
3429                 'left': 0,
3430                 'width': '100%',
3431                 'z-index': 500
3432             })
3433             .append($('#serverinfo'))
3434             .append($('#topmenucontainer'));
3435         $('body').css(
3436             'padding-top',
3437             $('#floating_menubar').outerHeight(true)
3438         );
3439     }
3443  * Toggles row colors of a set of 'tr' elements starting from a given element
3445  * @param $start Starting element
3446  */
3447 function toggleRowColors($start)
3449     for (var $curr_row = $start; $curr_row.length > 0; $curr_row = $curr_row.next()) {
3450         if ($curr_row.hasClass('odd')) {
3451             $curr_row.removeClass('odd').addClass('even');
3452         } else if ($curr_row.hasClass('even')) {
3453             $curr_row.removeClass('even').addClass('odd');
3454         }
3455     }