Fix broken inline edit
[phpmyadmin.git] / js / functions.js
blobcae7ed42df628de4c1dac178647685ef74dafbc3
1 /* vim: set expandtab sw=4 ts=4 sts=4: */
2 /**
3  * general function, usally 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  * Add a hidden field to the form to indicate that this will be an
34  * Ajax request (only if this hidden field does not exist)
35  *
36  * @param   object   the form
37  */
38 function PMA_prepareForAjaxRequest($form)
40     if (! $form.find('input:hidden').is('#ajax_request_hidden')) {
41         $form.append('<input type="hidden" id="ajax_request_hidden" name="ajax_request" value="true" />');
42     }
45 /**
46  * Generate a new password and copy it to the password input areas
47  *
48  * @param   object   the form that holds the password fields
49  *
50  * @return  boolean  always true
51  */
52 function suggestPassword(passwd_form)
54     // restrict the password to just letters and numbers to avoid problems:
55     // "editors and viewers regard the password as multiple words and
56     // things like double click no longer work"
57     var pwchars = "abcdefhjmnpqrstuvwxyz23456789ABCDEFGHJKLMNPQRSTUVWYXZ";
58     var passwordlength = 16;    // do we want that to be dynamic?  no, keep it simple :)
59     var passwd = passwd_form.generated_pw;
60     passwd.value = '';
62     for ( i = 0; i < passwordlength; i++ ) {
63         passwd.value += pwchars.charAt( Math.floor( Math.random() * pwchars.length ) )
64     }
65     passwd_form.text_pma_pw.value = passwd.value;
66     passwd_form.text_pma_pw2.value = passwd.value;
67     return true;
70 /**
71  * Version string to integer conversion.
72  */
73 function parseVersionString (str)
75     if (typeof(str) != 'string') { return false; }
76     var add = 0;
77     // Parse possible alpha/beta/rc/
78     var state = str.split('-');
79     if (state.length >= 2) {
80         if (state[1].substr(0, 2) == 'rc') {
81             add = - 20 - parseInt(state[1].substr(2));
82         } else if (state[1].substr(0, 4) == 'beta') {
83             add =  - 40 - parseInt(state[1].substr(4));
84         } else if (state[1].substr(0, 5) == 'alpha') {
85             add =  - 60 - parseInt(state[1].substr(5));
86         } else if (state[1].substr(0, 3) == 'dev') {
87             /* We don't handle dev, it's git snapshot */
88             add = 0;
89         }
90     }
91     // Parse version
92     var x = str.split('.');
93     // Use 0 for non existing parts
94     var maj = parseInt(x[0]) || 0;
95     var min = parseInt(x[1]) || 0;
96     var pat = parseInt(x[2]) || 0;
97     var hotfix = parseInt(x[3]) || 0;
98     return  maj * 100000000 + min * 1000000 + pat * 10000 + hotfix * 100 + add;
102  * Indicates current available version on main page.
103  */
104 function PMA_current_version()
106     var current = parseVersionString(pmaversion);
107     var latest = parseVersionString(PMA_latest_version);
108     var version_information_message = PMA_messages['strLatestAvailable'] + ' ' + PMA_latest_version;
109     if (latest > current) {
110         var message = $.sprintf(PMA_messages['strNewerVersion'], PMA_latest_version, PMA_latest_date);
111         if (Math.floor(latest / 10000) == Math.floor(current / 10000)) {
112             /* Security update */
113             klass = 'error';
114         } else {
115             klass = 'notice';
116         }
117         $('#maincontainer').after('<div class="' + klass + '">' + message + '</div>');
118     }
119     if (latest == current) {
120         version_information_message = ' (' + PMA_messages['strUpToDate'] + ')';
121     }
122     $('#li_pma_version').append(version_information_message);
126  * for libraries/display_change_password.lib.php
127  *     libraries/user_password.php
129  */
131 function displayPasswordGenerateButton()
133     $('#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>');
134     $('#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>');
138  * Adds a date/time picker to an element
140  * @param   object  $this_element   a jQuery object pointing to the element
141  */
142 function PMA_addDatepicker($this_element, options)
144     var showTimeOption = false;
145     if ($this_element.is('.datetimefield')) {
146         showTimeOption = true;
147     }
149     var defaultOptions = {
150         showOn: 'button',
151         buttonImage: themeCalendarImage, // defined in js/messages.php
152         buttonImageOnly: true,
153         stepMinutes: 1,
154         stepHours: 1,
155         showSecond: true,
156         showTimepicker: showTimeOption,
157         showButtonPanel: false,
158         dateFormat: 'yy-mm-dd', // yy means year with four digits
159         timeFormat: 'hh:mm:ss',
160         altFieldTimeOnly: false,
161         showAnim: '',
162         beforeShow: function(input, inst) {
163             // Remember that we came from the datepicker; this is used
164             // in tbl_change.js by verificationsAfterFieldChange()
165             $this_element.data('comes_from', 'datepicker');
167             // Fix wrong timepicker z-index, doesn't work without timeout
168             setTimeout(function() {
169                 $('#ui-timepicker-div').css('z-index',$('#ui-datepicker-div').css('z-index'))
170             },0);
171         }
172     };
174     $this_element.datetimepicker($.extend(defaultOptions, options));
178  * selects the content of a given object, f.e. a textarea
180  * @param   object  element     element of which the content will be selected
181  * @param   var     lock        variable which holds the lock for this element
182  *                              or true, if no lock exists
183  * @param   boolean only_once   if true this is only done once
184  *                              f.e. only on first focus
185  */
186 function selectContent( element, lock, only_once )
188     if ( only_once && only_once_elements[element.name] ) {
189         return;
190     }
192     only_once_elements[element.name] = true;
194     if ( lock  ) {
195         return;
196     }
198     element.select();
202  * Displays a confirmation box before to submit a "DROP/DELETE/ALTER" query.
203  * This function is called while clicking links
205  * @param   object   the link
206  * @param   object   the sql query to submit
208  * @return  boolean  whether to run the query or not
209  */
210 function confirmLink(theLink, theSqlQuery)
212     // Confirmation is not required in the configuration file
213     // or browser is Opera (crappy js implementation)
214     if (PMA_messages['strDoYouReally'] == '' || typeof(window.opera) != 'undefined') {
215         return true;
216     }
218     var is_confirmed = confirm(PMA_messages['strDoYouReally'] + ' :\n' + theSqlQuery);
219     if (is_confirmed) {
220         if ( $(theLink).hasClass('formLinkSubmit') ) {
221             var name = 'is_js_confirmed';
222             if ($(theLink).attr('href').indexOf('usesubform') != -1) {
223                 name = 'subform[' + $(theLink).attr('href').substr('#').match(/usesubform\[(\d+)\]/i)[1] + '][is_js_confirmed]';
224             }
226             $(theLink).parents('form').append('<input type="hidden" name="' + name + '" value="1" />');
227         } else if ( typeof(theLink.href) != 'undefined' ) {
228             theLink.href += '&is_js_confirmed=1';
229         } else if ( typeof(theLink.form) != 'undefined' ) {
230             theLink.form.action += '?is_js_confirmed=1';
231         }
232     }
234     return is_confirmed;
235 } // end of the 'confirmLink()' function
239  * Displays a confirmation box before doing some action
241  * @param   object   the message to display
243  * @return  boolean  whether to run the query or not
245  * @todo used only by libraries/display_tbl.lib.php. figure out how it is used
246  *       and replace with a jQuery equivalent
247  */
248 function confirmAction(theMessage)
250     // TODO: Confirmation is not required in the configuration file
251     // or browser is Opera (crappy js implementation)
252     if (typeof(window.opera) != 'undefined') {
253         return true;
254     }
256     var is_confirmed = confirm(theMessage);
258     return is_confirmed;
259 } // end of the 'confirmAction()' function
263  * Displays an error message if a "DROP DATABASE" statement is submitted
264  * while it isn't allowed, else confirms a "DROP/DELETE/ALTER" query before
265  * sumitting it if required.
266  * This function is called by the 'checkSqlQuery()' js function.
268  * @param   object   the form
269  * @param   object   the sql query textarea
271  * @return  boolean  whether to run the query or not
273  * @see     checkSqlQuery()
274  */
275 function confirmQuery(theForm1, sqlQuery1)
277     // Confirmation is not required in the configuration file
278     if (PMA_messages['strDoYouReally'] == '') {
279         return true;
280     }
282     // "DROP DATABASE" statement isn't allowed
283     if (PMA_messages['strNoDropDatabases'] != '') {
284         var drop_re = new RegExp('(^|;)\\s*DROP\\s+(IF EXISTS\\s+)?DATABASE\\s', 'i');
285         if (drop_re.test(sqlQuery1.value)) {
286             alert(PMA_messages['strNoDropDatabases']);
287             theForm1.reset();
288             sqlQuery1.focus();
289             return false;
290         } // end if
291     } // end if
293     // Confirms a "DROP/DELETE/ALTER/TRUNCATE" statement
294     //
295     // TODO: find a way (if possible) to use the parser-analyser
296     // for this kind of verification
297     // For now, I just added a ^ to check for the statement at
298     // beginning of expression
300     var do_confirm_re_0 = new RegExp('^\\s*DROP\\s+(IF EXISTS\\s+)?(TABLE|DATABASE|PROCEDURE)\\s', 'i');
301     var do_confirm_re_1 = new RegExp('^\\s*ALTER\\s+TABLE\\s+((`[^`]+`)|([A-Za-z0-9_$]+))\\s+DROP\\s', 'i');
302     var do_confirm_re_2 = new RegExp('^\\s*DELETE\\s+FROM\\s', 'i');
303     var do_confirm_re_3 = new RegExp('^\\s*TRUNCATE\\s', 'i');
305     if (do_confirm_re_0.test(sqlQuery1.value)
306         || do_confirm_re_1.test(sqlQuery1.value)
307         || do_confirm_re_2.test(sqlQuery1.value)
308         || do_confirm_re_3.test(sqlQuery1.value)) {
309         var message      = (sqlQuery1.value.length > 100)
310                          ? sqlQuery1.value.substr(0, 100) + '\n    ...'
311                          : sqlQuery1.value;
312         var is_confirmed = confirm(PMA_messages['strDoYouReally'] + ' :\n' + message);
313         // statement is confirmed -> update the
314         // "is_js_confirmed" form field so the confirm test won't be
315         // run on the server side and allows to submit the form
316         if (is_confirmed) {
317             theForm1.elements['is_js_confirmed'].value = 1;
318             return true;
319         }
320         // statement is rejected -> do not submit the form
321         else {
322             window.focus();
323             sqlQuery1.focus();
324             return false;
325         } // end if (handle confirm box result)
326     } // end if (display confirm box)
328     return true;
329 } // end of the 'confirmQuery()' function
333  * Displays a confirmation box before disabling the BLOB repository for a given database.
334  * This function is called while clicking links
336  * @param   object   the database
338  * @return  boolean  whether to disable the repository or not
339  */
340 function confirmDisableRepository(theDB)
342     // Confirmation is not required in the configuration file
343     // or browser is Opera (crappy js implementation)
344     if (PMA_messages['strDoYouReally'] == '' || typeof(window.opera) != 'undefined') {
345         return true;
346     }
348     var is_confirmed = confirm(PMA_messages['strBLOBRepositoryDisableStrongWarning'] + '\n' + PMA_messages['strBLOBRepositoryDisableAreYouSure']);
350     return is_confirmed;
351 } // end of the 'confirmDisableBLOBRepository()' function
355  * Displays an error message if the user submitted the sql query form with no
356  * sql query, else checks for "DROP/DELETE/ALTER" statements
358  * @param   object   the form
360  * @return  boolean  always false
362  * @see     confirmQuery()
363  */
364 function checkSqlQuery(theForm)
366     var sqlQuery = theForm.elements['sql_query'];
367     var isEmpty  = 1;
369     var space_re = new RegExp('\\s+');
370     if (typeof(theForm.elements['sql_file']) != 'undefined' &&
371             theForm.elements['sql_file'].value.replace(space_re, '') != '') {
372         return true;
373     }
374     if (typeof(theForm.elements['sql_localfile']) != 'undefined' &&
375             theForm.elements['sql_localfile'].value.replace(space_re, '') != '') {
376         return true;
377     }
378     if (isEmpty && typeof(theForm.elements['id_bookmark']) != 'undefined' &&
379             (theForm.elements['id_bookmark'].value != null || theForm.elements['id_bookmark'].value != '') &&
380             theForm.elements['id_bookmark'].selectedIndex != 0
381             ) {
382         return true;
383     }
384     // Checks for "DROP/DELETE/ALTER" statements
385     if (sqlQuery.value.replace(space_re, '') != '') {
386         if (confirmQuery(theForm, sqlQuery)) {
387             return true;
388         } else {
389             return false;
390         }
391     }
392     theForm.reset();
393     isEmpty = 1;
395     if (isEmpty) {
396         sqlQuery.select();
397         alert(PMA_messages['strFormEmpty']);
398         sqlQuery.focus();
399         return false;
400     }
402     return true;
403 } // end of the 'checkSqlQuery()' function
406  * Check if a form's element is empty.
407  * An element containing only spaces is also considered empty
409  * @param   object   the form
410  * @param   string   the name of the form field to put the focus on
412  * @return  boolean  whether the form field is empty or not
413  */
414 function emptyCheckTheField(theForm, theFieldName)
416     var theField = theForm.elements[theFieldName];
417     var space_re = new RegExp('\\s+');
418     return (theField.value.replace(space_re, '') == '') ? 1 : 0;
419 } // end of the 'emptyCheckTheField()' function
423  * Check whether a form field is empty or not
425  * @param   object   the form
426  * @param   string   the name of the form field to put the focus on
428  * @return  boolean  whether the form field is empty or not
429  */
430 function emptyFormElements(theForm, theFieldName)
432     var theField = theForm.elements[theFieldName];
433     var isEmpty = emptyCheckTheField(theForm, theFieldName);
436     return isEmpty;
437 } // end of the 'emptyFormElements()' function
441  * Ensures a value submitted in a form is numeric and is in a range
443  * @param   object   the form
444  * @param   string   the name of the form field to check
445  * @param   integer  the minimum authorized value
446  * @param   integer  the maximum authorized value
448  * @return  boolean  whether a valid number has been submitted or not
449  */
450 function checkFormElementInRange(theForm, theFieldName, message, min, max)
452     var theField         = theForm.elements[theFieldName];
453     var val              = parseInt(theField.value);
455     if (typeof(min) == 'undefined') {
456         min = 0;
457     }
458     if (typeof(max) == 'undefined') {
459         max = Number.MAX_VALUE;
460     }
462     // It's not a number
463     if (isNaN(val)) {
464         theField.select();
465         alert(PMA_messages['strNotNumber']);
466         theField.focus();
467         return false;
468     }
469     // It's a number but it is not between min and max
470     else if (val < min || val > max) {
471         theField.select();
472         alert(message.replace('%d', val));
473         theField.focus();
474         return false;
475     }
476     // It's a valid number
477     else {
478         theField.value = val;
479     }
480     return true;
482 } // end of the 'checkFormElementInRange()' function
485 function checkTableEditForm(theForm, fieldsCnt)
487     // TODO: avoid sending a message if user just wants to add a line
488     // on the form but has not completed at least one field name
490     var atLeastOneField = 0;
491     var i, elm, elm2, elm3, val, id;
493     for (i=0; i<fieldsCnt; i++)
494     {
495         id = "#field_" + i + "_2";
496         elm = $(id);
497         val = elm.val()
498         if (val == 'VARCHAR' || val == 'CHAR' || val == 'BIT' || val == 'VARBINARY' || val == 'BINARY') {
499             elm2 = $("#field_" + i + "_3");
500             val = parseInt(elm2.val());
501             elm3 = $("#field_" + i + "_1");
502             if (isNaN(val) && elm3.val() != "") {
503                 elm2.select();
504                 alert(PMA_messages['strNotNumber']);
505                 elm2.focus();
506                 return false;
507             }
508         }
510         if (atLeastOneField == 0) {
511             id = "field_" + i + "_1";
512             if (!emptyCheckTheField(theForm, id)) {
513                 atLeastOneField = 1;
514             }
515         }
516     }
517     if (atLeastOneField == 0) {
518         var theField = theForm.elements["field_0_1"];
519         alert(PMA_messages['strFormEmpty']);
520         theField.focus();
521         return false;
522     }
524     // at least this section is under jQuery
525     if ($("input.textfield[name='table']").val() == "") {
526         alert(PMA_messages['strFormEmpty']);
527         $("input.textfield[name='table']").focus();
528         return false;
529     }
532     return true;
533 } // enf of the 'checkTableEditForm()' function
537  * Ensures the choice between 'transmit', 'zipped', 'gzipped' and 'bzipped'
538  * checkboxes is consistant
540  * @param   object   the form
541  * @param   string   a code for the action that causes this function to be run
543  * @return  boolean  always true
544  */
545 function checkTransmitDump(theForm, theAction)
547     var formElts = theForm.elements;
549     // 'zipped' option has been checked
550     if (theAction == 'zip' && formElts['zip'].checked) {
551         if (!formElts['asfile'].checked) {
552             theForm.elements['asfile'].checked = true;
553         }
554         if (typeof(formElts['gzip']) != 'undefined' && formElts['gzip'].checked) {
555             theForm.elements['gzip'].checked = false;
556         }
557         if (typeof(formElts['bzip']) != 'undefined' && formElts['bzip'].checked) {
558             theForm.elements['bzip'].checked = false;
559         }
560     }
561     // 'gzipped' option has been checked
562     else if (theAction == 'gzip' && formElts['gzip'].checked) {
563         if (!formElts['asfile'].checked) {
564             theForm.elements['asfile'].checked = true;
565         }
566         if (typeof(formElts['zip']) != 'undefined' && formElts['zip'].checked) {
567             theForm.elements['zip'].checked = false;
568         }
569         if (typeof(formElts['bzip']) != 'undefined' && formElts['bzip'].checked) {
570             theForm.elements['bzip'].checked = false;
571         }
572     }
573     // 'bzipped' option has been checked
574     else if (theAction == 'bzip' && formElts['bzip'].checked) {
575         if (!formElts['asfile'].checked) {
576             theForm.elements['asfile'].checked = true;
577         }
578         if (typeof(formElts['zip']) != 'undefined' && formElts['zip'].checked) {
579             theForm.elements['zip'].checked = false;
580         }
581         if (typeof(formElts['gzip']) != 'undefined' && formElts['gzip'].checked) {
582             theForm.elements['gzip'].checked = false;
583         }
584     }
585     // 'transmit' option has been unchecked
586     else if (theAction == 'transmit' && !formElts['asfile'].checked) {
587         if (typeof(formElts['zip']) != 'undefined' && formElts['zip'].checked) {
588             theForm.elements['zip'].checked = false;
589         }
590         if ((typeof(formElts['gzip']) != 'undefined' && formElts['gzip'].checked)) {
591             theForm.elements['gzip'].checked = false;
592         }
593         if ((typeof(formElts['bzip']) != 'undefined' && formElts['bzip'].checked)) {
594             theForm.elements['bzip'].checked = false;
595         }
596     }
598     return true;
599 } // end of the 'checkTransmitDump()' function
601 $(document).ready(function() {
602     /**
603      * Row marking in horizontal mode (use "live" so that it works also for
604      * next pages reached via AJAX); a tr may have the class noclick to remove
605      * this behavior.
606      */
607     $('table:not(.noclick) tr.odd:not(.noclick), table:not(.noclick) tr.even:not(.noclick)').live('click',function(e) {
608         // do not trigger when clicked on anchor
609         if ($(e.target).is('a, img, a *')) {
610             return;
611         }
612         var $tr = $(this);
614         // make the table unselectable (to prevent default highlighting when shift+click)
615         //$tr.parents('table').noSelect();
617         if (!e.shiftKey || last_clicked_row == -1) {
618             // usual click
620             // XXX: FF fires two click events for <label> (label and checkbox), so we need to handle this differently
621             var $checkbox = $tr.find(':checkbox');
622             if ($checkbox.length) {
623                 // checkbox in a row, add or remove class depending on checkbox state
624                 var checked = $checkbox.attr('checked');
625                 if (!$(e.target).is(':checkbox, label')) {
626                     checked = !checked;
627                     $checkbox.attr('checked', checked);
628                 }
629                 if (checked) {
630                     $tr.addClass('marked');
631                 } else {
632                     $tr.removeClass('marked');
633                 }
634                 last_click_checked = checked;
635             } else {
636                 // normaln data table, just toggle class
637                 $tr.toggleClass('marked');
638                 last_click_checked = false;
639             }
641             // remember the last clicked row
642             last_clicked_row = last_click_checked ? $('tr.odd:not(.noclick), tr.even:not(.noclick)').index(this) : -1;
643             last_shift_clicked_row = -1;
644         } else {
645             // handle the shift click
646             PMA_clearSelection();
647             var start, end;
649             // clear last shift click result
650             if (last_shift_clicked_row >= 0) {
651                 if (last_shift_clicked_row >= last_clicked_row) {
652                     start = last_clicked_row;
653                     end = last_shift_clicked_row;
654                 } else {
655                     start = last_shift_clicked_row;
656                     end = last_clicked_row;
657                 }
658                 $tr.parent().find('tr.odd:not(.noclick), tr.even:not(.noclick)')
659                     .slice(start, end + 1)
660                     .removeClass('marked')
661                     .find(':checkbox')
662                     .attr('checked', false);
663             }
665             // handle new shift click
666             var curr_row = $('tr.odd:not(.noclick), tr.even:not(.noclick)').index(this);
667             if (curr_row >= last_clicked_row) {
668                 start = last_clicked_row;
669                 end = curr_row;
670             } else {
671                 start = curr_row;
672                 end = last_clicked_row;
673             }
674             $tr.parent().find('tr.odd:not(.noclick), tr.even:not(.noclick)')
675                 .slice(start, end + 1)
676                 .addClass('marked')
677                 .find(':checkbox')
678                 .attr('checked', true);
680             // remember the last shift clicked row
681             last_shift_clicked_row = curr_row;
682         }
683     });
685     /**
686      * Add a date/time picker to each element that needs it
687      * (only when timepicker.js is loaded)
688      */
689     if ($.timepicker != undefined) {
690         $('.datefield, .datetimefield').each(function() {
691             PMA_addDatepicker($(this));
692             });
693     }
697  * True if last click is to check a row.
698  */
699 var last_click_checked = false;
702  * Zero-based index of last clicked row.
703  * Used to handle the shift + click event in the code above.
704  */
705 var last_clicked_row = -1;
708  * Zero-based index of last shift clicked row.
709  */
710 var last_shift_clicked_row = -1;
713  * Row highlighting in horizontal mode (use "live"
714  * so that it works also for pages reached via AJAX)
715  */
716 /*$(document).ready(function() {
717     $('tr.odd, tr.even').live('hover',function(event) {
718         var $tr = $(this);
719         $tr.toggleClass('hover',event.type=='mouseover');
720         $tr.children().toggleClass('hover',event.type=='mouseover');
721     });
722 })*/
725  * This array is used to remember mark status of rows in browse mode
726  */
727 var marked_row = new Array;
730  * marks all rows and selects its first checkbox inside the given element
731  * the given element is usaly a table or a div containing the table or tables
733  * @param    container    DOM element
734  */
735 function markAllRows( container_id )
738     $("#"+container_id).find("input:checkbox:enabled").attr('checked', 'checked')
739     .parents("tr").addClass("marked");
740     return true;
744  * marks all rows and selects its first checkbox inside the given element
745  * the given element is usaly a table or a div containing the table or tables
747  * @param    container    DOM element
748  */
749 function unMarkAllRows( container_id )
752     $("#"+container_id).find("input:checkbox:enabled").removeAttr('checked')
753     .parents("tr").removeClass("marked");
754     return true;
758  * Checks/unchecks all checkbox in given conainer (f.e. a form, fieldset or div)
760  * @param   string   container_id  the container id
761  * @param   boolean  state         new value for checkbox (true or false)
762  * @return  boolean  always true
763  */
764 function setCheckboxes( container_id, state )
767     if(state) {
768         $("#"+container_id).find("input:checkbox").attr('checked', 'checked');
769     }
770     else {
771         $("#"+container_id).find("input:checkbox").removeAttr('checked');
772     }
774     return true;
775 } // end of the 'setCheckboxes()' function
778   * Checks/unchecks all options of a <select> element
779   *
780   * @param   string   the form name
781   * @param   string   the element name
782   * @param   boolean  whether to check or to uncheck options
783   *
784   * @return  boolean  always true
785   */
786 function setSelectOptions(the_form, the_select, do_check)
788     $("form[name='"+ the_form +"'] select[name='"+the_select+"']").find("option").attr('selected', do_check);
789     return true;
790 } // end of the 'setSelectOptions()' function
793  * Sets current value for query box.
794  */
795 function setQuery(query)
797     if (codemirror_editor) {
798         codemirror_editor.setValue(query);
799     } else {
800         document.sqlform.sql_query.value = query;
801     }
806   * Create quick sql statements.
807   *
808   */
809 function insertQuery(queryType)
811     if (queryType == "clear") {
812         setQuery('');
813         return;
814     }
816     var myQuery = document.sqlform.sql_query;
817     var query = "";
818     var myListBox = document.sqlform.dummy;
819     var table = document.sqlform.table.value;
821     if (myListBox.options.length > 0) {
822         sql_box_locked = true;
823         var chaineAj = "";
824         var valDis = "";
825         var editDis = "";
826         var NbSelect = 0;
827         for (var i=0; i < myListBox.options.length; i++) {
828             NbSelect++;
829             if (NbSelect > 1) {
830                 chaineAj += ", ";
831                 valDis += ",";
832                 editDis += ",";
833             }
834             chaineAj += myListBox.options[i].value;
835             valDis += "[value-" + NbSelect + "]";
836             editDis += myListBox.options[i].value + "=[value-" + NbSelect + "]";
837         }
838         if (queryType == "selectall") {
839             query = "SELECT * FROM `" + table + "` WHERE 1";
840         } else if (queryType == "select") {
841             query = "SELECT " + chaineAj + " FROM `" + table + "` WHERE 1";
842         } else if (queryType == "insert") {
843                query = "INSERT INTO `" + table + "`(" + chaineAj + ") VALUES (" + valDis + ")";
844         } else if (queryType == "update") {
845             query = "UPDATE `" + table + "` SET " + editDis + " WHERE 1";
846         } else if(queryType == "delete") {
847             query = "DELETE FROM `" + table + "` WHERE 1";
848         }
849         setQuery(query);
850         sql_box_locked = false;
851     }
856   * Inserts multiple fields.
857   *
858   */
859 function insertValueQuery()
861     var myQuery = document.sqlform.sql_query;
862     var myListBox = document.sqlform.dummy;
864     if(myListBox.options.length > 0) {
865         sql_box_locked = true;
866         var chaineAj = "";
867         var NbSelect = 0;
868         for(var i=0; i<myListBox.options.length; i++) {
869             if (myListBox.options[i].selected) {
870                 NbSelect++;
871                 if (NbSelect > 1) {
872                     chaineAj += ", ";
873                 }
874                 chaineAj += myListBox.options[i].value;
875             }
876         }
878         /* CodeMirror support */
879         if (codemirror_editor) {
880             codemirror_editor.replaceSelection(chaineAj);
881         //IE support
882         } else if (document.selection) {
883             myQuery.focus();
884             sel = document.selection.createRange();
885             sel.text = chaineAj;
886             document.sqlform.insert.focus();
887         }
888         //MOZILLA/NETSCAPE support
889         else if (document.sqlform.sql_query.selectionStart || document.sqlform.sql_query.selectionStart == "0") {
890             var startPos = document.sqlform.sql_query.selectionStart;
891             var endPos = document.sqlform.sql_query.selectionEnd;
892             var chaineSql = document.sqlform.sql_query.value;
894             myQuery.value = chaineSql.substring(0, startPos) + chaineAj + chaineSql.substring(endPos, chaineSql.length);
895         } else {
896             myQuery.value += chaineAj;
897         }
898         sql_box_locked = false;
899     }
903   * listbox redirection
904   */
905 function goToUrl(selObj, goToLocation)
907     eval("document.location.href = '" + goToLocation + "pos=" + selObj.options[selObj.selectedIndex].value + "'");
911   * Refresh the WYSIWYG scratchboard after changes have been made
912   */
913 function refreshDragOption(e)
915     var elm = $('#' + e);
916     if (elm.css('visibility') == 'visible') {
917         refreshLayout();
918         TableDragInit();
919     }
923   * Refresh/resize the WYSIWYG scratchboard
924   */
925 function refreshLayout()
927     var elm = $('#pdflayout')
928     var orientation = $('#orientation_opt').val();
929     if($('#paper_opt').length==1){
930         var paper = $('#paper_opt').val();
931     }else{
932         var paper = 'A4';
933     }
934     if (orientation == 'P') {
935         posa = 'x';
936         posb = 'y';
937     } else {
938         posa = 'y';
939         posb = 'x';
940     }
941     elm.css('width', pdfPaperSize(paper, posa) + 'px');
942     elm.css('height', pdfPaperSize(paper, posb) + 'px');
946   * Show/hide the WYSIWYG scratchboard
947   */
948 function ToggleDragDrop(e)
950     var elm = $('#' + e);
951     if (elm.css('visibility') == 'hidden') {
952         PDFinit(); /* Defined in pdf_pages.php */
953         elm.css('visibility', 'visible');
954         elm.css('display', 'block');
955         $('#showwysiwyg').val('1')
956     } else {
957         elm.css('visibility', 'hidden');
958         elm.css('display', 'none');
959         $('#showwysiwyg').val('0')
960     }
964   * PDF scratchboard: When a position is entered manually, update
965   * the fields inside the scratchboard.
966   */
967 function dragPlace(no, axis, value)
969     var elm = $('#table_' + no);
970     if (axis == 'x') {
971         elm.css('left', value + 'px');
972     } else {
973         elm.css('top', value + 'px');
974     }
978  * Returns paper sizes for a given format
979  */
980 function pdfPaperSize(format, axis)
982     switch (format.toUpperCase()) {
983         case '4A0':
984             if (axis == 'x') return 4767.87; else return 6740.79;
985             break;
986         case '2A0':
987             if (axis == 'x') return 3370.39; else return 4767.87;
988             break;
989         case 'A0':
990             if (axis == 'x') return 2383.94; else return 3370.39;
991             break;
992         case 'A1':
993             if (axis == 'x') return 1683.78; else return 2383.94;
994             break;
995         case 'A2':
996             if (axis == 'x') return 1190.55; else return 1683.78;
997             break;
998         case 'A3':
999             if (axis == 'x') return 841.89; else return 1190.55;
1000             break;
1001         case 'A4':
1002             if (axis == 'x') return 595.28; else return 841.89;
1003             break;
1004         case 'A5':
1005             if (axis == 'x') return 419.53; else return 595.28;
1006             break;
1007         case 'A6':
1008             if (axis == 'x') return 297.64; else return 419.53;
1009             break;
1010         case 'A7':
1011             if (axis == 'x') return 209.76; else return 297.64;
1012             break;
1013         case 'A8':
1014             if (axis == 'x') return 147.40; else return 209.76;
1015             break;
1016         case 'A9':
1017             if (axis == 'x') return 104.88; else return 147.40;
1018             break;
1019         case 'A10':
1020             if (axis == 'x') return 73.70; else return 104.88;
1021             break;
1022         case 'B0':
1023             if (axis == 'x') return 2834.65; else return 4008.19;
1024             break;
1025         case 'B1':
1026             if (axis == 'x') return 2004.09; else return 2834.65;
1027             break;
1028         case 'B2':
1029             if (axis == 'x') return 1417.32; else return 2004.09;
1030             break;
1031         case 'B3':
1032             if (axis == 'x') return 1000.63; else return 1417.32;
1033             break;
1034         case 'B4':
1035             if (axis == 'x') return 708.66; else return 1000.63;
1036             break;
1037         case 'B5':
1038             if (axis == 'x') return 498.90; else return 708.66;
1039             break;
1040         case 'B6':
1041             if (axis == 'x') return 354.33; else return 498.90;
1042             break;
1043         case 'B7':
1044             if (axis == 'x') return 249.45; else return 354.33;
1045             break;
1046         case 'B8':
1047             if (axis == 'x') return 175.75; else return 249.45;
1048             break;
1049         case 'B9':
1050             if (axis == 'x') return 124.72; else return 175.75;
1051             break;
1052         case 'B10':
1053             if (axis == 'x') return 87.87; else return 124.72;
1054             break;
1055         case 'C0':
1056             if (axis == 'x') return 2599.37; else return 3676.54;
1057             break;
1058         case 'C1':
1059             if (axis == 'x') return 1836.85; else return 2599.37;
1060             break;
1061         case 'C2':
1062             if (axis == 'x') return 1298.27; else return 1836.85;
1063             break;
1064         case 'C3':
1065             if (axis == 'x') return 918.43; else return 1298.27;
1066             break;
1067         case 'C4':
1068             if (axis == 'x') return 649.13; else return 918.43;
1069             break;
1070         case 'C5':
1071             if (axis == 'x') return 459.21; else return 649.13;
1072             break;
1073         case 'C6':
1074             if (axis == 'x') return 323.15; else return 459.21;
1075             break;
1076         case 'C7':
1077             if (axis == 'x') return 229.61; else return 323.15;
1078             break;
1079         case 'C8':
1080             if (axis == 'x') return 161.57; else return 229.61;
1081             break;
1082         case 'C9':
1083             if (axis == 'x') return 113.39; else return 161.57;
1084             break;
1085         case 'C10':
1086             if (axis == 'x') return 79.37; else return 113.39;
1087             break;
1088         case 'RA0':
1089             if (axis == 'x') return 2437.80; else return 3458.27;
1090             break;
1091         case 'RA1':
1092             if (axis == 'x') return 1729.13; else return 2437.80;
1093             break;
1094         case 'RA2':
1095             if (axis == 'x') return 1218.90; else return 1729.13;
1096             break;
1097         case 'RA3':
1098             if (axis == 'x') return 864.57; else return 1218.90;
1099             break;
1100         case 'RA4':
1101             if (axis == 'x') return 609.45; else return 864.57;
1102             break;
1103         case 'SRA0':
1104             if (axis == 'x') return 2551.18; else return 3628.35;
1105             break;
1106         case 'SRA1':
1107             if (axis == 'x') return 1814.17; else return 2551.18;
1108             break;
1109         case 'SRA2':
1110             if (axis == 'x') return 1275.59; else return 1814.17;
1111             break;
1112         case 'SRA3':
1113             if (axis == 'x') return 907.09; else return 1275.59;
1114             break;
1115         case 'SRA4':
1116             if (axis == 'x') return 637.80; else return 907.09;
1117             break;
1118         case 'LETTER':
1119             if (axis == 'x') return 612.00; else return 792.00;
1120             break;
1121         case 'LEGAL':
1122             if (axis == 'x') return 612.00; else return 1008.00;
1123             break;
1124         case 'EXECUTIVE':
1125             if (axis == 'x') return 521.86; else return 756.00;
1126             break;
1127         case 'FOLIO':
1128             if (axis == 'x') return 612.00; else return 936.00;
1129             break;
1130     } // end switch
1132     return 0;
1136  * for playing media from the BLOB repository
1138  * @param   var
1139  * @param   var     url_params  main purpose is to pass the token
1140  * @param   var     bs_ref      BLOB repository reference
1141  * @param   var     m_type      type of BLOB repository media
1142  * @param   var     w_width     width of popup window
1143  * @param   var     w_height    height of popup window
1144  */
1145 function popupBSMedia(url_params, bs_ref, m_type, is_cust_type, w_width, w_height)
1147     // if width not specified, use default
1148     if (w_width == undefined) {
1149         w_width = 640;
1150     }
1152     // if height not specified, use default
1153     if (w_height == undefined) {
1154         w_height = 480;
1155     }
1157     // open popup window (for displaying video/playing audio)
1158     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');
1162  * popups a request for changing MIME types for files in the BLOB repository
1164  * @param   var     db                      database name
1165  * @param   var     table                   table name
1166  * @param   var     reference               BLOB repository reference
1167  * @param   var     current_mime_type       current MIME type associated with BLOB repository reference
1168  */
1169 function requestMIMETypeChange(db, table, reference, current_mime_type)
1171     // no mime type specified, set to default (nothing)
1172     if (undefined == current_mime_type) {
1173         current_mime_type = "";
1174     }
1176     // prompt user for new mime type
1177     var new_mime_type = prompt("Enter custom MIME type", current_mime_type);
1179     // if new mime_type is specified and is not the same as the previous type, request for mime type change
1180     if (new_mime_type && new_mime_type != current_mime_type) {
1181         changeMIMEType(db, table, reference, new_mime_type);
1182     }
1186  * changes MIME types for files in the BLOB repository
1188  * @param   var     db              database name
1189  * @param   var     table           table name
1190  * @param   var     reference       BLOB repository reference
1191  * @param   var     mime_type       new MIME type to be associated with BLOB repository reference
1192  */
1193 function changeMIMEType(db, table, reference, mime_type)
1195     // specify url and parameters for jQuery POST
1196     var mime_chg_url = 'bs_change_mime_type.php';
1197     var params = {bs_db: db, bs_table: table, bs_reference: reference, bs_new_mime_type: mime_type};
1199     // jQuery POST
1200     jQuery.post(mime_chg_url, params);
1204  * Jquery Coding for inline editing SQL_QUERY
1205  */
1206 $(document).ready(function(){
1207     $(".inline_edit_sql").live('click', function(){
1208         var $form = $(this).prev();
1209         var sql_query  = $form.find("input[name='sql_query']").val();
1210         var $inner_sql = $(this).parent().prev().find('.inner_sql');
1211         var old_text   = $inner_sql.html();
1213         var new_content = "<textarea name=\"sql_query_edit\" id=\"sql_query_edit\">" + sql_query + "</textarea>\n";
1214         new_content    += "<input type=\"button\" class=\"btnSave\" value=\"" + PMA_messages['strGo'] + "\">\n";
1215         new_content    += "<input type=\"button\" class=\"btnDiscard\" value=\"" + PMA_messages['strCancel'] + "\">\n";
1216         $inner_sql.replaceWith(new_content);
1217         $(".btnSave").click(function(){
1218             var sql_query = $(this).prev().val();
1219             var $fake_form = $('<form>', {action: 'import.php', method: 'post'})
1220                     .append($form.find("input[name=server], input[name=db], input[name=table], input[name=token]").clone())
1221                     .append($('<input>', {type: 'hidden', name: 'show_query', value: 1}))
1222                     .append($('<input>', {type: 'hidden', name: 'sql_query', value: sql_query}));
1223             $fake_form.appendTo($('body')).submit();
1224         });
1225         $(".btnDiscard").click(function(){
1226             $(this).closest(".sql").html("<span class=\"syntax\"><span class=\"inner_sql\">" + old_text + "</span></span>");
1227         });
1228         return false;
1229     });
1231     $('.sqlbutton').click(function(evt){
1232         insertQuery(evt.target.id);
1233         return false;
1234     });
1236     $("#export_type").change(function(){
1237         if($("#export_type").val()=='svg'){
1238             $("#show_grid_opt").attr("disabled","disabled");
1239             $("#orientation_opt").attr("disabled","disabled");
1240             $("#with_doc").attr("disabled","disabled");
1241             $("#show_table_dim_opt").removeAttr("disabled");
1242             $("#all_table_same_wide").removeAttr("disabled");
1243             $("#paper_opt").removeAttr("disabled","disabled");
1244             $("#show_color_opt").removeAttr("disabled","disabled");
1245             //$(this).css("background-color","yellow");
1246         }else if($("#export_type").val()=='dia'){
1247             $("#show_grid_opt").attr("disabled","disabled");
1248             $("#with_doc").attr("disabled","disabled");
1249             $("#show_table_dim_opt").attr("disabled","disabled");
1250             $("#all_table_same_wide").attr("disabled","disabled");
1251             $("#paper_opt").removeAttr("disabled","disabled");
1252             $("#show_color_opt").removeAttr("disabled","disabled");
1253             $("#orientation_opt").removeAttr("disabled","disabled");
1254         }else if($("#export_type").val()=='eps'){
1255             $("#show_grid_opt").attr("disabled","disabled");
1256             $("#orientation_opt").removeAttr("disabled");
1257             $("#with_doc").attr("disabled","disabled");
1258             $("#show_table_dim_opt").attr("disabled","disabled");
1259             $("#all_table_same_wide").attr("disabled","disabled");
1260             $("#paper_opt").attr("disabled","disabled");
1261             $("#show_color_opt").attr("disabled","disabled");
1263         }else if($("#export_type").val()=='pdf'){
1264             $("#show_grid_opt").removeAttr("disabled");
1265             $("#orientation_opt").removeAttr("disabled");
1266             $("#with_doc").removeAttr("disabled","disabled");
1267             $("#show_table_dim_opt").removeAttr("disabled","disabled");
1268             $("#all_table_same_wide").removeAttr("disabled","disabled");
1269             $("#paper_opt").removeAttr("disabled","disabled");
1270             $("#show_color_opt").removeAttr("disabled","disabled");
1271         }else{
1272             // nothing
1273         }
1274     });
1276     $('#sqlquery').focus().keydown(function (e) {
1277         if (e.ctrlKey && e.keyCode == 13) {
1278             $("#sqlqueryform").submit();
1279         }
1280     });
1282     if ($('#input_username')) {
1283         if ($('#input_username').val() == '') {
1284             $('#input_username').focus();
1285         } else {
1286             $('#input_password').focus();
1287         }
1288     }
1292  * Show a message on the top of the page for an Ajax request
1294  * @param   var     message     string containing the message to be shown.
1295  *                              optional, defaults to 'Loading...'
1296  * @param   var     timeout     number of milliseconds for the message to be visible
1297  *                              optional, defaults to 5000
1298  * @return  jQuery object       jQuery Element that holds the message div
1299  */
1300 function PMA_ajaxShowMessage(message, timeout)
1303     //Handle the case when a empty data.message is passed. We don't want the empty message
1304     if (message == '') {
1305         return true;
1306     } else if (! message) {
1307         // If the message is undefined, show the default
1308         message = PMA_messages['strLoading'];
1309     }
1311     /**
1312      * @var timeout Number of milliseconds for which the message will be visible
1313      * @default 5000 ms
1314      */
1315     if (! timeout) {
1316         timeout = 5000;
1317     }
1319     // Create a parent element for the AJAX messages, if necessary
1320     if ($('#loading_parent').length == 0) {
1321         $('<div id="loading_parent"></div>')
1322         .insertBefore("#serverinfo");
1323     }
1325     // Update message count to create distinct message elements every time
1326     ajax_message_count++;
1328     // Remove all old messages, if any
1329     $(".ajax_notification[id^=ajax_message_num]").remove();
1331     /**
1332      * @var    $retval    a jQuery object containing the reference
1333      *                    to the created AJAX message
1334      */
1335     var $retval = $('<span class="ajax_notification" id="ajax_message_num_' + ajax_message_count + '"></span>')
1336         .hide()
1337         .appendTo("#loading_parent")
1338         .html(message)
1339         .fadeIn('medium')
1340         .delay(timeout)
1341         .fadeOut('medium', function() {
1342             $(this).remove();
1343         });
1345     return $retval;
1349  * Removes the message shown for an Ajax operation when it's completed
1350  */
1351 function PMA_ajaxRemoveMessage($this_msgbox)
1353     if ($this_msgbox != undefined && $this_msgbox instanceof jQuery) {
1354         $this_msgbox
1355         .stop(true, true)
1356         .fadeOut('medium');
1357     }
1361  * Hides/shows the "Open in ENUM/SET editor" message, depending on the data type of the column currently selected
1362  */
1363 function PMA_showNoticeForEnum(selectElement)
1365     var enum_notice_id = selectElement.attr("id").split("_")[1];
1366     enum_notice_id += "_" + (parseInt(selectElement.attr("id").split("_")[2]) + 1);
1367     var selectedType = selectElement.attr("value");
1368     if (selectedType == "ENUM" || selectedType == "SET") {
1369         $("p[id='enum_notice_" + enum_notice_id + "']").show();
1370     } else {
1371         $("p[id='enum_notice_" + enum_notice_id + "']").hide();
1372     }
1376  * Generates a dialog box to pop up the create_table form
1377  */
1378 function PMA_createTableDialog( div, url , target)
1380      /**
1381      *  @var    button_options  Object that stores the options passed to jQueryUI
1382      *                          dialog
1383      */
1384      var button_options = {};
1385      // in the following function we need to use $(this)
1386      button_options[PMA_messages['strCancel']] = function() {$(this).parent().dialog('close').remove();}
1388      var button_options_error = {};
1389      button_options_error[PMA_messages['strOK']] = function() {$(this).parent().dialog('close').remove();}
1391      var $msgbox = PMA_ajaxShowMessage();
1393      $.get( target , url ,  function(data) {
1394          //in the case of an error, show the error message returned.
1395          if (data.success != undefined && data.success == false) {
1396              div
1397              .append(data.error)
1398              .dialog({
1399                  title: PMA_messages['strCreateTable'],
1400                  height: 230,
1401                  width: 900,
1402                  open: PMA_verifyTypeOfAllColumns,
1403                  buttons : button_options_error
1404              })// end dialog options
1405              //remove the redundant [Back] link in the error message.
1406              .find('fieldset').remove();
1407          } else {
1408              div
1409              .append(data)
1410              .dialog({
1411                  title: PMA_messages['strCreateTable'],
1412                  height: 600,
1413                  width: 900,
1414                  open: PMA_verifyTypeOfAllColumns,
1415                  buttons : button_options
1416              }); // end dialog options
1417          }
1418          PMA_ajaxRemoveMessage($msgbox);
1419      }) // end $.get()
1424  * Creates a highcharts chart in the given container
1426  * @param   var     settings    object with highcharts properties that should be applied. (See also http://www.highcharts.com/ref/)
1427  *                              requires at least settings.chart.renderTo and settings.series to be set.
1428  *                              In addition there may be an additional property object 'realtime' that allows for realtime charting:
1429  *                              realtime: {
1430  *                                  url: adress to get the data from (will always add token, ajax_request=1 and chart_data=1 to the GET request)
1431  *                                  type: the GET request will also add type=[value of the type property] to the request
1432  *                                  callback: Callback function that should draw the point, it's called with 4 parameters in this order:
1433  *                                      - the chart object
1434  *                                      - the current response value of the GET request, JSON parsed
1435  *                                      - the previous response value of the GET request, JSON parsed
1436  *                                      - the number of added points
1437  *                                  error: Callback function when the get request fails. TODO: Apply callback on timeouts aswell
1438  *                              }
1440  * @return  object   The created highcharts instance
1441  */
1442 function PMA_createChart(passedSettings)
1444     var container = passedSettings.chart.renderTo;
1446     var settings = {
1447         chart: {
1448             type: 'spline',
1449             marginRight: 10,
1450             backgroundColor: 'none',
1451             events: {
1452                 /* Live charting support */
1453                 load: function() {
1454                     var thisChart = this;
1455                     var lastValue = null, curValue = null;
1456                     var numLoadedPoints = 0, otherSum = 0;
1457                     var diff;
1459                     // No realtime updates for graphs that are being exported, and disabled when realtime is not set
1460                     // Also don't do live charting if we don't have the server time
1461                     if(thisChart.options.chart.forExport == true ||
1462                         ! thisChart.options.realtime ||
1463                         ! thisChart.options.realtime.callback ||
1464                         ! server_time_diff) return;
1466                     thisChart.options.realtime.timeoutCallBack = function() {
1467                         thisChart.options.realtime.postRequest = $.post(
1468                             thisChart.options.realtime.url,
1469                             thisChart.options.realtime.postData,
1470                             function(data) {
1471                                 try {
1472                                     curValue = jQuery.parseJSON(data);
1473                                 } catch (err) {
1474                                     if(thisChart.options.realtime.error)
1475                                         thisChart.options.realtime.error(err);
1476                                     return;
1477                                 }
1479                                 if (lastValue==null) {
1480                                     diff = curValue.x - thisChart.xAxis[0].getExtremes().max;
1481                                 } else {
1482                                     diff = parseInt(curValue.x - lastValue.x);
1483                                 }
1485                                 thisChart.xAxis[0].setExtremes(
1486                                     thisChart.xAxis[0].getExtremes().min+diff,
1487                                     thisChart.xAxis[0].getExtremes().max+diff,
1488                                     false
1489                                 );
1491                                 thisChart.options.realtime.callback(thisChart,curValue,lastValue,numLoadedPoints);
1493                                 lastValue = curValue;
1494                                 numLoadedPoints++;
1496                                 // Timeout has been cleared => don't start a new timeout
1497                                 if (chart_activeTimeouts[container] == null) {
1498                                     return;
1499                                 }
1501                                 chart_activeTimeouts[container] = setTimeout(
1502                                     thisChart.options.realtime.timeoutCallBack,
1503                                     thisChart.options.realtime.refreshRate
1504                                 );
1505                         });
1506                     }
1508                     chart_activeTimeouts[container] = setTimeout(thisChart.options.realtime.timeoutCallBack, 5);
1509                 }
1510             }
1511         },
1512         plotOptions: {
1513             series: {
1514                 marker: {
1515                     radius: 3
1516                 }
1517             }
1518         },
1519         credits: {
1520             enabled:false
1521         },
1522         xAxis: {
1523             type: 'datetime'
1524         },
1525         yAxis: {
1526             min: 0,
1527             title: {
1528                 text: PMA_messages['strTotalCount']
1529             },
1530             plotLines: [{
1531                 value: 0,
1532                 width: 1,
1533                 color: '#808080'
1534             }]
1535         },
1536         tooltip: {
1537             formatter: function() {
1538                     return '<b>' + this.series.name +'</b><br/>' +
1539                     Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '<br/>' +
1540                     Highcharts.numberFormat(this.y, 2);
1541             }
1542         },
1543         exporting: {
1544             enabled: true
1545         },
1546         series: []
1547     }
1549     /* Set/Get realtime chart default values */
1550     if(passedSettings.realtime) {
1551         if(!passedSettings.realtime.refreshRate) {
1552             passedSettings.realtime.refreshRate = 5000;
1553         }
1555         if(!passedSettings.realtime.numMaxPoints) {
1556             passedSettings.realtime.numMaxPoints = 30;
1557         }
1559         // Allow custom POST vars to be added
1560         passedSettings.realtime.postData = $.extend(false,{ ajax_request: true, chart_data: 1, type: passedSettings.realtime.type },passedSettings.realtime.postData);
1562         if(server_time_diff) {
1563             settings.xAxis.min = new Date().getTime() - server_time_diff - passedSettings.realtime.numMaxPoints * passedSettings.realtime.refreshRate;
1564             settings.xAxis.max = new Date().getTime() - server_time_diff + passedSettings.realtime.refreshRate;
1565         }
1566     }
1568     // Overwrite/Merge default settings with passedsettings
1569     $.extend(true,settings,passedSettings);
1571     return new Highcharts.Chart(settings);
1576  * Creates a Profiling Chart. Used in sql.php and server_status.js
1577  */
1578 function PMA_createProfilingChart(data, options)
1580     return PMA_createChart($.extend(true, {
1581         chart: {
1582             renderTo: 'profilingchart',
1583             type: 'pie'
1584         },
1585         title: { text:'', margin:0 },
1586         series: [{
1587             type: 'pie',
1588             name: PMA_messages['strQueryExecutionTime'],
1589             data: data
1590         }],
1591         plotOptions: {
1592             pie: {
1593                 allowPointSelect: true,
1594                 cursor: 'pointer',
1595                 dataLabels: {
1596                     enabled: true,
1597                     distance: 35,
1598                     formatter: function() {
1599                         return '<b>'+ this.point.name +'</b><br/>'+ Highcharts.numberFormat(this.percentage, 2) +' %';
1600                    }
1601                 }
1602             }
1603         },
1604         tooltip: {
1605             formatter: function() {
1606                 return '<b>'+ this.point.name +'</b><br/>'+PMA_prettyProfilingNum(this.y)+'<br/>('+Highcharts.numberFormat(this.percentage, 2) +' %)';
1607             }
1608         }
1609     },options));
1613  * Formats a profiling duration nicely (in us and ms time). Used in PMA_createProfilingChart() and server_status.js
1615  * @param   integer     Number to be formatted, should be in the range of microsecond to second
1616  * @param   integer     Acuracy, how many numbers right to the comma should be
1617  * @return  string      The formatted number
1618  */
1619 function PMA_prettyProfilingNum(num, acc)
1621     if (!acc) {
1622         acc = 2;
1623     }
1624     acc = Math.pow(10,acc);
1625     if (num * 1000 < 0.1) {
1626         num = Math.round(acc * (num * 1000 * 1000)) / acc + 'µ';
1627     } else if (num < 0.1) {
1628         num = Math.round(acc * (num * 1000)) / acc + 'm';
1629     } else {
1630         num = Math.round(acc * num) / acc;
1631     }
1633     return num + 's';
1638  * Formats a SQL Query nicely with newlines and indentation. Depends on Codemirror and MySQL Mode!
1640  * @param   string      Query to be formatted
1641  * @return  string      The formatted query
1642  */
1643 function PMA_SQLPrettyPrint(string)
1645     var mode = CodeMirror.getMode({},"text/x-mysql");
1646     var stream = new CodeMirror.StringStream(string);
1647     var state = mode.startState();
1648     var token, tokens = [];
1649     var output = '';
1650     var tabs = function(cnt) {
1651         var ret = '';
1652         for (var i=0; i<4*cnt; i++)
1653             ret += " ";
1654         return ret;
1655     };
1657     // "root-level" statements
1658     var statements = {
1659         'select': ['select', 'from','on','where','having','limit','order by','group by'],
1660         'update': ['update', 'set','where'],
1661         'insert into': ['insert into', 'values']
1662     };
1663     // don't put spaces before these tokens
1664     var spaceExceptionsBefore = { ';':true, ',': true, '.': true, '(': true };
1665     // don't put spaces after these tokens
1666     var spaceExceptionsAfter = { '.': true };
1668     // Populate tokens array
1669     var str='';
1670     while (! stream.eol()) { 
1671         stream.start = stream.pos;
1672         token = mode.token(stream, state);
1673         if(token != null) {
1674             tokens.push([token, stream.current().toLowerCase()]);
1675         }
1676     }
1678     var currentStatement = tokens[0][1];
1680     if(! statements[currentStatement]) {
1681         return string;
1682     }
1683     // Holds all currently opened code blocks (statement, function or generic)
1684     var blockStack = [];
1685     // Holds the type of block from last iteration (the current is in blockStack[0])
1686     var previousBlock;
1687     // If a new code block is found, newBlock contains its type for one iteration and vice versa for endBlock
1688     var newBlock, endBlock;
1689     // How much to indent in the current line
1690     var indentLevel = 0;
1691     // Holds the "root-level" statements
1692     var statementPart, lastStatementPart = statements[currentStatement][0];
1694     blockStack.unshift('statement');
1696     // Iterate through every token and format accordingly
1697     for (var i = 0; i < tokens.length; i++) {
1698         previousBlock = blockStack[0];
1700         // New block => push to stack
1701         if (tokens[i][1] == '(') {
1702             if (i < tokens.length - 1 && tokens[i+1][0] == 'statement-verb') {
1703                 blockStack.unshift(newBlock = 'statement');
1704             } else if (i > 0 && tokens[i-1][0] == 'builtin') {
1705                 blockStack.unshift(newBlock = 'function');
1706             } else {
1707                 blockStack.unshift(newBlock = 'generic');
1708             }
1709         } else {
1710             newBlock = null;
1711         }
1713         // Block end => pop from stack
1714         if (tokens[i][1] == ')') {
1715             endBlock = blockStack[0];
1716             blockStack.shift();
1717         } else {
1718             endBlock = null;
1719         }
1721         // A subquery is starting
1722         if (i > 0 && newBlock == 'statement') {
1723             indentLevel++;
1724             output += "\n" + tabs(indentLevel) + tokens[i][1] + ' ' + tokens[i+1][1].toUpperCase() + "\n" + tabs(indentLevel + 1);
1725             currentStatement = tokens[i+1][1];
1726             i++;
1727             continue;
1728         }
1730         // A subquery is ending
1731         if (endBlock == 'statement' && indentLevel > 0) {
1732             output += "\n" + tabs(indentLevel);
1733             indentLevel--;
1734         }
1736         // One less indentation for statement parts (from, where, order by, etc.) and a newline
1737         statementPart = statements[currentStatement].indexOf(tokens[i][1]);
1738         if (statementPart != -1) {
1739             if (i > 0) output += "\n";
1740             output += tabs(indentLevel) + tokens[i][1].toUpperCase();
1741             output += "\n" + tabs(indentLevel + 1);
1742             lastStatementPart = tokens[i][1];
1743         }
1744         // Normal indentatin and spaces for everything else
1745         else {
1746             if (! spaceExceptionsBefore[tokens[i][1]] 
1747                && ! (i > 0 && spaceExceptionsAfter[tokens[i-1][1]])
1748                && output.charAt(output.length -1) != ' ' ) {
1749                     output += " ";
1750             }
1751             if (tokens[i][0] == 'keyword') {
1752                 output += tokens[i][1].toUpperCase();
1753             } else {
1754                 output += tokens[i][1];
1755             }
1756         }
1758         // split columns in select and 'update set' clauses, but only inside statements blocks
1759         if (( lastStatementPart == 'select' || lastStatementPart == 'where'  || lastStatementPart == 'set') 
1760             && tokens[i][1]==',' && blockStack[0] == 'statement') {
1762             output += "\n" + tabs(indentLevel + 1);
1763         }
1765         // split conditions in where clauses, but only inside statements blocks
1766         if (lastStatementPart == 'where' 
1767             && (tokens[i][1]=='and' || tokens[i][1]=='or' || tokens[i][1]=='xor')) {
1769             if (blockStack[0] == 'statement') {
1770                 output += "\n" + tabs(indentLevel + 1);
1771             }
1772             // Todo: Also split and or blocks in newlines & identation++
1773             //if(blockStack[0] == 'generic')
1774              //   output += ...
1775         }
1776     }
1777     return output;
1781  * jQuery function that uses jQueryUI's dialogs to confirm with user. Does not
1782  *  return a jQuery object yet and hence cannot be chained
1784  * @param   string      question
1785  * @param   string      url         URL to be passed to the callbackFn to make
1786  *                                  an Ajax call to
1787  * @param   function    callbackFn  callback to execute after user clicks on OK
1788  */
1790 jQuery.fn.PMA_confirm = function(question, url, callbackFn) {
1791     if (PMA_messages['strDoYouReally'] == '') {
1792         return true;
1793     }
1795     /**
1796      *  @var    button_options  Object that stores the options passed to jQueryUI
1797      *                          dialog
1798      */
1799     var button_options = {};
1800     button_options[PMA_messages['strOK']] = function(){
1801                                                 $(this).dialog("close").remove();
1803                                                 if($.isFunction(callbackFn)) {
1804                                                     callbackFn.call(this, url);
1805                                                 }
1806                                             };
1807     button_options[PMA_messages['strCancel']] = function() {$(this).dialog("close").remove();}
1809     $('<div id="confirm_dialog"></div>')
1810     .prepend(question)
1811     .dialog({buttons: button_options});
1815  * jQuery function to sort a table's body after a new row has been appended to it.
1816  * Also fixes the even/odd classes of the table rows at the end.
1818  * @param   string      text_selector   string to select the sortKey's text
1820  * @return  jQuery Object for chaining purposes
1821  */
1822 jQuery.fn.PMA_sort_table = function(text_selector) {
1823     return this.each(function() {
1825         /**
1826          * @var table_body  Object referring to the table's <tbody> element
1827          */
1828         var table_body = $(this);
1829         /**
1830          * @var rows    Object referring to the collection of rows in {@link table_body}
1831          */
1832         var rows = $(this).find('tr').get();
1834         //get the text of the field that we will sort by
1835         $.each(rows, function(index, row) {
1836             row.sortKey = $.trim($(row).find(text_selector).text().toLowerCase());
1837         })
1839         //get the sorted order
1840         rows.sort(function(a,b) {
1841             if(a.sortKey < b.sortKey) {
1842                 return -1;
1843             }
1844             if(a.sortKey > b.sortKey) {
1845                 return 1;
1846             }
1847             return 0;
1848         })
1850         //pull out each row from the table and then append it according to it's order
1851         $.each(rows, function(index, row) {
1852             $(table_body).append(row);
1853             row.sortKey = null;
1854         })
1856         //Re-check the classes of each row
1857         $(this).find('tr:odd')
1858         .removeClass('even').addClass('odd')
1859         .end()
1860         .find('tr:even')
1861         .removeClass('odd').addClass('even');
1862     })
1866  * jQuery coding for 'Create Table'.  Used on db_operations.php,
1867  * db_structure.php and db_tracking.php (i.e., wherever
1868  * libraries/display_create_table.lib.php is used)
1870  * Attach Ajax Event handlers for Create Table
1871  */
1872 $(document).ready(function() {
1874      /**
1875      * Attach event handler to the submit action of the create table minimal form
1876      * and retrieve the full table form and display it in a dialog
1877      *
1878      * @uses    PMA_ajaxShowMessage()
1879      */
1880     $("#create_table_form_minimal.ajax").live('submit', function(event) {
1881         event.preventDefault();
1882         $form = $(this);
1883         PMA_prepareForAjaxRequest($form);
1885         /*variables which stores the common attributes*/
1886         var url = $form.serialize();
1887         var action = $form.attr('action');
1888         var div =  $('<div id="create_table_dialog"></div>');
1890         /*Calling to the createTableDialog function*/
1891         PMA_createTableDialog(div, url, action);
1893         // empty table name and number of columns from the minimal form
1894         $form.find('input[name=table],input[name=num_fields]').val('');
1895     });
1897     /**
1898      * Attach event handler for submission of create table form (save)
1899      *
1900      * @uses    PMA_ajaxShowMessage()
1901      * @uses    $.PMA_sort_table()
1902      *
1903      */
1904     // .live() must be called after a selector, see http://api.jquery.com/live
1905     $("#create_table_form input[name=do_save_data]").live('click', function(event) {
1906         event.preventDefault();
1908         /**
1909          *  @var    the_form    object referring to the create table form
1910          */
1911         var $form = $("#create_table_form");
1913         /*
1914          * First validate the form; if there is a problem, avoid submitting it
1915          *
1916          * checkTableEditForm() needs a pure element and not a jQuery object,
1917          * this is why we pass $form[0] as a parameter (the jQuery object
1918          * is actually an array of DOM elements)
1919          */
1921         if (checkTableEditForm($form[0], $form.find('input[name=orig_num_fields]').val())) {
1922             // OK, form passed validation step
1923             if ($form.hasClass('ajax')) {
1924                 PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
1925                 PMA_prepareForAjaxRequest($form);
1926                 //User wants to submit the form
1927                 $.post($form.attr('action'), $form.serialize() + "&do_save_data=" + $(this).val(), function(data) {
1928                     if(data.success == true) {
1929                         $('#properties_message')
1930                          .removeClass('error')
1931                          .html('');
1932                         PMA_ajaxShowMessage(data.message);
1933                         // Only if the create table dialog (distinct panel) exists
1934                         if ($("#create_table_dialog").length > 0) {
1935                             $("#create_table_dialog").dialog("close").remove();
1936                         }
1938                         /**
1939                          * @var tables_table    Object referring to the <tbody> element that holds the list of tables
1940                          */
1941                         var tables_table = $("#tablesForm").find("tbody").not("#tbl_summary_row");
1942                         // this is the first table created in this db
1943                         if (tables_table.length == 0) {
1944                             if (window.parent && window.parent.frame_content) {
1945                                 window.parent.frame_content.location.reload();
1946                             }
1947                         } else {
1948                             /**
1949                              * @var curr_last_row   Object referring to the last <tr> element in {@link tables_table}
1950                              */
1951                             var curr_last_row = $(tables_table).find('tr:last');
1952                             /**
1953                              * @var curr_last_row_index_string   String containing the index of {@link curr_last_row}
1954                              */
1955                             var curr_last_row_index_string = $(curr_last_row).find('input:checkbox').attr('id').match(/\d+/)[0];
1956                             /**
1957                              * @var curr_last_row_index Index of {@link curr_last_row}
1958                              */
1959                             var curr_last_row_index = parseFloat(curr_last_row_index_string);
1960                             /**
1961                              * @var new_last_row_index   Index of the new row to be appended to {@link tables_table}
1962                              */
1963                             var new_last_row_index = curr_last_row_index + 1;
1964                             /**
1965                              * @var new_last_row_id String containing the id of the row to be appended to {@link tables_table}
1966                              */
1967                             var new_last_row_id = 'checkbox_tbl_' + new_last_row_index;
1969                             data.new_table_string = data.new_table_string.replace(/checkbox_tbl_/, new_last_row_id);
1970                             //append to table
1971                             $(data.new_table_string)
1972                              .appendTo(tables_table);
1974                             //Sort the table
1975                             $(tables_table).PMA_sort_table('th');
1976                         }
1978                         //Refresh navigation frame as a new table has been added
1979                         if (window.parent && window.parent.frame_navigation) {
1980                             window.parent.frame_navigation.location.reload();
1981                         }
1982                     } else {
1983                         $('#properties_message')
1984                          .addClass('error')
1985                          .html(data.error);
1986                         // scroll to the div containing the error message
1987                         $('#properties_message')[0].scrollIntoView();
1988                     }
1989                 }) // end $.post()
1990             } // end if ($form.hasClass('ajax')
1991             else {
1992                 // non-Ajax submit
1993                 $form.append('<input type="hidden" name="do_save_data" value="save" />');
1994                 $form.submit();
1995             }
1996         } // end if (checkTableEditForm() )
1997     }) // end create table form (save)
1999     /**
2000      * Attach event handler for create table form (add fields)
2001      *
2002      * @uses    PMA_ajaxShowMessage()
2003      * @uses    $.PMA_sort_table()
2004      * @uses    window.parent.refreshNavigation()
2005      *
2006      */
2007     // .live() must be called after a selector, see http://api.jquery.com/live
2008     $("#create_table_form.ajax input[name=submit_num_fields]").live('click', function(event) {
2009         event.preventDefault();
2011         /**
2012          *  @var    the_form    object referring to the create table form
2013          */
2014         var $form = $("#create_table_form");
2016         var $msgbox = PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
2017         PMA_prepareForAjaxRequest($form);
2019         //User wants to add more fields to the table
2020         $.post($form.attr('action'), $form.serialize() + "&submit_num_fields=" + $(this).val(), function(data) {
2021             // if 'create_table_dialog' exists
2022             if ($("#create_table_dialog").length > 0) {
2023                 $("#create_table_dialog").html(data);
2024             }
2025             // if 'create_table_div' exists
2026             if ($("#create_table_div").length > 0) {
2027                 $("#create_table_div").html(data);
2028             }
2029             PMA_verifyTypeOfAllColumns();
2030             PMA_ajaxRemoveMessage($msgbox);
2031         }) //end $.post()
2033     }) // end create table form (add fields)
2035 }, 'top.frame_content'); //end $(document).ready for 'Create Table'
2038  * jQuery coding for 'Change Table' and 'Add Column'.  Used on tbl_structure.php *
2039  * Attach Ajax Event handlers for Change Table
2040  */
2041 $(document).ready(function() {
2042     /**
2043      *Ajax action for submitting the "Column Change" and "Add Column" form
2044     **/
2045     $("#append_fields_form input[name=do_save_data]").live('click', function(event) {
2046         event.preventDefault();
2047         /**
2048          *  @var    the_form    object referring to the export form
2049          */
2050         var $form = $("#append_fields_form");
2052         /*
2053          * First validate the form; if there is a problem, avoid submitting it
2054          *
2055          * checkTableEditForm() needs a pure element and not a jQuery object,
2056          * this is why we pass $form[0] as a parameter (the jQuery object
2057          * is actually an array of DOM elements)
2058          */
2059         if (checkTableEditForm($form[0], $form.find('input[name=orig_num_fields]').val())) {
2060             // OK, form passed validation step
2061             if ($form.hasClass('ajax')) {
2062                 PMA_prepareForAjaxRequest($form);
2063                 //User wants to submit the form
2064                 $.post($form.attr('action'), $form.serialize()+"&do_save_data=Save", function(data) {
2065                     if ($("#sqlqueryresults").length != 0) {
2066                         $("#sqlqueryresults").remove();
2067                     } else if ($(".error").length != 0) {
2068                         $(".error").remove();
2069                     }
2070                     if (data.success == true) {
2071                         PMA_ajaxShowMessage(data.message);
2072                         $("<div id='sqlqueryresults'></div>").insertAfter("#topmenucontainer");
2073                         $("#sqlqueryresults").html(data.sql_query);
2074                         $("#result_query .notice").remove();
2075                         $("#result_query").prepend((data.message));
2076                         if ($("#change_column_dialog").length > 0) {
2077                             $("#change_column_dialog").dialog("close").remove();
2078                         } else if ($("#add_columns").length > 0) {
2079                             $("#add_columns").dialog("close").remove();
2080                         }
2081                         /*Reload the field form*/
2082                         $.post($("#fieldsForm").attr('action'), $("#fieldsForm").serialize()+"&ajax_request=true", function(form_data) {
2083                             $("#fieldsForm").remove();
2084                             $("#addColumns").remove();
2085                             var $temp_div = $("<div id='temp_div'><div>").append(form_data);
2086                             if ($("#sqlqueryresults").length != 0) {
2087                                 $temp_div.find("#fieldsForm").insertAfter("#sqlqueryresults");
2088                             } else {
2089                                 $temp_div.find("#fieldsForm").insertAfter(".error");
2090                             }
2091                             $temp_div.find("#addColumns").insertBefore("iframe.IE_hack");
2092                             /*Call the function to display the more options in table*/
2093                             displayMoreTableOpts();
2094                         });
2095                     } else {
2096                         var $temp_div = $("<div id='temp_div'><div>").append(data);
2097                         var $error = $temp_div.find(".error code").addClass("error");
2098                         PMA_ajaxShowMessage($error);
2099                     }
2100                 }) // end $.post()
2101             } else {
2102                 // non-Ajax submit
2103                 $form.append('<input type="hidden" name="do_save_data" value="Save" />');
2104                 $form.submit();
2105             }
2106         }
2107     }) // end change table button "do_save_data"
2109 }, 'top.frame_content'); //end $(document).ready for 'Change Table'
2112  * jQuery coding for 'Table operations'.  Used on tbl_operations.php
2113  * Attach Ajax Event handlers for Table operations
2114  */
2115 $(document).ready(function() {
2116     /**
2117      *Ajax action for submitting the "Alter table order by"
2118     **/
2119     $("#alterTableOrderby.ajax").live('submit', function(event) {
2120         event.preventDefault();
2121         var $form = $(this);
2123         PMA_prepareForAjaxRequest($form);
2124         /*variables which stores the common attributes*/
2125         $.post($form.attr('action'), $form.serialize()+"&submitorderby=Go", function(data) {
2126             if ($("#sqlqueryresults").length != 0) {
2127                 $("#sqlqueryresults").remove();
2128             }
2129             if ($("#result_query").length != 0) {
2130                 $("#result_query").remove();
2131             }
2132             if (data.success == true) {
2133                 PMA_ajaxShowMessage(data.message);
2134                 $("<div id='sqlqueryresults'></div>").insertAfter("#topmenucontainer");
2135                 $("#sqlqueryresults").html(data.sql_query);
2136                 $("#result_query .notice").remove();
2137                 $("#result_query").prepend((data.message));
2138             } else {
2139                 var $temp_div = $("<div id='temp_div'></div>")
2140                 $temp_div.html(data.error);
2141                 var $error = $temp_div.find("code").addClass("error");
2142                 PMA_ajaxShowMessage($error);
2143             }
2144         }) // end $.post()
2145     });//end of alterTableOrderby ajax submit
2147     /**
2148      *Ajax action for submitting the "Copy table"
2149     **/
2150     $("#copyTable.ajax input[name='submit_copy']").live('click', function(event) {
2151         event.preventDefault();
2152         var $form = $("#copyTable");
2153         if($form.find("input[name='switch_to_new']").attr('checked')) {
2154             $form.append('<input type="hidden" name="submit_copy" value="Go" />');
2155             $form.removeClass('ajax');
2156             $form.find("#ajax_request_hidden").remove();
2157             $form.submit();
2158         } else {
2159             PMA_prepareForAjaxRequest($form);
2160             /*variables which stores the common attributes*/
2161             $.post($form.attr('action'), $form.serialize()+"&submit_copy=Go", function(data) {
2162                 if ($("#sqlqueryresults").length != 0) {
2163                     $("#sqlqueryresults").remove();
2164                 }
2165                 if ($("#result_query").length != 0) {
2166                     $("#result_query").remove();
2167                 }
2168                 if (data.success == true) {
2169                     PMA_ajaxShowMessage(data.message);
2170                     $("<div id='sqlqueryresults'></div>").insertAfter("#topmenucontainer");
2171                     $("#sqlqueryresults").html(data.sql_query);
2172                     $("#result_query .notice").remove();
2173                     $("#result_query").prepend((data.message));
2174                     $("#copyTable").find("select[name='target_db'] option[value="+data.db+"]").attr('selected', 'selected');
2176                     //Refresh navigation frame when the table is coppied
2177                     if (window.parent && window.parent.frame_navigation) {
2178                         window.parent.frame_navigation.location.reload();
2179                     }
2180                 } else {
2181                     var $temp_div = $("<div id='temp_div'></div>");
2182                     $temp_div.html(data.error);
2183                     var $error = $temp_div.find("code").addClass("error");
2184                     PMA_ajaxShowMessage($error);
2185                 }
2186             }) // end $.post()
2187         }
2188     });//end of copyTable ajax submit
2190     /**
2191      *Ajax events for actions in the "Table maintenance"
2192     **/
2193     $("#tbl_maintenance.ajax li a.maintain_action").live('click', function(event) {
2194         event.preventDefault();
2195         var $link = $(this);
2196         var href = $link.attr("href");
2197         href = href.split('?');
2198         if ($("#sqlqueryresults").length != 0) {
2199             $("#sqlqueryresults").remove();
2200         }
2201         if ($("#result_query").length != 0) {
2202             $("#result_query").remove();
2203         }
2204         //variables which stores the common attributes
2205         $.post(href[0], href[1]+"&ajax_request=true", function(data) {
2206             if (data.success == undefined) {
2207                 var $temp_div = $("<div id='temp_div'></div>");
2208                 $temp_div.html(data);
2209                 var $success = $temp_div.find("#result_query .success");
2210                 PMA_ajaxShowMessage($success);
2211                 $("<div id='sqlqueryresults' class='ajax'></div>").insertAfter("#topmenucontainer");
2212                 $("#sqlqueryresults").html(data);
2213                 PMA_init_slider();
2214                 $("#sqlqueryresults").children("fieldset").remove();
2215             } else if (data.success == true ) {
2216                 PMA_ajaxShowMessage(data.message);
2217                 $("<div id='sqlqueryresults' class='ajax'></div>").insertAfter("#topmenucontainer");
2218                 $("#sqlqueryresults").html(data.sql_query);
2219             } else {
2220                 var $temp_div = $("<div id='temp_div'></div>");
2221                 $temp_div.html(data.error);
2222                 var $error = $temp_div.find("code").addClass("error");
2223                 PMA_ajaxShowMessage($error);
2224             }
2225         }) // end $.post()
2226     });//end of table maintanance ajax click
2228 }, 'top.frame_content'); //end $(document).ready for 'Table operations'
2232  * Attach Ajax event handlers for Drop Database. Moved here from db_structure.js
2233  * as it was also required on db_create.php
2235  * @uses    $.PMA_confirm()
2236  * @uses    PMA_ajaxShowMessage()
2237  * @uses    window.parent.refreshNavigation()
2238  * @uses    window.parent.refreshMain()
2239  * @see $cfg['AjaxEnable']
2240  */
2241 $(document).ready(function() {
2242     $("#drop_db_anchor").live('click', function(event) {
2243         event.preventDefault();
2245         //context is top.frame_content, so we need to use window.parent.db to access the db var
2246         /**
2247          * @var question    String containing the question to be asked for confirmation
2248          */
2249         var question = PMA_messages['strDropDatabaseStrongWarning'] + '\n' + PMA_messages['strDoYouReally'] + ' :\n' + 'DROP DATABASE ' + window.parent.db;
2251         $(this).PMA_confirm(question, $(this).attr('href') ,function(url) {
2253             PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
2254             $.get(url, {'is_js_confirmed': '1', 'ajax_request': true}, function(data) {
2255                 //Database deleted successfully, refresh both the frames
2256                 window.parent.refreshNavigation();
2257                 window.parent.refreshMain();
2258             }) // end $.get()
2259         }); // end $.PMA_confirm()
2260     }); //end of Drop Database Ajax action
2261 }) // end of $(document).ready() for Drop Database
2264  * Attach Ajax event handlers for 'Create Database'.  Used wherever libraries/
2265  * display_create_database.lib.php is used, ie main.php and server_databases.php
2267  * @uses    PMA_ajaxShowMessage()
2268  * @see $cfg['AjaxEnable']
2269  */
2270 $(document).ready(function() {
2272     $('#create_database_form.ajax').live('submit', function(event) {
2273         event.preventDefault();
2275         $form = $(this);
2277         PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
2278         PMA_prepareForAjaxRequest($form);
2280         $.post($form.attr('action'), $form.serialize(), function(data) {
2281             if(data.success == true) {
2282                 PMA_ajaxShowMessage(data.message);
2284                 //Append database's row to table
2285                 $("#tabledatabases")
2286                 .find('tbody')
2287                 .append(data.new_db_string)
2288                 .PMA_sort_table('.name')
2289                 .find('#db_summary_row')
2290                 .appendTo('#tabledatabases tbody')
2291                 .removeClass('odd even');
2293                 var $databases_count_object = $('#databases_count');
2294                 var databases_count = parseInt($databases_count_object.text());
2295                 $databases_count_object.text(++databases_count);
2296                 //Refresh navigation frame as a new database has been added
2297                 if (window.parent && window.parent.frame_navigation) {
2298                     window.parent.frame_navigation.location.reload();
2299                 }
2300             }
2301             else {
2302                 PMA_ajaxShowMessage(data.error);
2303             }
2304         }) // end $.post()
2305     }) // end $().live()
2306 })  // end $(document).ready() for Create Database
2309  * Attach Ajax event handlers for 'Change Password' on main.php
2310  */
2311 $(document).ready(function() {
2313     /**
2314      * Attach Ajax event handler on the change password anchor
2315      * @see $cfg['AjaxEnable']
2316      */
2317     $('#change_password_anchor.dialog_active').live('click',function(event) {
2318         event.preventDefault();
2319         return false;
2320         });
2321     $('#change_password_anchor.ajax').live('click', function(event) {
2322         event.preventDefault();
2323         $(this).removeClass('ajax').addClass('dialog_active');
2324         /**
2325          * @var button_options  Object containing options to be passed to jQueryUI's dialog
2326          */
2327         var button_options = {};
2328         button_options[PMA_messages['strCancel']] = function() {$(this).dialog('close').remove();}
2329         $.get($(this).attr('href'), {'ajax_request': true}, function(data) {
2330             $('<div id="change_password_dialog"></div>')
2331             .dialog({
2332                 title: PMA_messages['strChangePassword'],
2333                 width: 600,
2334                 close: function(ev,ui) {$(this).remove();},
2335                 buttons : button_options,
2336                 beforeClose: function(ev,ui){ $('#change_password_anchor.dialog_active').removeClass('dialog_active').addClass('ajax')}
2337             })
2338             .append(data);
2339             displayPasswordGenerateButton();
2340         }) // end $.get()
2341     }) // end handler for change password anchor
2343     /**
2344      * Attach Ajax event handler for Change Password form submission
2345      *
2346      * @uses    PMA_ajaxShowMessage()
2347      * @see $cfg['AjaxEnable']
2348      */
2349     $("#change_password_form.ajax").find('input[name=change_pw]').live('click', function(event) {
2350         event.preventDefault();
2352         /**
2353          * @var the_form    Object referring to the change password form
2354          */
2355         var the_form = $("#change_password_form");
2357         /**
2358          * @var this_value  String containing the value of the submit button.
2359          * Need to append this for the change password form on Server Privileges
2360          * page to work
2361          */
2362         var this_value = $(this).val();
2364         var $msgbox = PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
2365         $(the_form).append('<input type="hidden" name="ajax_request" value="true" />');
2367         $.post($(the_form).attr('action'), $(the_form).serialize() + '&change_pw='+ this_value, function(data) {
2368             if(data.success == true) {
2369                 $("#topmenucontainer").after(data.sql_query);
2370                 $("#change_password_dialog").hide().remove();
2371                 $("#edit_user_dialog").dialog("close").remove();
2372                 $('#change_password_anchor.dialog_active').removeClass('dialog_active').addClass('ajax');
2373                 PMA_ajaxRemoveMessage($msgbox);
2374             }
2375             else {
2376                 PMA_ajaxShowMessage(data.error);
2377             }
2378         }) // end $.post()
2379     }) // end handler for Change Password form submission
2380 }) // end $(document).ready() for Change Password
2383  * Toggle the hiding/showing of the "Open in ENUM/SET editor" message when
2384  * the page loads and when the selected data type changes
2385  */
2386 $(document).ready(function() {
2387     // is called here for normal page loads and also when opening
2388     // the Create table dialog
2389     PMA_verifyTypeOfAllColumns();
2390     //
2391     // needs live() to work also in the Create Table dialog
2392     $("select[class='column_type']").live('change', function() {
2393         PMA_showNoticeForEnum($(this));
2394     });
2397 function PMA_verifyTypeOfAllColumns()
2399     $("select[class='column_type']").each(function() {
2400         PMA_showNoticeForEnum($(this));
2401     });
2405  * Closes the ENUM/SET editor and removes the data in it
2406  */
2407 function disable_popup()
2409     $("#popup_background").fadeOut("fast");
2410     $("#enum_editor").fadeOut("fast");
2411     // clear the data from the text boxes
2412     $("#enum_editor #values input").remove();
2413     $("#enum_editor input[type='hidden']").remove();
2417  * Opens the ENUM/SET editor and controls its functions
2418  */
2419 $(document).ready(function() {
2420     // Needs live() to work also in the Create table dialog
2421     $("a[class='open_enum_editor']").live('click', function() {
2422         // Center the popup
2423         var windowWidth = document.documentElement.clientWidth;
2424         var windowHeight = document.documentElement.clientHeight;
2425         var popupWidth = windowWidth/2;
2426         var popupHeight = windowHeight*0.8;
2427         var popupOffsetTop = windowHeight/2 - popupHeight/2;
2428         var popupOffsetLeft = windowWidth/2 - popupWidth/2;
2429         $("#enum_editor").css({"position":"absolute", "top": popupOffsetTop, "left": popupOffsetLeft, "width": popupWidth, "height": popupHeight});
2431         // Make it appear
2432         $("#popup_background").css({"opacity":"0.7"});
2433         $("#popup_background").fadeIn("fast");
2434         $("#enum_editor").fadeIn("fast");
2435         /**Replacing the column name in the enum editor header*/
2436         var column_name = $("#append_fields_form").find("input[id=field_0_1]").attr("value");
2437         var h3_text = $("#enum_editor h3").html();
2438         $("#enum_editor h3").html(h3_text.split('"')[0]+'"'+column_name+'"');
2440         // Get the values
2441         var values = $(this).parent().prev("input").attr("value").split(",");
2442         $.each(values, function(index, val) {
2443             if(jQuery.trim(val) != "") {
2444                  // enclose the string in single quotes if it's not already
2445                  if(val.substr(0, 1) != "'") {
2446                       val = "'" + val;
2447                  }
2448                  if(val.substr(val.length-1, val.length) != "'") {
2449                       val = val + "'";
2450                  }
2451                 // escape the single quotes, except the mandatory ones enclosing the entire string
2452                 val = val.substr(1, val.length-2).replace(/''/g, "'").replace(/\\\\/g, '\\').replace(/\\'/g, "'").replace(/'/g, "&#039;");
2453                 // escape the greater-than symbol
2454                 val = val.replace(/>/g, "&gt;");
2455                 $("#enum_editor #values").append("<input type='text' value=" + val + " />");
2456             }
2457         });
2458         // So we know which column's data is being edited
2459         $("#enum_editor").append("<input type='hidden' value='" + $(this).parent().prev("input").attr("id") + "' />");
2460         return false;
2461     });
2463     // If the "close" link is clicked, close the enum editor
2464     // Needs live() to work also in the Create table dialog
2465     $("a[class='close_enum_editor']").live('click', function() {
2466         disable_popup();
2467     });
2469     // If the "cancel" link is clicked, close the enum editor
2470     // Needs live() to work also in the Create table dialog
2471     $("a[class='cancel_enum_editor']").live('click', function() {
2472         disable_popup();
2473     });
2475     // When "add a new value" is clicked, append an empty text field
2476     // Needs live() to work also in the Create table dialog
2477     $("a[class='add_value']").live('click', function() {
2478         $("#enum_editor #values").append("<input type='text' />");
2479     });
2481     // When the submit button is clicked, put the data back into the original form
2482     // Needs live() to work also in the Create table dialog
2483     $("#enum_editor input[type='submit']").live('click', function() {
2484         var value_array = new Array();
2485         $.each($("#enum_editor #values input"), function(index, input_element) {
2486             val = jQuery.trim(input_element.value);
2487             if(val != "") {
2488                 value_array.push("'" + val.replace(/\\/g, '\\\\').replace(/'/g, "''") + "'");
2489             }
2490         });
2491         // get the Length/Values text field where this value belongs
2492         var values_id = $("#enum_editor input[type='hidden']").attr("value");
2493         $("input[id='" + values_id + "']").attr("value", value_array.join(","));
2494         disable_popup();
2495      });
2497     /**
2498      * Hides certain table structure actions, replacing them with the word "More". They are displayed
2499      * in a dropdown menu when the user hovers over the word "More."
2500      */
2501     displayMoreTableOpts();
2504 function displayMoreTableOpts()
2506     // Remove the actions from the table cells (they are available by default for JavaScript-disabled browsers)
2507     // if the table is not a view or information_schema (otherwise there is only one action to hide and there's no point)
2508     if($("input[type='hidden'][name='table_type']").val() == "table") {
2509         var $table = $("table[id='tablestructure']");
2510         $table.find("td[class='browse']").remove();
2511         $table.find("td[class='primary']").remove();
2512         $table.find("td[class='unique']").remove();
2513         $table.find("td[class='index']").remove();
2514         $table.find("td[class='fulltext']").remove();
2515         $table.find("td[class='spatial']").remove();
2516         $table.find("th[class='action']").attr("colspan", 3);
2518         // Display the "more" text
2519         $table.find("td[class='more_opts']").show();
2521         // Position the dropdown
2522         $(".structure_actions_dropdown").each(function() {
2523             // Optimize DOM querying
2524             var $this_dropdown = $(this);
2525              // The top offset must be set for IE even if it didn't change
2526             var cell_right_edge_offset = $this_dropdown.parent().position().left + $this_dropdown.parent().innerWidth();
2527             var left_offset = cell_right_edge_offset - $this_dropdown.innerWidth();
2528             var top_offset = $this_dropdown.parent().position().top + $this_dropdown.parent().innerHeight();
2529             $this_dropdown.offset({ top: top_offset, left: left_offset });
2530         });
2532         // A hack for IE6 to prevent the after_field select element from being displayed on top of the dropdown by
2533         // positioning an iframe directly on top of it
2534         var $after_field = $("select[name='after_field']");
2535         $("iframe[class='IE_hack']")
2536             .width($after_field.width())
2537             .height($after_field.height())
2538             .offset({
2539                 top: $after_field.offset().top,
2540                 left: $after_field.offset().left
2541             });
2543         // When "more" is hovered over, show the hidden actions
2544         $table.find("td[class='more_opts']")
2545             .mouseenter(function() {
2546                 if($.browser.msie && $.browser.version == "6.0") {
2547                     $("iframe[class='IE_hack']")
2548                         .show()
2549                         .width($after_field.width()+4)
2550                         .height($after_field.height()+4)
2551                         .offset({
2552                             top: $after_field.offset().top,
2553                             left: $after_field.offset().left
2554                         });
2555                 }
2556                 $(".structure_actions_dropdown").hide(); // Hide all the other ones that may be open
2557                 $(this).children(".structure_actions_dropdown").show();
2558                 // Need to do this again for IE otherwise the offset is wrong
2559                 if($.browser.msie) {
2560                     var left_offset_IE = $(this).offset().left + $(this).innerWidth() - $(this).children(".structure_actions_dropdown").innerWidth();
2561                     var top_offset_IE = $(this).offset().top + $(this).innerHeight();
2562                     $(this).children(".structure_actions_dropdown").offset({
2563                         top: top_offset_IE,
2564                         left: left_offset_IE });
2565                 }
2566             })
2567             .mouseleave(function() {
2568                 $(this).children(".structure_actions_dropdown").hide();
2569                 if($.browser.msie && $.browser.version == "6.0") {
2570                     $("iframe[class='IE_hack']").hide();
2571                 }
2572             });
2573     }
2576 $(document).ready(function(){
2577     PMA_convertFootnotesToTooltips();
2581  * Ensures indexes names are valid according to their type and, for a primary
2582  * key, lock index name to 'PRIMARY'
2583  * @param   string   form_id  Variable which parses the form name as
2584  *                            the input
2585  * @return  boolean  false    if there is no index form, true else
2586  */
2587 function checkIndexName(form_id)
2589     if ($("#"+form_id).length == 0) {
2590         return false;
2591     }
2593     // Gets the elements pointers
2594     var $the_idx_name = $("#input_index_name");
2595     var $the_idx_type = $("#select_index_type");
2597     // Index is a primary key
2598     if ($the_idx_type.find("option:selected").attr("value") == 'PRIMARY') {
2599         $the_idx_name.attr("value", 'PRIMARY');
2600         $the_idx_name.attr("disabled", true);
2601     }
2603     // Other cases
2604     else {
2605         if ($the_idx_name.attr("value") == 'PRIMARY') {
2606             $the_idx_name.attr("value",  '');
2607         }
2608         $the_idx_name.attr("disabled", false);
2609     }
2611     return true;
2612 } // end of the 'checkIndexName()' function
2615  * function to convert the footnotes to tooltips
2617  * @param   jquery-Object   $div    a div jquery object which specifies the
2618  *                                  domain for searching footnootes. If we
2619  *                                  ommit this parameter the function searches
2620  *                                  the footnotes in the whole body
2621  **/
2622 function PMA_convertFootnotesToTooltips($div)
2624     // Hide the footnotes from the footer (which are displayed for
2625     // JavaScript-disabled browsers) since the tooltip is sufficient
2627     if ($div == undefined || ! $div instanceof jQuery || $div.length == 0) {
2628         $div = $("#serverinfo").parent();
2629     }
2631     $footnotes = $div.find(".footnotes");
2633     $footnotes.hide();
2634     $footnotes.find('span').each(function() {
2635         $(this).children("sup").remove();
2636     });
2637     // The border and padding must be removed otherwise a thin yellow box remains visible
2638     $footnotes.css("border", "none");
2639     $footnotes.css("padding", "0px");
2641     // Replace the superscripts with the help icon
2642     $div.find("sup.footnotemarker").hide();
2643     $div.find("img.footnotemarker").show();
2645     $div.find("img.footnotemarker").each(function() {
2646         var img_class = $(this).attr("class");
2647         /** img contains two classes, as example "footnotemarker footnote_1".
2648          *  We split it by second class and take it for the id of span
2649         */
2650         img_class = img_class.split(" ");
2651         for (i = 0; i < img_class.length; i++) {
2652             if (img_class[i].split("_")[0] == "footnote") {
2653                 var span_id = img_class[i].split("_")[1];
2654             }
2655         }
2656         /**
2657          * Now we get the #id of the span with span_id variable. As an example if we
2658          * initially get the img class as "footnotemarker footnote_2", now we get
2659          * #2 as the span_id. Using that we can find footnote_2 in footnotes.
2660          * */
2661         var tooltip_text = $footnotes.find("span[id='footnote_" + span_id + "']").html();
2662         $(this).qtip({
2663             content: tooltip_text,
2664             show: { delay: 0 },
2665             hide: { delay: 1000 },
2666             style: { background: '#ffffcc' }
2667         });
2668     });
2671 function menuResize()
2673     var cnt = $('#topmenu');
2674     var wmax = cnt.innerWidth() - 5; // 5 px margin for jumping menu in Chrome
2675     var submenu = cnt.find('.submenu');
2676     var submenu_w = submenu.outerWidth(true);
2677     var submenu_ul = submenu.find('ul');
2678     var li = cnt.find('> li');
2679     var li2 = submenu_ul.find('li');
2680     var more_shown = li2.length > 0;
2681     var w = more_shown ? submenu_w : 0;
2683     // hide menu items
2684     var hide_start = 0;
2685     for (var i = 0; i < li.length-1; i++) { // li.length-1: skip .submenu element
2686         var el = $(li[i]);
2687         var el_width = el.outerWidth(true);
2688         el.data('width', el_width);
2689         w += el_width;
2690         if (w > wmax) {
2691             w -= el_width;
2692             if (w + submenu_w < wmax) {
2693                 hide_start = i;
2694             } else {
2695                 hide_start = i-1;
2696                 w -= $(li[i-1]).data('width');
2697             }
2698             break;
2699         }
2700     }
2702     if (hide_start > 0) {
2703         for (var i = hide_start; i < li.length-1; i++) {
2704             $(li[i])[more_shown ? 'prependTo' : 'appendTo'](submenu_ul);
2705         }
2706         submenu.addClass('shown');
2707     } else if (more_shown) {
2708         w -= submenu_w;
2709         // nothing hidden, maybe something can be restored
2710         for (var i = 0; i < li2.length; i++) {
2711             //console.log(li2[i], submenu_w);
2712             w += $(li2[i]).data('width');
2713             // item fits or (it is the last item and it would fit if More got removed)
2714             if (w+submenu_w < wmax || (i == li2.length-1 && w < wmax)) {
2715                 $(li2[i]).insertBefore(submenu);
2716                 if (i == li2.length-1) {
2717                     submenu.removeClass('shown');
2718                 }
2719                 continue;
2720             }
2721             break;
2722         }
2723     }
2724     if (submenu.find('.tabactive').length) {
2725         submenu.addClass('active').find('> a').removeClass('tab').addClass('tabactive');
2726     } else {
2727         submenu.removeClass('active').find('> a').addClass('tab').removeClass('tabactive');
2728     }
2731 $(function() {
2732     var topmenu = $('#topmenu');
2733     if (topmenu.length == 0) {
2734         return;
2735     }
2736     // create submenu container
2737     var link = $('<a />', {href: '#', 'class': 'tab'})
2738         .text(PMA_messages['strMore'])
2739         .click(function(e) {
2740             e.preventDefault();
2741         });
2742     var img = topmenu.find('li:first-child img');
2743     if (img.length) {
2744         img.clone().attr('class', 'icon ic_b_more').prependTo(link);
2745     }
2746     var submenu = $('<li />', {'class': 'submenu'})
2747         .append(link)
2748         .append($('<ul />'))
2749         .mouseenter(function() {
2750             if ($(this).find('ul .tabactive').length == 0) {
2751                 $(this).addClass('submenuhover').find('> a').addClass('tabactive');
2752             }
2753         })
2754         .mouseleave(function() {
2755             if ($(this).find('ul .tabactive').length == 0) {
2756                 $(this).removeClass('submenuhover').find('> a').removeClass('tabactive');
2757             }
2758         });
2759     topmenu.append(submenu);
2761     // populate submenu and register resize event
2762     $(window).resize(menuResize);
2763     menuResize();
2767  * Get the row number from the classlist (for example, row_1)
2768  */
2769 function PMA_getRowNumber(classlist)
2771     return parseInt(classlist.split(/\s+row_/)[1]);
2775  * Changes status of slider
2776  */
2777 function PMA_set_status_label(id)
2779     if ($('#' + id).css('display') == 'none') {
2780         $('#anchor_status_' + id).text('+ ');
2781     } else {
2782         $('#anchor_status_' + id).text('- ');
2783     }
2787  * Initializes slider effect.
2788  */
2789 function PMA_init_slider()
2791     $('.pma_auto_slider').each(function(idx, e) {
2792         if ($(e).hasClass('slider_init_done')) return;
2793         $(e).addClass('slider_init_done');
2794         $('<span id="anchor_status_' + e.id + '"></span>')
2795             .insertBefore(e);
2796         PMA_set_status_label(e.id);
2798         $('<a href="#' + e.id + '" id="anchor_' + e.id + '">' + e.title + '</a>')
2799             .insertBefore(e)
2800             .click(function() {
2801                 $('#' + e.id).toggle('clip', function() {
2802                     PMA_set_status_label(e.id);
2803                 });
2804                 return false;
2805             });
2806     });
2810  * var  toggleButton  This is a function that creates a toggle
2811  *                    sliding button given a jQuery reference
2812  *                    to the correct DOM element
2813  */
2814 var toggleButton = function ($obj) {
2815     // In rtl mode the toggle switch is flipped horizontally
2816     // so we need to take that into account
2817     if ($('.text_direction', $obj).text() == 'ltr') {
2818         var right = 'right';
2819     } else {
2820         var right = 'left';
2821     }
2822     /**
2823      *  var  h  Height of the button, used to scale the
2824      *          background image and position the layers
2825      */
2826     var h = $obj.height();
2827     $('img', $obj).height(h);
2828     $('table', $obj).css('bottom', h-1);
2829     /**
2830      *  var  on   Width of the "ON" part of the toggle switch
2831      *  var  off  Width of the "OFF" part of the toggle switch
2832      */
2833     var on  = $('.toggleOn', $obj).width();
2834     var off = $('.toggleOff', $obj).width();
2835     // Make the "ON" and "OFF" parts of the switch the same size
2836     $('.toggleOn > div', $obj).width(Math.max(on, off));
2837     $('.toggleOff > div', $obj).width(Math.max(on, off));
2838     /**
2839      *  var  w  Width of the central part of the switch
2840      */
2841     var w = parseInt(($('img', $obj).height() / 16) * 22, 10);
2842     // Resize the central part of the switch on the top
2843     // layer to match the background
2844     $('table td:nth-child(2) > div', $obj).width(w);
2845     /**
2846      *  var  imgw    Width of the background image
2847      *  var  tblw    Width of the foreground layer
2848      *  var  offset  By how many pixels to move the background
2849      *               image, so that it matches the top layer
2850      */
2851     var imgw = $('img', $obj).width();
2852     var tblw = $('table', $obj).width();
2853     var offset = parseInt(((imgw - tblw) / 2), 10);
2854     // Move the background to match the layout of the top layer
2855     $obj.find('img').css(right, offset);
2856     /**
2857      *  var  offw    Outer width of the "ON" part of the toggle switch
2858      *  var  btnw    Outer width of the central part of the switch
2859      */
2860     var offw = $('.toggleOff', $obj).outerWidth();
2861     var btnw = $('table td:nth-child(2)', $obj).outerWidth();
2862     // Resize the main div so that exactly one side of
2863     // the switch plus the central part fit into it.
2864     $obj.width(offw + btnw + 2);
2865     /**
2866      *  var  move  How many pixels to move the
2867      *             switch by when toggling
2868      */
2869     var move = $('.toggleOff', $obj).outerWidth();
2870     // If the switch is initialized to the
2871     // OFF state we need to move it now.
2872     if ($('.container', $obj).hasClass('off')) {
2873         if (right == 'right') {
2874             $('table, img', $obj).animate({'left': '-=' + move + 'px'}, 0);
2875         } else {
2876             $('table, img', $obj).animate({'left': '+=' + move + 'px'}, 0);
2877         }
2878     }
2879     // Attach an 'onclick' event to the switch
2880     $('.container', $obj).click(function () {
2881         if ($(this).hasClass('isActive')) {
2882             return false;
2883         } else {
2884             $(this).addClass('isActive');
2885         }
2886         var $msg = PMA_ajaxShowMessage(PMA_messages['strLoading']);
2887         var $container = $(this);
2888         var callback = $('.callback', this).text();
2889         // Perform the actual toggle
2890         if ($(this).hasClass('on')) {
2891             if (right == 'right') {
2892                 var operator = '-=';
2893             } else {
2894                 var operator = '+=';
2895             }
2896             var url = $(this).find('.toggleOff > span').text();
2897             var removeClass = 'on';
2898             var addClass = 'off';
2899         } else {
2900             if (right == 'right') {
2901                 var operator = '+=';
2902             } else {
2903                 var operator = '-=';
2904             }
2905             var url = $(this).find('.toggleOn > span').text();
2906             var removeClass = 'off';
2907             var addClass = 'on';
2908         }
2909         $.post(url, {'ajax_request': true}, function(data) {
2910             if(data.success == true) {
2911                 PMA_ajaxRemoveMessage($msg);
2912                 $container
2913                 .removeClass(removeClass)
2914                 .addClass(addClass)
2915                 .animate({'left': operator + move + 'px'}, function () {
2916                     $container.removeClass('isActive');
2917                 });
2918                 eval(callback);
2919             } else {
2920                 PMA_ajaxShowMessage(data.error);
2921                 $container.removeClass('isActive');
2922             }
2923         });
2924     });
2928  * Initialise all toggle buttons
2929  */
2930 $(window).load(function () {
2931     $('.toggleAjax').each(function () {
2932         $(this)
2933         .show()
2934         .find('.toggleButton')
2935         toggleButton($(this));
2936     });
2940  * Vertical pointer
2941  */
2942 $(document).ready(function() {
2943     $('.vpointer').live('hover',
2944         //handlerInOut
2945         function(e) {
2946             var $this_td = $(this);
2947             var row_num = PMA_getRowNumber($this_td.attr('class'));
2948             // for all td of the same vertical row, toggle hover
2949             $('.vpointer').filter('.row_' + row_num).toggleClass('hover');
2950         }
2951         );
2952 }) // end of $(document).ready() for vertical pointer
2954 $(document).ready(function() {
2955     /**
2956      * Vertical marker
2957      */
2958     $('.vmarker').live('click', function(e) {
2959         // do not trigger when clicked on anchor
2960         if ($(e.target).is('a, img, a *')) {
2961             return;
2962         }
2964         var $this_td = $(this);
2965         var row_num = PMA_getRowNumber($this_td.attr('class'));
2967         // XXX: FF fires two click events for <label> (label and checkbox), so we need to handle this differently
2968         var $tr = $(this);
2969         var $checkbox = $('.vmarker').filter('.row_' + row_num + ':first').find(':checkbox');
2970         if ($checkbox.length) {
2971             // checkbox in a row, add or remove class depending on checkbox state
2972             var checked = $checkbox.attr('checked');
2973             if (!$(e.target).is(':checkbox, label')) {
2974                 checked = !checked;
2975                 $checkbox.attr('checked', checked);
2976             }
2977             // for all td of the same vertical row, toggle the marked class
2978             if (checked) {
2979                 $('.vmarker').filter('.row_' + row_num).addClass('marked');
2980             } else {
2981                 $('.vmarker').filter('.row_' + row_num).removeClass('marked');
2982             }
2983         } else {
2984             // normaln data table, just toggle class
2985             $('.vmarker').filter('.row_' + row_num).toggleClass('marked');
2986         }
2987     });
2989     /**
2990      * Reveal visual builder anchor
2991      */
2993     $('#visual_builder_anchor').show();
2995     /**
2996      * Page selector in db Structure (non-AJAX)
2997      */
2998     $('#tableslistcontainer').find('#pageselector').live('change', function() {
2999         $(this).parent("form").submit();
3000     });
3002     /**
3003      * Page selector in navi panel (non-AJAX)
3004      */
3005     $('#navidbpageselector').find('#pageselector').live('change', function() {
3006         $(this).parent("form").submit();
3007     });
3009     /**
3010      * Page selector in browse_foreigners windows (non-AJAX)
3011      */
3012     $('#body_browse_foreigners').find('#pageselector').live('change', function() {
3013         $(this).closest("form").submit();
3014     });
3016     /**
3017      * Load version information asynchronously.
3018      */
3019     if ($('.jsversioncheck').length > 0) {
3020         (function() {
3021             var s = document.createElement('script');
3022             s.type = 'text/javascript';
3023             s.async = true;
3024             s.src = 'http://www.phpmyadmin.net/home_page/version.js';
3025             s.onload = PMA_current_version;
3026             var x = document.getElementsByTagName('script')[0];
3027             x.parentNode.insertBefore(s, x);
3028         })();
3029     }
3031     /**
3032      * Slider effect.
3033      */
3034     PMA_init_slider();
3036     /**
3037      * Enables the text generated by PMA_linkOrButton() to be clickable
3038      */
3039     $('a[class~="formLinkSubmit"]').live('click',function(e) {
3041         if($(this).attr('href').indexOf('=') != -1) {
3042             var data = $(this).attr('href').substr($(this).attr('href').indexOf('#')+1).split('=',2);
3043             $(this).parents('form').append('<input type="hidden" name="' + data[0] + '" value="' + data[1] + '"/>');
3044         }
3045         $(this).parents('form').submit();
3046         return false;
3047     });
3049     $('#update_recent_tables').ready(function() {
3050         if (window.parent.frame_navigation != undefined
3051             && window.parent.frame_navigation.PMA_reloadRecentTable != undefined)
3052         {
3053             window.parent.frame_navigation.PMA_reloadRecentTable();
3054         }
3055     });
3057 }) // end of $(document).ready()
3060  * Creates a message inside an object with a sliding effect
3062  * @param   msg    A string containing the text to display
3063  * @param   $obj   a jQuery object containing the reference
3064  *                 to the element where to put the message
3065  *                 This is optional, if no element is
3066  *                 provided, one will be created below the
3067  *                 navigation links at the top of the page
3069  * @return  bool   True on success, false on failure
3070  */
3071 function PMA_slidingMessage(msg, $obj)
3073     if (msg == undefined || msg.length == 0) {
3074         // Don't show an empty message
3075         return false;
3076     }
3077     if ($obj == undefined || ! $obj instanceof jQuery || $obj.length == 0) {
3078         // If the second argument was not supplied,
3079         // we might have to create a new DOM node.
3080         if ($('#PMA_slidingMessage').length == 0) {
3081             $('#topmenucontainer')
3082             .after('<span id="PMA_slidingMessage" '
3083                  + 'style="display: inline-block;"></span>');
3084         }
3085         $obj = $('#PMA_slidingMessage');
3086     }
3087     if ($obj.has('div').length > 0) {
3088         // If there already is a message inside the
3089         // target object, we must get rid of it
3090         $obj
3091         .find('div')
3092         .first()
3093         .fadeOut(function () {
3094             $obj
3095             .children()
3096             .remove();
3097             $obj
3098             .append('<div style="display: none;">' + msg + '</div>')
3099             .animate({
3100                 height: $obj.find('div').first().height()
3101             })
3102             .find('div')
3103             .first()
3104             .fadeIn();
3105         });
3106     } else {
3107         // Object does not already have a message
3108         // inside it, so we simply slide it down
3109         var h = $obj
3110                 .width('100%')
3111                 .html('<div style="display: none;">' + msg + '</div>')
3112                 .find('div')
3113                 .first()
3114                 .height();
3115         $obj
3116         .find('div')
3117         .first()
3118         .css('height', 0)
3119         .show()
3120         .animate({
3121                 height: h
3122             }, function() {
3123             // Set the height of the parent
3124             // to the height of the child
3125             $obj
3126             .height(
3127                 $obj
3128                 .find('div')
3129                 .first()
3130                 .height()
3131             );
3132         });
3133     }
3134     return true;
3135 } // end PMA_slidingMessage()
3138  * Attach Ajax event handlers for Drop Table.
3140  * @uses    $.PMA_confirm()
3141  * @uses    PMA_ajaxShowMessage()
3142  * @uses    window.parent.refreshNavigation()
3143  * @uses    window.parent.refreshMain()
3144  * @see $cfg['AjaxEnable']
3145  */
3146 $(document).ready(function() {
3147     $("#drop_tbl_anchor").live('click', function(event) {
3148         event.preventDefault();
3150         //context is top.frame_content, so we need to use window.parent.table to access the table var
3151         /**
3152          * @var question    String containing the question to be asked for confirmation
3153          */
3154         var question = PMA_messages['strDropTableStrongWarning'] + '\n' + PMA_messages['strDoYouReally'] + ' :\n' + 'DROP TABLE ' + window.parent.table;
3156         $(this).PMA_confirm(question, $(this).attr('href') ,function(url) {
3158             PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
3159             $.get(url, {'is_js_confirmed': '1', 'ajax_request': true}, function(data) {
3160                 //Database deleted successfully, refresh both the frames
3161                 window.parent.refreshNavigation();
3162                 window.parent.refreshMain();
3163             }) // end $.get()
3164         }); // end $.PMA_confirm()
3165     }); //end of Drop Table Ajax action
3166 }) // end of $(document).ready() for Drop Table
3169  * Attach Ajax event handlers for Truncate Table.
3171  * @uses    $.PMA_confirm()
3172  * @uses    PMA_ajaxShowMessage()
3173  * @uses    window.parent.refreshNavigation()
3174  * @uses    window.parent.refreshMain()
3175  * @see $cfg['AjaxEnable']
3176  */
3177 $(document).ready(function() {
3178     $("#truncate_tbl_anchor.ajax").live('click', function(event) {
3179         event.preventDefault();
3181       //context is top.frame_content, so we need to use window.parent.table to access the table var
3182         /**
3183          * @var question    String containing the question to be asked for confirmation
3184          */
3185         var question = PMA_messages['strTruncateTableStrongWarning'] + '\n' + PMA_messages['strDoYouReally'] + ' :\n' + 'TRUNCATE TABLE ' + window.parent.table;
3187         $(this).PMA_confirm(question, $(this).attr('href') ,function(url) {
3189             PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
3190             $.get(url, {'is_js_confirmed': '1', 'ajax_request': true}, function(data) {
3191                 if ($("#sqlqueryresults").length != 0) {
3192                     $("#sqlqueryresults").remove();
3193                 }
3194                 if ($("#result_query").length != 0) {
3195                     $("#result_query").remove();
3196                 }
3197                 if (data.success == true) {
3198                     PMA_ajaxShowMessage(data.message);
3199                     $("<div id='sqlqueryresults'></div>").insertAfter("#topmenucontainer");
3200                     $("#sqlqueryresults").html(data.sql_query);
3201                 } else {
3202                     var $temp_div = $("<div id='temp_div'></div>")
3203                     $temp_div.html(data.error);
3204                     var $error = $temp_div.find("code").addClass("error");
3205                     PMA_ajaxShowMessage($error);
3206                 }
3207             }) // end $.get()
3208         }); // end $.PMA_confirm()
3209     }); //end of Truncate Table Ajax action
3210 }) // end of $(document).ready() for Truncate Table
3213  * Attach CodeMirror2 editor to SQL edit area.
3214  */
3215 $(document).ready(function() {
3216     var elm = $('#sqlquery');
3217     if (elm.length > 0 && typeof CodeMirror != 'undefined') {
3218         codemirror_editor = CodeMirror.fromTextArea(elm[0], {lineNumbers: true, matchBrackets: true, indentUnit: 4, mode: "text/x-mysql"});
3219     }
3223  * jQuery plugin to cancel selection in HTML code.
3224  */
3225 (function ($) {
3226     $.fn.noSelect = function (p) { //no select plugin by Paulo P.Marinas
3227         var prevent = (p == null) ? true : p;
3228         if (prevent) {
3229             return this.each(function () {
3230                 if ($.browser.msie || $.browser.safari) $(this).bind('selectstart', function () {
3231                     return false;
3232                 });
3233                 else if ($.browser.mozilla) {
3234                     $(this).css('MozUserSelect', 'none');
3235                     $('body').trigger('focus');
3236                 } else if ($.browser.opera) $(this).bind('mousedown', function () {
3237                     return false;
3238                 });
3239                 else $(this).attr('unselectable', 'on');
3240             });
3241         } else {
3242             return this.each(function () {
3243                 if ($.browser.msie || $.browser.safari) $(this).unbind('selectstart');
3244                 else if ($.browser.mozilla) $(this).css('MozUserSelect', 'inherit');
3245                 else if ($.browser.opera) $(this).unbind('mousedown');
3246                 else $(this).removeAttr('unselectable', 'on');
3247             });
3248         }
3249     }; //end noSelect
3250 })(jQuery);
3253  * Create default PMA tooltip for the element specified. The default appearance
3254  * can be overriden by specifying optional "options" parameter (see qTip options).
3255  */
3256 function PMA_createqTip($elements, content, options)
3258     if ($('#no_hint').length > 0) {
3259         return;
3260     }
3262     var o = {
3263         content: content,
3264         style: {
3265             classes: {
3266                 tooltip: 'normalqTip',
3267                 content: 'normalqTipContent'
3268             },
3269             name: 'dark'
3270         },
3271         position: {
3272             target: 'mouse',
3273             corner: { target: 'rightMiddle', tooltip: 'leftMiddle' },
3274             adjust: { x: 10, y: 20 }
3275         },
3276         show: {
3277             delay: 0,
3278             effect: {
3279                 type: 'grow',
3280                 length: 150
3281             }
3282         },
3283         hide: {
3284             effect: {
3285                 type: 'grow',
3286                 length: 200
3287             }
3288         }
3289     }
3291     $elements.qtip($.extend(true, o, options));
3295  * Return value of a cell in a table.
3296  */
3297 function PMA_getCellValue(td) {
3298     if ($(td).is('.null')) {
3299         return '';
3300     } else if (! $(td).is('.to_be_saved') && $(td).data('original_data')) {
3301         return $(td).data('original_data');
3302     } else {
3303         return $(td).text();
3304     }
3307 /* Loads a js file, an array may be passed as well */
3308 loadJavascript=function(file) {
3309     if($.isArray(file)) {
3310         for(var i=0; i<file.length; i++) {
3311             $('head').append('<script type="text/javascript" src="'+file[i]+'"></script>');
3312         }
3313     } else {
3314         $('head').append('<script type="text/javascript" src="'+file+'"></script>');
3315     }
3318 $(document).ready(function() {
3319     /**
3320      * Theme selector.
3321      */
3322     $('a.themeselect').live('click', function(e) {
3323         window.open(
3324             e.target,
3325             'themes',
3326             'left=10,top=20,width=510,height=350,scrollbars=yes,status=yes,resizable=yes'
3327             );
3328         return false;
3329     });
3331     /**
3332      * Automatic form submission on change.
3333      */
3334     $('.autosubmit').change(function(e) {
3335         e.target.form.submit();
3336     });
3338     /**
3339      * Theme changer.
3340      */
3341     $('.take_theme').click(function(e) {
3342         var what = this.name;
3343         if (window.opener && window.opener.document.forms['setTheme'].elements['set_theme']) {
3344             window.opener.document.forms['setTheme'].elements['set_theme'].value = what;
3345             window.opener.document.forms['setTheme'].submit();
3346             window.close();
3347             return false;
3348         }
3349         return true;
3350     });
3354  * Clear text selection
3355  */
3356 function PMA_clearSelection() {
3357     if(document.selection && document.selection.empty) {
3358         document.selection.empty();
3359     } else if(window.getSelection) {
3360         var sel = window.getSelection();
3361         if(sel.empty) sel.empty();
3362         if(sel.removeAllRanges) sel.removeAllRanges();
3363     }