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