Merge branch 'MAINT_3_4_7' into QA_3_4
[phpmyadmin/alexukf.git] / js / functions.js
blob8431b2a98a7db233c175f36efd1ed30f483842b3
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 ajax_message_init   boolean boolean that stores status of
19  *      notification for PMA_ajaxShowNotification
20  */
21 var ajax_message_init = false;
23 /**
24  * Add a hidden field to the form to indicate that this will be an
25  * Ajax request (only if this hidden field does not exist)
26  *
27  * @param   object   the form
28  */
29 function PMA_prepareForAjaxRequest($form) {
30     if (! $form.find('input:hidden').is('#ajax_request_hidden')) {
31         $form.append('<input type="hidden" id="ajax_request_hidden" name="ajax_request" value="true" />');
32     }
35 /**
36  * Generate a new password and copy it to the password input areas
37  *
38  * @param   object   the form that holds the password fields
39  *
40  * @return  boolean  always true
41  */
42 function suggestPassword(passwd_form) {
43     // restrict the password to just letters and numbers to avoid problems:
44     // "editors and viewers regard the password as multiple words and
45     // things like double click no longer work"
46     var pwchars = "abcdefhjmnpqrstuvwxyz23456789ABCDEFGHJKLMNPQRSTUVWYXZ";
47     var passwordlength = 16;    // do we want that to be dynamic?  no, keep it simple :)
48     var passwd = passwd_form.generated_pw;
49     passwd.value = '';
51     for ( i = 0; i < passwordlength; i++ ) {
52         passwd.value += pwchars.charAt( Math.floor( Math.random() * pwchars.length ) )
53     }
54     passwd_form.text_pma_pw.value = passwd.value;
55     passwd_form.text_pma_pw2.value = passwd.value;
56     return true;
59 /**
60  * Version string to integer conversion.
61  */
62 function parseVersionString (str) {
63     if (typeof(str) != 'string') { return false; }
64     var add = 0;
65     // Parse possible alpha/beta/rc/
66     var state = str.split('-');
67     if (state.length >= 2) {
68         if (state[1].substr(0, 2) == 'rc') {
69             add = - 20 - parseInt(state[1].substr(2));
70         } else if (state[1].substr(0, 4) == 'beta') {
71             add =  - 40 - parseInt(state[1].substr(4));
72         } else if (state[1].substr(0, 5) == 'alpha') {
73             add =  - 60 - parseInt(state[1].substr(5));
74         } else if (state[1].substr(0, 3) == 'dev') {
75             /* We don't handle dev, it's git snapshot */
76             add = 0;
77         }
78     }
79     // Parse version
80     var x = str.split('.');
81     // Use 0 for non existing parts
82     var maj = parseInt(x[0]) || 0;
83     var min = parseInt(x[1]) || 0;
84     var pat = parseInt(x[2]) || 0;
85     var hotfix = parseInt(x[3]) || 0;
86     return  maj * 100000000 + min * 1000000 + pat * 10000 + hotfix * 100 + add;
89 /**
90  * Indicates current available version on main page.
91  */
92 function PMA_current_version() {
93     var current = parseVersionString(pmaversion);
94     var latest = parseVersionString(PMA_latest_version);
95     $('#li_pma_version').append(PMA_messages['strLatestAvailable'] + ' ' + PMA_latest_version);
96     if (latest > current) {
97         var message = $.sprintf(PMA_messages['strNewerVersion'], PMA_latest_version, PMA_latest_date);
98         if (Math.floor(latest / 10000) == Math.floor(current / 10000)) {
99             /* Security update */
100             klass = 'error';
101         } else {
102             klass = 'notice';
103         }
104         $('#maincontainer').after('<div class="' + klass + '">' + message + '</div>');
105     }
109  * for libraries/display_change_password.lib.php
110  *     libraries/user_password.php
112  */
114 function displayPasswordGenerateButton() {
115     $('#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>');
116     $('#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>');
120  * Adds a date/time picker to an element
122  * @param   object  $this_element   a jQuery object pointing to the element
123  */
124 function PMA_addDatepicker($this_element) {
125     var showTimeOption = false;
126     if ($this_element.is('.datetimefield')) {
127         showTimeOption = true;
128     }
130     $this_element
131         .datepicker({
132         showOn: 'button',
133         buttonImage: themeCalendarImage, // defined in js/messages.php
134         buttonImageOnly: true,
135         duration: '',
136         time24h: true,
137         stepMinutes: 1,
138         stepHours: 1,
139         showTime: showTimeOption,
140         dateFormat: 'yy-mm-dd', // yy means year with four digits
141         altTimeField: '',
142         beforeShow: function(input, inst) {
143             // Remember that we came from the datepicker; this is used
144             // in tbl_change.js by verificationsAfterFieldChange()
145             $this_element.data('comes_from', 'datepicker');
146         },
147         constrainInput: false
148      });
152  * selects the content of a given object, f.e. a textarea
154  * @param   object  element     element of which the content will be selected
155  * @param   var     lock        variable which holds the lock for this element
156  *                              or true, if no lock exists
157  * @param   boolean only_once   if true this is only done once
158  *                              f.e. only on first focus
159  */
160 function selectContent( element, lock, only_once ) {
161     if ( only_once && only_once_elements[element.name] ) {
162         return;
163     }
165     only_once_elements[element.name] = true;
167     if ( lock  ) {
168         return;
169     }
171     element.select();
175  * Displays a confirmation box before submitting a "DROP/DELETE/ALTER" query.
176  * This function is called while clicking links
178  * @param   object   the link
179  * @param   object   the sql query to submit
181  * @return  boolean  whether to run the query or not
182  */
183 function confirmLink(theLink, theSqlQuery)
185     // Confirmation is not required in the configuration file
186     // or browser is Opera (crappy js implementation)
187     if (PMA_messages['strDoYouReally'] == '' || typeof(window.opera) != 'undefined') {
188         return true;
189     }
191     var is_confirmed = confirm(PMA_messages['strDoYouReally'] + ' :\n' + theSqlQuery);
192     if (is_confirmed) {
193         if ( typeof(theLink.href) != 'undefined' ) {
194             theLink.href += '&is_js_confirmed=1';
195         } else if ( typeof(theLink.form) != 'undefined' ) {
196             theLink.form.action += '?is_js_confirmed=1';
197         }
198     }
200     return is_confirmed;
201 } // end of the 'confirmLink()' function
205  * Displays a confirmation box before doing some action
207  * @param   object   the message to display
209  * @return  boolean  whether to run the query or not
211  * @todo used only by libraries/display_tbl.lib.php. figure out how it is used
212  *       and replace with a jQuery equivalent
213  */
214 function confirmAction(theMessage)
216     // TODO: Confirmation is not required in the configuration file
217     // or browser is Opera (crappy js implementation)
218     if (typeof(window.opera) != 'undefined') {
219         return true;
220     }
222     var is_confirmed = confirm(theMessage);
224     return is_confirmed;
225 } // end of the 'confirmAction()' function
229  * Displays an error message if a "DROP DATABASE" statement is submitted
230  * while it isn't allowed, else confirms a "DROP/DELETE/ALTER" query before
231  * sumitting it if required.
232  * This function is called by the 'checkSqlQuery()' js function.
234  * @param   object   the form
235  * @param   object   the sql query textarea
237  * @return  boolean  whether to run the query or not
239  * @see     checkSqlQuery()
240  */
241 function confirmQuery(theForm1, sqlQuery1)
243     // Confirmation is not required in the configuration file
244     if (PMA_messages['strDoYouReally'] == '') {
245         return true;
246     }
248     // The replace function (js1.2) isn't supported
249     else if (typeof(sqlQuery1.value.replace) == 'undefined') {
250         return true;
251     }
253     // js1.2+ -> validation with regular expressions
254     else {
255         // "DROP DATABASE" statement isn't allowed
256         if (PMA_messages['strNoDropDatabases'] != '') {
257             var drop_re = new RegExp('(^|;)\\s*DROP\\s+(IF EXISTS\\s+)?DATABASE\\s', 'i');
258             if (drop_re.test(sqlQuery1.value)) {
259                 alert(PMA_messages['strNoDropDatabases']);
260                 theForm1.reset();
261                 sqlQuery1.focus();
262                 return false;
263             } // end if
264         } // end if
266         // Confirms a "DROP/DELETE/ALTER/TRUNCATE" statement
267         //
268         // TODO: find a way (if possible) to use the parser-analyser
269         // for this kind of verification
270         // For now, I just added a ^ to check for the statement at
271         // beginning of expression
273         var do_confirm_re_0 = new RegExp('^\\s*DROP\\s+(IF EXISTS\\s+)?(TABLE|DATABASE|PROCEDURE)\\s', 'i');
274         var do_confirm_re_1 = new RegExp('^\\s*ALTER\\s+TABLE\\s+((`[^`]+`)|([A-Za-z0-9_$]+))\\s+DROP\\s', 'i');
275         var do_confirm_re_2 = new RegExp('^\\s*DELETE\\s+FROM\\s', 'i');
276         var do_confirm_re_3 = new RegExp('^\\s*TRUNCATE\\s', 'i');
278         if (do_confirm_re_0.test(sqlQuery1.value)
279             || do_confirm_re_1.test(sqlQuery1.value)
280             || do_confirm_re_2.test(sqlQuery1.value)
281             || do_confirm_re_3.test(sqlQuery1.value)) {
282             var message      = (sqlQuery1.value.length > 100)
283                              ? sqlQuery1.value.substr(0, 100) + '\n    ...'
284                              : sqlQuery1.value;
285             var is_confirmed = confirm(PMA_messages['strDoYouReally'] + ' :\n' + message);
286             // statement is confirmed -> update the
287             // "is_js_confirmed" form field so the confirm test won't be
288             // run on the server side and allows to submit the form
289             if (is_confirmed) {
290                 theForm1.elements['is_js_confirmed'].value = 1;
291                 return true;
292             }
293             // statement is rejected -> do not submit the form
294             else {
295                 window.focus();
296                 sqlQuery1.focus();
297                 return false;
298             } // end if (handle confirm box result)
299         } // end if (display confirm box)
300     } // end confirmation stuff
302     return true;
303 } // end of the 'confirmQuery()' function
307  * Displays a confirmation box before disabling the BLOB repository for a given database.
308  * This function is called while clicking links
310  * @param   object   the database
312  * @return  boolean  whether to disable the repository or not
313  */
314 function confirmDisableRepository(theDB)
316     // Confirmation is not required in the configuration file
317     // or browser is Opera (crappy js implementation)
318     if (PMA_messages['strDoYouReally'] == '' || typeof(window.opera) != 'undefined') {
319         return true;
320     }
322     var is_confirmed = confirm(PMA_messages['strBLOBRepositoryDisableStrongWarning'] + '\n' + PMA_messages['strBLOBRepositoryDisableAreYouSure']);
324     return is_confirmed;
325 } // end of the 'confirmDisableBLOBRepository()' function
329  * Displays an error message if the user submitted the sql query form with no
330  * sql query, else checks for "DROP/DELETE/ALTER" statements
332  * @param   object   the form
334  * @return  boolean  always false
336  * @see     confirmQuery()
337  */
338 function checkSqlQuery(theForm)
340     var sqlQuery = theForm.elements['sql_query'];
341     var isEmpty  = 1;
343     // The replace function (js1.2) isn't supported -> basic tests
344     if (typeof(sqlQuery.value.replace) == 'undefined') {
345         isEmpty      = (sqlQuery.value == '') ? 1 : 0;
346         if (isEmpty && typeof(theForm.elements['sql_file']) != 'undefined') {
347             isEmpty  = (theForm.elements['sql_file'].value == '') ? 1 : 0;
348         }
349         if (isEmpty && typeof(theForm.elements['sql_localfile']) != 'undefined') {
350             isEmpty  = (theForm.elements['sql_localfile'].value == '') ? 1 : 0;
351         }
352         if (isEmpty && typeof(theForm.elements['id_bookmark']) != 'undefined') {
353             isEmpty  = (theForm.elements['id_bookmark'].value == null || theForm.elements['id_bookmark'].value == '');
354         }
355     }
356     // js1.2+ -> validation with regular expressions
357     else {
358         var space_re = new RegExp('\\s+');
359         if (typeof(theForm.elements['sql_file']) != 'undefined' &&
360                 theForm.elements['sql_file'].value.replace(space_re, '') != '') {
361             return true;
362         }
363         if (typeof(theForm.elements['sql_localfile']) != 'undefined' &&
364                 theForm.elements['sql_localfile'].value.replace(space_re, '') != '') {
365             return true;
366         }
367         if (isEmpty && typeof(theForm.elements['id_bookmark']) != 'undefined' &&
368                 (theForm.elements['id_bookmark'].value != null || theForm.elements['id_bookmark'].value != '') &&
369                 theForm.elements['id_bookmark'].selectedIndex != 0
370                 ) {
371             return true;
372         }
373         // Checks for "DROP/DELETE/ALTER" statements
374         if (sqlQuery.value.replace(space_re, '') != '') {
375             if (confirmQuery(theForm, sqlQuery)) {
376                 return true;
377             } else {
378                 return false;
379             }
380         }
381         theForm.reset();
382         isEmpty = 1;
383     }
385     if (isEmpty) {
386         sqlQuery.select();
387         alert(PMA_messages['strFormEmpty']);
388         sqlQuery.focus();
389         return false;
390     }
392     return true;
393 } // end of the 'checkSqlQuery()' function
396  * Check if a form's element is empty.
397  * An element containing only spaces is also considered empty
399  * @param   object   the form
400  * @param   string   the name of the form field to put the focus on
402  * @return  boolean  whether the form field is empty or not
403  */
404 function emptyCheckTheField(theForm, theFieldName)
406     var isEmpty  = 1;
407     var theField = theForm.elements[theFieldName];
408     // Whether the replace function (js1.2) is supported or not
409     var isRegExp = (typeof(theField.value.replace) != 'undefined');
411     if (!isRegExp) {
412         isEmpty      = (theField.value == '') ? 1 : 0;
413     } else {
414         var space_re = new RegExp('\\s+');
415         isEmpty      = (theField.value.replace(space_re, '') == '') ? 1 : 0;
416     }
418     return isEmpty;
419 } // end of the 'emptyCheckTheField()' function
423  * Check whether a form field is empty or not
425  * @param   object   the form
426  * @param   string   the name of the form field to put the focus on
428  * @return  boolean  whether the form field is empty or not
429  */
430 function emptyFormElements(theForm, theFieldName)
432     var theField = theForm.elements[theFieldName];
433     var isEmpty = emptyCheckTheField(theForm, theFieldName);
436     return isEmpty;
437 } // end of the 'emptyFormElements()' function
441  * Ensures a value submitted in a form is numeric and is in a range
443  * @param   object   the form
444  * @param   string   the name of the form field to check
445  * @param   integer  the minimum authorized value
446  * @param   integer  the maximum authorized value
448  * @return  boolean  whether a valid number has been submitted or not
449  */
450 function checkFormElementInRange(theForm, theFieldName, message, min, max)
452     var theField         = theForm.elements[theFieldName];
453     var val              = parseInt(theField.value);
455     if (typeof(min) == 'undefined') {
456         min = 0;
457     }
458     if (typeof(max) == 'undefined') {
459         max = Number.MAX_VALUE;
460     }
462     // It's not a number
463     if (isNaN(val)) {
464         theField.select();
465         alert(PMA_messages['strNotNumber']);
466         theField.focus();
467         return false;
468     }
469     // It's a number but it is not between min and max
470     else if (val < min || val > max) {
471         theField.select();
472         alert(message.replace('%d', val));
473         theField.focus();
474         return false;
475     }
476     // It's a valid number
477     else {
478         theField.value = val;
479     }
480     return true;
482 } // end of the 'checkFormElementInRange()' function
485 function checkTableEditForm(theForm, fieldsCnt)
487     // TODO: avoid sending a message if user just wants to add a line
488     // on the form but has not completed at least one field name
490     var atLeastOneField = 0;
491     var i, elm, elm2, elm3, val, id;
493     for (i=0; i<fieldsCnt; i++)
494     {
495         id = "#field_" + i + "_2";
496         elm = $(id);
497         val = elm.val()
498         if (val == 'VARCHAR' || val == 'CHAR' || val == 'BIT' || val == 'VARBINARY' || val == 'BINARY') {
499             elm2 = $("#field_" + i + "_3");
500             val = parseInt(elm2.val());
501             elm3 = $("#field_" + i + "_1");
502             if (isNaN(val) && elm3.val() != "") {
503                 elm2.select();
504                 alert(PMA_messages['strNotNumber']);
505                 elm2.focus();
506                 return false;
507             }
508         }
510         if (atLeastOneField == 0) {
511             id = "field_" + i + "_1";
512             if (!emptyCheckTheField(theForm, id)) {
513                 atLeastOneField = 1;
514             }
515         }
516     }
517     if (atLeastOneField == 0) {
518         var theField = theForm.elements["field_0_1"];
519         alert(PMA_messages['strFormEmpty']);
520         theField.focus();
521         return false;
522     }
524     // at least this section is under jQuery
525     if ($("input.textfield[name='table']").val() == "") {
526         alert(PMA_messages['strFormEmpty']);
527         $("input.textfield[name='table']").focus();
528         return false;
529     }
532     return true;
533 } // enf of the 'checkTableEditForm()' function
537  * Ensures the choice between 'transmit', 'zipped', 'gzipped' and 'bzipped'
538  * checkboxes is consistant
540  * @param   object   the form
541  * @param   string   a code for the action that causes this function to be run
543  * @return  boolean  always true
544  */
545 function checkTransmitDump(theForm, theAction)
547     var formElts = theForm.elements;
549     // 'zipped' option has been checked
550     if (theAction == 'zip' && formElts['zip'].checked) {
551         if (!formElts['asfile'].checked) {
552             theForm.elements['asfile'].checked = true;
553         }
554         if (typeof(formElts['gzip']) != 'undefined' && formElts['gzip'].checked) {
555             theForm.elements['gzip'].checked = false;
556         }
557         if (typeof(formElts['bzip']) != 'undefined' && formElts['bzip'].checked) {
558             theForm.elements['bzip'].checked = false;
559         }
560     }
561     // 'gzipped' option has been checked
562     else if (theAction == 'gzip' && formElts['gzip'].checked) {
563         if (!formElts['asfile'].checked) {
564             theForm.elements['asfile'].checked = true;
565         }
566         if (typeof(formElts['zip']) != 'undefined' && formElts['zip'].checked) {
567             theForm.elements['zip'].checked = false;
568         }
569         if (typeof(formElts['bzip']) != 'undefined' && formElts['bzip'].checked) {
570             theForm.elements['bzip'].checked = false;
571         }
572     }
573     // 'bzipped' option has been checked
574     else if (theAction == 'bzip' && formElts['bzip'].checked) {
575         if (!formElts['asfile'].checked) {
576             theForm.elements['asfile'].checked = true;
577         }
578         if (typeof(formElts['zip']) != 'undefined' && formElts['zip'].checked) {
579             theForm.elements['zip'].checked = false;
580         }
581         if (typeof(formElts['gzip']) != 'undefined' && formElts['gzip'].checked) {
582             theForm.elements['gzip'].checked = false;
583         }
584     }
585     // 'transmit' option has been unchecked
586     else if (theAction == 'transmit' && !formElts['asfile'].checked) {
587         if (typeof(formElts['zip']) != 'undefined' && formElts['zip'].checked) {
588             theForm.elements['zip'].checked = false;
589         }
590         if ((typeof(formElts['gzip']) != 'undefined' && formElts['gzip'].checked)) {
591             theForm.elements['gzip'].checked = false;
592         }
593         if ((typeof(formElts['bzip']) != 'undefined' && formElts['bzip'].checked)) {
594             theForm.elements['bzip'].checked = false;
595         }
596     }
598     return true;
599 } // end of the 'checkTransmitDump()' function
601 $(document).ready(function() {
602     /**
603      * Row marking in horizontal mode (use "live" so that it works also for
604      * next pages reached via AJAX); a tr may have the class noclick to remove
605      * this behavior.
606      */
607     $('tr.odd:not(.noclick), tr.even:not(.noclick)').live('click',function(e) {
608         // do not trigger when clicked on anchor
609         if ($(e.target).is('a, img, a *')) {
610             return;
611         }
612         // XXX: FF fires two click events for <label> (label and checkbox), so we need to handle this differently
613         var $tr = $(this);
614         var $checkbox = $tr.find(':checkbox');
615         if ($checkbox.length) {
616             // checkbox in a row, add or remove class depending on checkbox state
617             var checked = $checkbox.attr('checked');
618             if (!$(e.target).is(':checkbox, label')) {
619                 checked = !checked;
620                 $checkbox.attr('checked', checked);
621             }
622             if (checked) {
623                 $tr.addClass('marked');
624             } else {
625                 $tr.removeClass('marked');
626             }
627         } else {
628             // normaln data table, just toggle class
629             $tr.toggleClass('marked');
630         }
631     });
633     /**
634      * Add a date/time picker to each element that needs it
635      */
636     $('.datefield, .datetimefield').each(function() {
637         PMA_addDatepicker($(this));
638         });
642  * Row highlighting in horizontal mode (use "live"
643  * so that it works also for pages reached via AJAX)
644  */
645 $(document).ready(function() {
646     $('tr.odd, tr.even').live('hover',function() {
647         var $tr = $(this);
648         $tr.toggleClass('hover');
649         $tr.children().toggleClass('hover');
650     });
654  * This array is used to remember mark status of rows in browse mode
655  */
656 var marked_row = new Array;
659  * marks all rows and selects its first checkbox inside the given element
660  * the given element is usaly a table or a div containing the table or tables
662  * @param    container    DOM element
663  */
664 function markAllRows( container_id ) {
666     $("#"+container_id).find("input:checkbox:enabled").attr('checked', 'checked')
667     .parents("tr").addClass("marked");
668     return true;
672  * marks all rows and selects its first checkbox inside the given element
673  * the given element is usaly a table or a div containing the table or tables
675  * @param    container    DOM element
676  */
677 function unMarkAllRows( container_id ) {
679     $("#"+container_id).find("input:checkbox:enabled").removeAttr('checked')
680     .parents("tr").removeClass("marked");
681     return true;
685  * Checks/unchecks all checkbox in given conainer (f.e. a form, fieldset or div)
687  * @param   string   container_id  the container id
688  * @param   boolean  state         new value for checkbox (true or false)
689  * @return  boolean  always true
690  */
691 function setCheckboxes( container_id, state ) {
693     if(state) {
694         $("#"+container_id).find("input:checkbox").attr('checked', 'checked');
695     }
696     else {
697         $("#"+container_id).find("input:checkbox").removeAttr('checked');
698     }
700     return true;
701 } // end of the 'setCheckboxes()' function
704   * Checks/unchecks all options of a <select> element
705   *
706   * @param   string   the form name
707   * @param   string   the element name
708   * @param   boolean  whether to check or to uncheck options
709   *
710   * @return  boolean  always true
711   */
712 function setSelectOptions(the_form, the_select, do_check)
714     $("form[name='"+ the_form +"'] select[name='"+the_select+"']").find("option").attr('selected', do_check);
715     return true;
716 } // end of the 'setSelectOptions()' function
720   * Create quick sql statements.
721   *
722   */
723 function insertQuery(queryType) {
724     var myQuery = document.sqlform.sql_query;
725     var myListBox = document.sqlform.dummy;
726     var query = "";
727     var table = document.sqlform.table.value;
729     if (myListBox.options.length > 0) {
730         sql_box_locked = true;
731         var chaineAj = "";
732         var valDis = "";
733         var editDis = "";
734         var NbSelect = 0;
735         for (var i=0; i < myListBox.options.length; i++) {
736             NbSelect++;
737             if (NbSelect > 1) {
738                 chaineAj += ", ";
739                 valDis += ",";
740                 editDis += ",";
741             }
742             chaineAj += myListBox.options[i].value;
743             valDis += "[value-" + NbSelect + "]";
744             editDis += myListBox.options[i].value + "=[value-" + NbSelect + "]";
745         }
746         if (queryType == "selectall") {
747             query = "SELECT * FROM `" + table + "` WHERE 1";
748         } else if (queryType == "select") {
749             query = "SELECT " + chaineAj + " FROM `" + table + "` WHERE 1";
750         } else if (queryType == "insert") {
751                query = "INSERT INTO `" + table + "`(" + chaineAj + ") VALUES (" + valDis + ")";
752         } else if (queryType == "update") {
753             query = "UPDATE `" + table + "` SET " + editDis + " WHERE 1";
754         } else if(queryType == "delete") {
755             query = "DELETE FROM `" + table + "` WHERE 1";
756         }
757         document.sqlform.sql_query.value = query;
758         sql_box_locked = false;
759     }
764   * Inserts multiple fields.
765   *
766   */
767 function insertValueQuery() {
768     var myQuery = document.sqlform.sql_query;
769     var myListBox = document.sqlform.dummy;
771     if(myListBox.options.length > 0) {
772         sql_box_locked = true;
773         var chaineAj = "";
774         var NbSelect = 0;
775         for(var i=0; i<myListBox.options.length; i++) {
776             if (myListBox.options[i].selected){
777                 NbSelect++;
778                 if (NbSelect > 1)
779                     chaineAj += ", ";
780                 chaineAj += myListBox.options[i].value;
781             }
782         }
784         //IE support
785         if (document.selection) {
786             myQuery.focus();
787             sel = document.selection.createRange();
788             sel.text = chaineAj;
789             document.sqlform.insert.focus();
790         }
791         //MOZILLA/NETSCAPE support
792         else if (document.sqlform.sql_query.selectionStart || document.sqlform.sql_query.selectionStart == "0") {
793             var startPos = document.sqlform.sql_query.selectionStart;
794             var endPos = document.sqlform.sql_query.selectionEnd;
795             var chaineSql = document.sqlform.sql_query.value;
797             myQuery.value = chaineSql.substring(0, startPos) + chaineAj + chaineSql.substring(endPos, chaineSql.length);
798         } else {
799             myQuery.value += chaineAj;
800         }
801         sql_box_locked = false;
802     }
806   * listbox redirection
807   */
808 function goToUrl(selObj, goToLocation) {
809     eval("document.location.href = '" + goToLocation + "pos=" + selObj.options[selObj.selectedIndex].value + "'");
813  * getElement
814  */
815 function getElement(e,f){
816     if(document.layers){
817         f=(f)?f:self;
818         if(f.document.layers[e]) {
819             return f.document.layers[e];
820         }
821         for(W=0;W<f.document.layers.length;W++) {
822             return(getElement(e,f.document.layers[W]));
823         }
824     }
825     if(document.all) {
826         return document.all[e];
827     }
828     return document.getElementById(e);
832   * Refresh the WYSIWYG scratchboard after changes have been made
833   */
834 function refreshDragOption(e) {
835     var elm = $('#' + e);
836     if (elm.css('visibility') == 'visible') {
837         refreshLayout();
838         TableDragInit();
839     }
843   * Refresh/resize the WYSIWYG scratchboard
844   */
845 function refreshLayout() {
846     var elm = $('#pdflayout')
847     var orientation = $('#orientation_opt').val();
848     if($('#paper_opt').length==1){
849         var paper = $('#paper_opt').val();
850     }else{
851         var paper = 'A4';
852     }
853     if (orientation == 'P') {
854         posa = 'x';
855         posb = 'y';
856     } else {
857         posa = 'y';
858         posb = 'x';
859     }
860     elm.css('width', pdfPaperSize(paper, posa) + 'px');
861     elm.css('height', pdfPaperSize(paper, posb) + 'px');
865   * Show/hide the WYSIWYG scratchboard
866   */
867 function ToggleDragDrop(e) {
868     var elm = $('#' + e);
869     if (elm.css('visibility') == 'hidden') {
870         PDFinit(); /* Defined in pdf_pages.php */
871         elm.css('visibility', 'visible');
872         elm.css('display', 'block');
873         $('#showwysiwyg').val('1')
874     } else {
875         elm.css('visibility', 'hidden');
876         elm.css('display', 'none');
877         $('#showwysiwyg').val('0')
878     }
882   * PDF scratchboard: When a position is entered manually, update
883   * the fields inside the scratchboard.
884   */
885 function dragPlace(no, axis, value) {
886     var elm = $('#table_' + no);
887     if (axis == 'x') {
888         elm.css('left', value + 'px');
889     } else {
890         elm.css('top', value + 'px');
891     }
895  * Returns paper sizes for a given format
896  */
897 function pdfPaperSize(format, axis) {
898     switch (format.toUpperCase()) {
899         case '4A0':
900             if (axis == 'x') return 4767.87; else return 6740.79;
901             break;
902         case '2A0':
903             if (axis == 'x') return 3370.39; else return 4767.87;
904             break;
905         case 'A0':
906             if (axis == 'x') return 2383.94; else return 3370.39;
907             break;
908         case 'A1':
909             if (axis == 'x') return 1683.78; else return 2383.94;
910             break;
911         case 'A2':
912             if (axis == 'x') return 1190.55; else return 1683.78;
913             break;
914         case 'A3':
915             if (axis == 'x') return 841.89; else return 1190.55;
916             break;
917         case 'A4':
918             if (axis == 'x') return 595.28; else return 841.89;
919             break;
920         case 'A5':
921             if (axis == 'x') return 419.53; else return 595.28;
922             break;
923         case 'A6':
924             if (axis == 'x') return 297.64; else return 419.53;
925             break;
926         case 'A7':
927             if (axis == 'x') return 209.76; else return 297.64;
928             break;
929         case 'A8':
930             if (axis == 'x') return 147.40; else return 209.76;
931             break;
932         case 'A9':
933             if (axis == 'x') return 104.88; else return 147.40;
934             break;
935         case 'A10':
936             if (axis == 'x') return 73.70; else return 104.88;
937             break;
938         case 'B0':
939             if (axis == 'x') return 2834.65; else return 4008.19;
940             break;
941         case 'B1':
942             if (axis == 'x') return 2004.09; else return 2834.65;
943             break;
944         case 'B2':
945             if (axis == 'x') return 1417.32; else return 2004.09;
946             break;
947         case 'B3':
948             if (axis == 'x') return 1000.63; else return 1417.32;
949             break;
950         case 'B4':
951             if (axis == 'x') return 708.66; else return 1000.63;
952             break;
953         case 'B5':
954             if (axis == 'x') return 498.90; else return 708.66;
955             break;
956         case 'B6':
957             if (axis == 'x') return 354.33; else return 498.90;
958             break;
959         case 'B7':
960             if (axis == 'x') return 249.45; else return 354.33;
961             break;
962         case 'B8':
963             if (axis == 'x') return 175.75; else return 249.45;
964             break;
965         case 'B9':
966             if (axis == 'x') return 124.72; else return 175.75;
967             break;
968         case 'B10':
969             if (axis == 'x') return 87.87; else return 124.72;
970             break;
971         case 'C0':
972             if (axis == 'x') return 2599.37; else return 3676.54;
973             break;
974         case 'C1':
975             if (axis == 'x') return 1836.85; else return 2599.37;
976             break;
977         case 'C2':
978             if (axis == 'x') return 1298.27; else return 1836.85;
979             break;
980         case 'C3':
981             if (axis == 'x') return 918.43; else return 1298.27;
982             break;
983         case 'C4':
984             if (axis == 'x') return 649.13; else return 918.43;
985             break;
986         case 'C5':
987             if (axis == 'x') return 459.21; else return 649.13;
988             break;
989         case 'C6':
990             if (axis == 'x') return 323.15; else return 459.21;
991             break;
992         case 'C7':
993             if (axis == 'x') return 229.61; else return 323.15;
994             break;
995         case 'C8':
996             if (axis == 'x') return 161.57; else return 229.61;
997             break;
998         case 'C9':
999             if (axis == 'x') return 113.39; else return 161.57;
1000             break;
1001         case 'C10':
1002             if (axis == 'x') return 79.37; else return 113.39;
1003             break;
1004         case 'RA0':
1005             if (axis == 'x') return 2437.80; else return 3458.27;
1006             break;
1007         case 'RA1':
1008             if (axis == 'x') return 1729.13; else return 2437.80;
1009             break;
1010         case 'RA2':
1011             if (axis == 'x') return 1218.90; else return 1729.13;
1012             break;
1013         case 'RA3':
1014             if (axis == 'x') return 864.57; else return 1218.90;
1015             break;
1016         case 'RA4':
1017             if (axis == 'x') return 609.45; else return 864.57;
1018             break;
1019         case 'SRA0':
1020             if (axis == 'x') return 2551.18; else return 3628.35;
1021             break;
1022         case 'SRA1':
1023             if (axis == 'x') return 1814.17; else return 2551.18;
1024             break;
1025         case 'SRA2':
1026             if (axis == 'x') return 1275.59; else return 1814.17;
1027             break;
1028         case 'SRA3':
1029             if (axis == 'x') return 907.09; else return 1275.59;
1030             break;
1031         case 'SRA4':
1032             if (axis == 'x') return 637.80; else return 907.09;
1033             break;
1034         case 'LETTER':
1035             if (axis == 'x') return 612.00; else return 792.00;
1036             break;
1037         case 'LEGAL':
1038             if (axis == 'x') return 612.00; else return 1008.00;
1039             break;
1040         case 'EXECUTIVE':
1041             if (axis == 'x') return 521.86; else return 756.00;
1042             break;
1043         case 'FOLIO':
1044             if (axis == 'x') return 612.00; else return 936.00;
1045             break;
1046     } // end switch
1048     return 0;
1052  * for playing media from the BLOB repository
1054  * @param   var
1055  * @param   var     url_params  main purpose is to pass the token
1056  * @param   var     bs_ref      BLOB repository reference
1057  * @param   var     m_type      type of BLOB repository media
1058  * @param   var     w_width     width of popup window
1059  * @param   var     w_height    height of popup window
1060  */
1061 function popupBSMedia(url_params, bs_ref, m_type, is_cust_type, w_width, w_height)
1063     // if width not specified, use default
1064     if (w_width == undefined)
1065         w_width = 640;
1067     // if height not specified, use default
1068     if (w_height == undefined)
1069         w_height = 480;
1071     // open popup window (for displaying video/playing audio)
1072     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');
1076  * popups a request for changing MIME types for files in the BLOB repository
1078  * @param   var     db                      database name
1079  * @param   var     table                   table name
1080  * @param   var     reference               BLOB repository reference
1081  * @param   var     current_mime_type       current MIME type associated with BLOB repository reference
1082  */
1083 function requestMIMETypeChange(db, table, reference, current_mime_type)
1085     // no mime type specified, set to default (nothing)
1086     if (undefined == current_mime_type)
1087         current_mime_type = "";
1089     // prompt user for new mime type
1090     var new_mime_type = prompt("Enter custom MIME type", current_mime_type);
1092     // if new mime_type is specified and is not the same as the previous type, request for mime type change
1093     if (new_mime_type && new_mime_type != current_mime_type)
1094         changeMIMEType(db, table, reference, new_mime_type);
1098  * changes MIME types for files in the BLOB repository
1100  * @param   var     db              database name
1101  * @param   var     table           table name
1102  * @param   var     reference       BLOB repository reference
1103  * @param   var     mime_type       new MIME type to be associated with BLOB repository reference
1104  */
1105 function changeMIMEType(db, table, reference, mime_type)
1107     // specify url and parameters for jQuery POST
1108     var mime_chg_url = 'bs_change_mime_type.php';
1109     var params = {bs_db: db, bs_table: table, bs_reference: reference, bs_new_mime_type: mime_type};
1111     // jQuery POST
1112     jQuery.post(mime_chg_url, params);
1116  * Jquery Coding for inline editing SQL_QUERY
1117  */
1118 $(document).ready(function(){
1119     $(".inline_edit_sql").live('click', function(){
1120         var server     = $(this).prev().find("input[name='server']").val();
1121         var db         = $(this).prev().find("input[name='db']").val();
1122         var table      = $(this).prev().find("input[name='table']").val();
1123         var token      = $(this).prev().find("input[name='token']").val();
1124         var sql_query  = $(this).prev().find("input[name='sql_query']").val();
1125         var $inner_sql = $(this).parent().prev().find('.inner_sql');
1126         var old_text   = $inner_sql.html();
1128         var new_content = "<textarea name=\"sql_query_edit\" id=\"sql_query_edit\">" + sql_query + "</textarea>\n";
1129         new_content    += "<input type=\"button\" class=\"btnSave\" value=\"" + PMA_messages['strGo'] + "\">\n";
1130         new_content    += "<input type=\"button\" class=\"btnDiscard\" value=\"" + PMA_messages['strCancel'] + "\">\n";
1131         $inner_sql.replaceWith(new_content);
1132         $(".btnSave").each(function(){
1133             $(this).click(function(){
1134                 sql_query = $(this).prev().val();
1135                 window.location.replace("import.php"
1136                                       + "?server=" + encodeURIComponent(server)
1137                                       + "&db=" + encodeURIComponent(db)
1138                                       + "&table=" + encodeURIComponent(table)
1139                                       + "&sql_query=" + encodeURIComponent(sql_query)
1140                                       + "&show_query=1"
1141                                       + "&token=" + token);
1142             });
1143         });
1144         $(".btnDiscard").each(function(){
1145             $(this).click(function(){
1146                 $(this).closest(".sql").html("<span class=\"syntax\"><span class=\"inner_sql\">" + old_text + "</span></span>");
1147             });
1148         });
1149         return false;
1150     });
1152     $('.sqlbutton').click(function(evt){
1153         if (evt.target.id == 'clear') {
1154             $('#sqlquery').val('');
1155         } else {
1156             insertQuery(evt.target.id);
1157         }
1158         return false;
1159     });
1161     $("#export_type").change(function(){
1162         if($("#export_type").val()=='svg'){
1163             $("#show_grid_opt").attr("disabled","disabled");
1164             $("#orientation_opt").attr("disabled","disabled");
1165             $("#with_doc").attr("disabled","disabled");
1166             $("#show_table_dim_opt").removeAttr("disabled");
1167             $("#all_table_same_wide").removeAttr("disabled");
1168             $("#paper_opt").removeAttr("disabled","disabled");
1169             $("#show_color_opt").removeAttr("disabled","disabled");
1170             //$(this).css("background-color","yellow");
1171         }else if($("#export_type").val()=='dia'){
1172             $("#show_grid_opt").attr("disabled","disabled");
1173             $("#with_doc").attr("disabled","disabled");
1174             $("#show_table_dim_opt").attr("disabled","disabled");
1175             $("#all_table_same_wide").attr("disabled","disabled");
1176             $("#paper_opt").removeAttr("disabled","disabled");
1177             $("#show_color_opt").removeAttr("disabled","disabled");
1178             $("#orientation_opt").removeAttr("disabled","disabled");
1179         }else if($("#export_type").val()=='eps'){
1180             $("#show_grid_opt").attr("disabled","disabled");
1181             $("#orientation_opt").removeAttr("disabled");
1182             $("#with_doc").attr("disabled","disabled");
1183             $("#show_table_dim_opt").attr("disabled","disabled");
1184             $("#all_table_same_wide").attr("disabled","disabled");
1185             $("#paper_opt").attr("disabled","disabled");
1186             $("#show_color_opt").attr("disabled","disabled");
1188         }else if($("#export_type").val()=='pdf'){
1189             $("#show_grid_opt").removeAttr("disabled");
1190             $("#orientation_opt").removeAttr("disabled");
1191             $("#with_doc").removeAttr("disabled","disabled");
1192             $("#show_table_dim_opt").removeAttr("disabled","disabled");
1193             $("#all_table_same_wide").removeAttr("disabled","disabled");
1194             $("#paper_opt").removeAttr("disabled","disabled");
1195             $("#show_color_opt").removeAttr("disabled","disabled");
1196         }else{
1197             // nothing
1198         }
1199     });
1201     $('#sqlquery').focus();
1202     if ($('#input_username')) {
1203         if ($('#input_username').val() == '') {
1204             $('#input_username').focus();
1205         } else {
1206             $('#input_password').focus();
1207         }
1208     }
1212  * Show a message on the top of the page for an Ajax request
1214  * @param   var     message     string containing the message to be shown.
1215  *                              optional, defaults to 'Loading...'
1216  * @param   var     timeout     number of milliseconds for the message to be visible
1217  *                              optional, defaults to 5000
1218  */
1220 function PMA_ajaxShowMessage(message, timeout) {
1222     //Handle the case when a empty data.message is passed.  We don't want the empty message
1223     if(message == '') {
1224         return true;
1225     }
1227     /**
1228      * @var msg String containing the message that has to be displayed
1229      * @default PMA_messages['strLoading']
1230      */
1231     if(!message) {
1232         var msg = PMA_messages['strLoading'];
1233     }
1234     else {
1235         var msg = message;
1236     }
1238     /**
1239      * @var timeout Number of milliseconds for which {@link msg} will be visible
1240      * @default 5000 ms
1241      */
1242     if(!timeout) {
1243         var to = 5000;
1244     }
1245     else {
1246         var to = timeout;
1247     }
1249     if( !ajax_message_init) {
1250         //For the first time this function is called, append a new div
1251         $(function(){
1252             $('<div id="loading_parent"></div>')
1253             .insertBefore("#serverinfo");
1255             $('<span id="loading" class="ajax_notification"></span>')
1256             .appendTo("#loading_parent")
1257             .html(msg)
1258             .fadeIn('medium')
1259             .delay(to)
1260             .fadeOut('medium', function(){
1261                 $(this)
1262                 .html("") //Clear the message
1263                 .hide();
1264             });
1265         }, 'top.frame_content');
1266         ajax_message_init = true;
1267     }
1268     else {
1269         //Otherwise, just show the div again after inserting the message
1270         $("#loading")
1271         .stop(true, true)
1272         .html(msg)
1273         .fadeIn('medium')
1274         .delay(to)
1275         .fadeOut('medium', function() {
1276             $(this)
1277             .html("")
1278             .hide();
1279         })
1280     }
1281         
1282         return $("#loading");
1286  * Removes the message shown for an Ajax operation when it's completed
1287  */
1288 function PMA_ajaxRemoveMessage($this_msgbox) {
1289     $this_msgbox
1290      .stop(true, true)
1291      .fadeOut('medium', function() {
1292         $this_msgbox.hide();
1293      });
1297  * Hides/shows the "Open in ENUM/SET editor" message, depending on the data type of the column currently selected
1298  */
1299 function PMA_showNoticeForEnum(selectElement) {
1300     var enum_notice_id = selectElement.attr("id").split("_")[1];
1301     enum_notice_id += "_" + (parseInt(selectElement.attr("id").split("_")[2]) + 1);
1302     var selectedType = selectElement.attr("value");
1303     if (selectedType == "ENUM" || selectedType == "SET") {
1304         $("p[id='enum_notice_" + enum_notice_id + "']").show();
1305     } else {
1306         $("p[id='enum_notice_" + enum_notice_id + "']").hide();
1307     }
1311  * jQuery function that uses jQueryUI's dialogs to confirm with user. Does not
1312  *  return a jQuery object yet and hence cannot be chained
1314  * @param   string      question
1315  * @param   string      url         URL to be passed to the callbackFn to make
1316  *                                  an Ajax call to
1317  * @param   function    callbackFn  callback to execute after user clicks on OK
1318  */
1320 jQuery.fn.PMA_confirm = function(question, url, callbackFn) {
1321     if (PMA_messages['strDoYouReally'] == '') {
1322         return true;
1323     }
1325     /**
1326      *  @var    button_options  Object that stores the options passed to jQueryUI
1327      *                          dialog
1328      */
1329     var button_options = {};
1330     button_options[PMA_messages['strOK']] = function(){
1331                                                 $(this).dialog("close").remove();
1333                                                 if($.isFunction(callbackFn)) {
1334                                                     callbackFn.call(this, url);
1335                                                 }
1336                                             };
1337     button_options[PMA_messages['strCancel']] = function() {$(this).dialog("close").remove();}
1339     $('<div id="confirm_dialog"></div>')
1340     .prepend(question)
1341     .dialog({buttons: button_options});
1345  * jQuery function to sort a table's body after a new row has been appended to it.
1346  * Also fixes the even/odd classes of the table rows at the end.
1348  * @param   string      text_selector   string to select the sortKey's text
1350  * @return  jQuery Object for chaining purposes
1351  */
1352 jQuery.fn.PMA_sort_table = function(text_selector) {
1353     return this.each(function() {
1355         /**
1356          * @var table_body  Object referring to the table's <tbody> element
1357          */
1358         var table_body = $(this);
1359         /**
1360          * @var rows    Object referring to the collection of rows in {@link table_body}
1361          */
1362         var rows = $(this).find('tr').get();
1364         //get the text of the field that we will sort by
1365         $.each(rows, function(index, row) {
1366             row.sortKey = $.trim($(row).find(text_selector).text().toLowerCase());
1367         })
1369         //get the sorted order
1370         rows.sort(function(a,b) {
1371             if(a.sortKey < b.sortKey) {
1372                 return -1;
1373             }
1374             if(a.sortKey > b.sortKey) {
1375                 return 1;
1376             }
1377             return 0;
1378         })
1380         //pull out each row from the table and then append it according to it's order
1381         $.each(rows, function(index, row) {
1382             $(table_body).append(row);
1383             row.sortKey = null;
1384         })
1386         //Re-check the classes of each row
1387         $(this).find('tr:odd')
1388         .removeClass('even').addClass('odd')
1389         .end()
1390         .find('tr:even')
1391         .removeClass('odd').addClass('even');
1392     })
1396  * jQuery coding for 'Create Table'.  Used on db_operations.php,
1397  * db_structure.php and db_tracking.php (i.e., wherever
1398  * libraries/display_create_table.lib.php is used)
1400  * Attach Ajax Event handlers for Create Table
1401  */
1402 $(document).ready(function() {
1404     /**
1405      * Attach event handler to the submit action of the create table minimal form
1406      * and retrieve the full table form and display it in a dialog
1407      *
1408      * @uses    PMA_ajaxShowMessage()
1409      */
1410     $("#create_table_form_minimal.ajax").live('submit', function(event) {
1411         event.preventDefault();
1412         $form = $(this);
1414         /* @todo Validate this form! */
1416         /**
1417          *  @var    button_options  Object that stores the options passed to jQueryUI
1418          *                          dialog
1419          */
1420         var button_options = {};
1421         // in the following function we need to use $(this)
1422         button_options[PMA_messages['strCancel']] = function() {$(this).dialog('close').remove();}
1424         var button_options_error = {};
1425         button_options_error[PMA_messages['strOK']] = function() {$(this).dialog('close').remove();}
1427         var $msgbox = PMA_ajaxShowMessage();
1428         PMA_prepareForAjaxRequest($form);
1430         $.get($form.attr('action'), $form.serialize(), function(data) {
1431             //in the case of an error, show the error message returned.
1432             if (data.success != undefined && data.success == false) {
1433                 $('<div id="create_table_dialog"></div>')
1434                 .append(data.error)
1435                 .dialog({
1436                     title: PMA_messages['strCreateTable'],
1437                     height: 230,
1438                     width: 900,
1439                     open: PMA_verifyTypeOfAllColumns,
1440                     buttons : button_options_error
1441                 })// end dialog options
1442                 //remove the redundant [Back] link in the error message.
1443                 .find('fieldset').remove();
1444             } else {
1445                 $('<div id="create_table_dialog"></div>')
1446                 .append(data)
1447                 .dialog({
1448                     title: PMA_messages['strCreateTable'],
1449                     height: 600,
1450                     width: 900,
1451                     open: PMA_verifyTypeOfAllColumns,
1452                     buttons : button_options
1453                 }); // end dialog options
1454             }            
1455             PMA_ajaxRemoveMessage($msgbox);
1456         }) // end $.get()
1458         // empty table name and number of columns from the minimal form
1459         $form.find('input[name=table],input[name=num_fields]').val('');
1460     });
1462     /**
1463      * Attach event handler for submission of create table form (save)
1464      *
1465      * @uses    PMA_ajaxShowMessage()
1466      * @uses    $.PMA_sort_table()
1467      *
1468      */
1469     // .live() must be called after a selector, see http://api.jquery.com/live
1470     $("#create_table_form input[name=do_save_data]").live('click', function(event) {
1471         event.preventDefault();
1473         /**
1474          *  @var    the_form    object referring to the create table form
1475          */
1476         var $form = $("#create_table_form");
1478         /*
1479          * First validate the form; if there is a problem, avoid submitting it
1480          *
1481          * checkTableEditForm() needs a pure element and not a jQuery object,
1482          * this is why we pass $form[0] as a parameter (the jQuery object
1483          * is actually an array of DOM elements)
1484          */
1486         if (checkTableEditForm($form[0], $form.find('input[name=orig_num_fields]').val())) {
1487             // OK, form passed validation step
1488             if ($form.hasClass('ajax')) {
1489                 PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
1490                 PMA_prepareForAjaxRequest($form);
1491                 //User wants to submit the form
1492                 $.post($form.attr('action'), $form.serialize() + "&do_save_data=" + $(this).val(), function(data) {
1493                     if(data.success == true) {
1494                         $('#properties_message')
1495                          .removeClass('error')
1496                          .html('');
1497                         PMA_ajaxShowMessage(data.message);
1498                         // Only if the create table dialog (distinct panel) exists
1499                         if ($("#create_table_dialog").length > 0) {
1500                             $("#create_table_dialog").dialog("close").remove();
1501                         }
1503                         /**
1504                          * @var tables_table    Object referring to the <tbody> element that holds the list of tables
1505                          */
1506                         var tables_table = $("#tablesForm").find("tbody").not("#tbl_summary_row");
1507                         // this is the first table created in this db
1508                         if (tables_table.length == 0) {
1509                             if (window.parent && window.parent.frame_content) {
1510                                 window.parent.frame_content.location.reload();
1511                             }
1512                         } else {
1513                             /**
1514                              * @var curr_last_row   Object referring to the last <tr> element in {@link tables_table}
1515                              */
1516                             var curr_last_row = $(tables_table).find('tr:last');
1517                             /**
1518                              * @var curr_last_row_index_string   String containing the index of {@link curr_last_row}
1519                              */
1520                             var curr_last_row_index_string = $(curr_last_row).find('input:checkbox').attr('id').match(/\d+/)[0];
1521                             /**
1522                              * @var curr_last_row_index Index of {@link curr_last_row}
1523                              */
1524                             var curr_last_row_index = parseFloat(curr_last_row_index_string);
1525                             /**
1526                              * @var new_last_row_index   Index of the new row to be appended to {@link tables_table}
1527                              */
1528                             var new_last_row_index = curr_last_row_index + 1;
1529                             /**
1530                              * @var new_last_row_id String containing the id of the row to be appended to {@link tables_table}
1531                              */
1532                             var new_last_row_id = 'checkbox_tbl_' + new_last_row_index;
1534                             data.new_table_string = data.new_table_string.replace(/checkbox_tbl_/, new_last_row_id);
1535                             //append to table
1536                             $(data.new_table_string)
1537                              .appendTo(tables_table);
1539                             //Sort the table
1540                             $(tables_table).PMA_sort_table('th');
1541                         }
1543                         //Refresh navigation frame as a new table has been added
1544                         if (window.parent && window.parent.frame_navigation) {
1545                             window.parent.frame_navigation.location.reload();
1546                         }
1547                     } else {
1548                         $('#properties_message')
1549                          .addClass('error')
1550                          .html(data.error);
1551                         // scroll to the div containing the error message
1552                         $('#properties_message')[0].scrollIntoView();
1553                     }
1554                 }) // end $.post()
1555             } // end if ($form.hasClass('ajax')
1556             else {
1557                 // non-Ajax submit
1558                 $form.append('<input type="hidden" name="do_save_data" value="save" />');
1559                 $form.submit();
1560             }
1561         } // end if (checkTableEditForm() )
1562     }) // end create table form (save)
1564     /**
1565      * Attach event handler for create table form (add fields)
1566      *
1567      * @uses    PMA_ajaxShowMessage()
1568      * @uses    $.PMA_sort_table()
1569      * @uses    window.parent.refreshNavigation()
1570      *
1571      */
1572     // .live() must be called after a selector, see http://api.jquery.com/live
1573     $("#create_table_form.ajax input[name=submit_num_fields]").live('click', function(event) {
1574         event.preventDefault();
1576         /**
1577          *  @var    the_form    object referring to the create table form
1578          */
1579         var $form = $("#create_table_form");
1581         var $msgbox = PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
1582         PMA_prepareForAjaxRequest($form);
1584         //User wants to add more fields to the table
1585         $.post($form.attr('action'), $form.serialize() + "&submit_num_fields=" + $(this).val(), function(data) {
1586             // if 'create_table_dialog' exists
1587             if ($("#create_table_dialog").length > 0) {
1588                 $("#create_table_dialog").html(data);
1589             }
1590             // if 'create_table_div' exists
1591             if ($("#create_table_div").length > 0) {
1592                 $("#create_table_div").html(data);
1593             }
1594             PMA_verifyTypeOfAllColumns();
1595             PMA_ajaxRemoveMessage($msgbox);    
1596         }) //end $.post()
1598     }) // end create table form (add fields)
1600 }, 'top.frame_content'); //end $(document).ready for 'Create Table'
1603  * Attach Ajax event handlers for Drop Trigger.  Used on tbl_structure.php
1604  * @see $cfg['AjaxEnable']
1605  */
1606 $(document).ready(function() {
1608     $(".drop_trigger_anchor").live('click', function(event) {
1609         event.preventDefault();
1611         $anchor = $(this);
1612         /**
1613          * @var curr_row    Object reference to the current trigger's <tr>
1614          */
1615         var $curr_row = $anchor.parents('tr');
1616         /**
1617          * @var question    String containing the question to be asked for confirmation
1618          */
1619         var question = 'DROP TRIGGER IF EXISTS `' + $curr_row.children('td:first').text() + '`';
1621         $anchor.PMA_confirm(question, $anchor.attr('href'), function(url) {
1623             PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
1624             $.get(url, {'is_js_confirmed': 1, 'ajax_request': true}, function(data) {
1625                 if(data.success == true) {
1626                     PMA_ajaxShowMessage(data.message);
1627                     $("#topmenucontainer")
1628                     .next('div')
1629                     .remove()
1630                     .end()
1631                     .after(data.sql_query);
1632                     $curr_row.hide("medium").remove();
1633                 }
1634                 else {
1635                     PMA_ajaxShowMessage(data.error);
1636                 }
1637             }) // end $.get()
1638         }) // end $.PMA_confirm()
1639     }) // end $().live()
1640 }, 'top.frame_content'); //end $(document).ready() for Drop Trigger
1643  * Attach Ajax event handlers for Drop Database. Moved here from db_structure.js
1644  * as it was also required on db_create.php
1646  * @uses    $.PMA_confirm()
1647  * @uses    PMA_ajaxShowMessage()
1648  * @uses    window.parent.refreshNavigation()
1649  * @uses    window.parent.refreshMain()
1650  * @see $cfg['AjaxEnable']
1651  */
1652 $(document).ready(function() {
1653     $("#drop_db_anchor").live('click', function(event) {
1654         event.preventDefault();
1656         //context is top.frame_content, so we need to use window.parent.db to access the db var
1657         /**
1658          * @var question    String containing the question to be asked for confirmation
1659          */
1660         var question = PMA_messages['strDropDatabaseStrongWarning'] + '\n' + PMA_messages['strDoYouReally'] + ' :\n' + 'DROP DATABASE ' + escapeHtml(window.parent.db);
1662         $(this).PMA_confirm(question, $(this).attr('href') ,function(url) {
1664             PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
1665             $.get(url, {'is_js_confirmed': '1', 'ajax_request': true}, function(data) {
1666                 //Database deleted successfully, refresh both the frames
1667                 window.parent.refreshNavigation();
1668                 window.parent.refreshMain();
1669             }) // end $.get()
1670         }); // end $.PMA_confirm()
1671     }); //end of Drop Database Ajax action
1672 }) // end of $(document).ready() for Drop Database
1675  * Attach Ajax event handlers for 'Create Database'.  Used wherever libraries/
1676  * display_create_database.lib.php is used, ie main.php and server_databases.php
1678  * @uses    PMA_ajaxShowMessage()
1679  * @see $cfg['AjaxEnable']
1680  */
1681 $(document).ready(function() {
1683     $('#create_database_form.ajax').live('submit', function(event) {
1684         event.preventDefault();
1686         $form = $(this);
1688         PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
1689         PMA_prepareForAjaxRequest($form);
1691         $.post($form.attr('action'), $form.serialize(), function(data) {
1692             if(data.success == true) {
1693                 PMA_ajaxShowMessage(data.message);
1695                 //Append database's row to table
1696                 $("#tabledatabases")
1697                 .find('tbody')
1698                 .append(data.new_db_string)
1699                 .PMA_sort_table('.name')
1700                 .find('#db_summary_row')
1701                 .appendTo('#tabledatabases tbody')
1702                 .removeClass('odd even');
1704                 var $databases_count_object = $('#databases_count');
1705                 var databases_count = parseInt($databases_count_object.text());
1706                 $databases_count_object.text(++databases_count);
1707                 //Refresh navigation frame as a new database has been added
1708                 if (window.parent && window.parent.frame_navigation) {
1709                     window.parent.frame_navigation.location.reload();
1710                 }
1711             }
1712             else {
1713                 PMA_ajaxShowMessage(data.error);
1714             }
1715         }) // end $.post()
1716     }) // end $().live()
1717 })  // end $(document).ready() for Create Database
1720  * Attach Ajax event handlers for 'Change Password' on main.php
1721  */
1722 $(document).ready(function() {
1724     /**
1725      * Attach Ajax event handler on the change password anchor
1726      * @see $cfg['AjaxEnable']
1727      */
1728     $('#change_password_anchor.dialog_active').live('click',function(event) {
1729         event.preventDefault();
1730         return false;
1731         });
1732     $('#change_password_anchor.ajax').live('click', function(event) {
1733         event.preventDefault();
1734         $(this).removeClass('ajax').addClass('dialog_active');
1735         /**
1736          * @var button_options  Object containing options to be passed to jQueryUI's dialog
1737          */
1738         var button_options = {};
1739         button_options[PMA_messages['strCancel']] = function() {$(this).dialog('close').remove();}
1740         $.get($(this).attr('href'), {'ajax_request': true}, function(data) {
1741             $('<div id="change_password_dialog"></div>')
1742             .dialog({
1743                 title: PMA_messages['strChangePassword'],
1744                 width: 600,
1745                 close: function(ev,ui) {$(this).remove();}, 
1746                 buttons : button_options,
1747                 beforeClose: function(ev,ui){ $('#change_password_anchor.dialog_active').removeClass('dialog_active').addClass('ajax')}
1748             })
1749             .append(data);
1750             displayPasswordGenerateButton();
1751         }) // end $.get()
1752     }) // end handler for change password anchor
1754     /**
1755      * Attach Ajax event handler for Change Password form submission
1756      *
1757      * @uses    PMA_ajaxShowMessage()
1758      * @see $cfg['AjaxEnable']
1759      */
1760     $("#change_password_form.ajax").find('input[name=change_pw]').live('click', function(event) {
1761         event.preventDefault();
1763         /**
1764          * @var the_form    Object referring to the change password form
1765          */
1766         var the_form = $("#change_password_form");
1768         /**
1769          * @var this_value  String containing the value of the submit button.
1770          * Need to append this for the change password form on Server Privileges
1771          * page to work
1772          */
1773         var this_value = $(this).val();
1775         var $msgbox = PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
1776         $(the_form).append('<input type="hidden" name="ajax_request" value="true" />');
1778         $.post($(the_form).attr('action'), $(the_form).serialize() + '&change_pw='+ this_value, function(data) {
1779             if(data.success == true) {
1780                 $("#topmenucontainer").after(data.sql_query);
1781                 $("#change_password_dialog").hide().remove();
1782                 $("#edit_user_dialog").dialog("close").remove();
1783                 $('#change_password_anchor.dialog_active').removeClass('dialog_active').addClass('ajax');
1784                 PMA_ajaxRemoveMessage($msgbox); 
1785             }
1786             else {
1787                 PMA_ajaxShowMessage(data.error);
1788             }
1789         }) // end $.post()
1790     }) // end handler for Change Password form submission
1791 }) // end $(document).ready() for Change Password
1794  * Toggle the hiding/showing of the "Open in ENUM/SET editor" message when
1795  * the page loads and when the selected data type changes
1796  */
1797 $(document).ready(function() {
1798     // is called here for normal page loads and also when opening
1799     // the Create table dialog
1800     PMA_verifyTypeOfAllColumns();
1801     //
1802     // needs live() to work also in the Create Table dialog
1803     $("select[class='column_type']").live('change', function() {
1804         PMA_showNoticeForEnum($(this));
1805     });
1808 function PMA_verifyTypeOfAllColumns() {
1809     $("select[class='column_type']").each(function() {
1810         PMA_showNoticeForEnum($(this));
1811     });
1815  * Closes the ENUM/SET editor and removes the data in it
1816  */
1817 function disable_popup() {
1818     $("#popup_background").fadeOut("fast");
1819     $("#enum_editor").fadeOut("fast");
1820     // clear the data from the text boxes
1821     $("#enum_editor #values input").remove();
1822     $("#enum_editor input[type='hidden']").remove();
1826  * Opens the ENUM/SET editor and controls its functions
1827  */
1828 $(document).ready(function() {
1829     // Needs live() to work also in the Create table dialog
1830     $("a[class='open_enum_editor']").live('click', function() {
1831         // Center the popup
1832         var windowWidth = document.documentElement.clientWidth;
1833         var windowHeight = document.documentElement.clientHeight;
1834         var popupWidth = windowWidth/2;
1835         var popupHeight = windowHeight*0.8;
1836         var popupOffsetTop = windowHeight/2 - popupHeight/2;
1837         var popupOffsetLeft = windowWidth/2 - popupWidth/2;
1838         $("#enum_editor").css({"position":"absolute", "top": popupOffsetTop, "left": popupOffsetLeft, "width": popupWidth, "height": popupHeight});
1840         // Make it appear
1841         $("#popup_background").css({"opacity":"0.7"});
1842         $("#popup_background").fadeIn("fast");
1843         $("#enum_editor").fadeIn("fast");
1845         // Get the values as a string
1846         var inputstring = $(this)
1847             .parent()
1848             .prev("input")
1849             .val();
1850         // Escape html entities
1851         inputstring = $('<div/>')
1852             .text(inputstring)
1853             .html();
1854         // Parse the values, escaping quotes and
1855         // slashes on the fly, into an array
1856         var values = [];
1857         var in_string = false;
1858         var curr, next, buffer = '';
1859         for (var i=0; i<inputstring.length; i++) {
1860             curr = inputstring.charAt(i);
1861             next = i == inputstring.length ? '' : inputstring.charAt(i+1);
1862             if (! in_string && curr == "'") {
1863                 in_string = true;
1864             } else if (in_string && curr == "\\" && next == "\\") {
1865                 buffer += "&#92;";
1866                 i++;
1867             } else if (in_string && next == "'" && (curr == "'" || curr == "\\")) {
1868                 buffer += "&#39;";
1869                 i++;
1870             } else if (in_string && curr == "'") {
1871                 in_string = false;
1872                 values.push(buffer);
1873                 buffer = '';
1874             } else if (in_string) {
1875                  buffer += curr;
1876             }
1877         }
1878         if (buffer.length > 0) {
1879             values.push(buffer);
1880         }
1881         // Add the parsed values to the editor
1882         for (var i=0; i<values.length; i++) {
1883             $("#enum_editor #values").append(
1884                 "<input type='text' value='" + values[i] + "' />"
1885             );
1886         }
1887         // So we know which column's data is being edited
1888         $("#enum_editor").append("<input type='hidden' value='" + $(this).parent().prev("input").attr("id") + "' />");
1889         return false;
1890     });
1892     // If the "close" link is clicked, close the enum editor
1893     // Needs live() to work also in the Create table dialog
1894     $("a[class='close_enum_editor']").live('click', function() {
1895         disable_popup();
1896     });
1898     // If the "cancel" link is clicked, close the enum editor
1899     // Needs live() to work also in the Create table dialog
1900     $("a[class='cancel_enum_editor']").live('click', function() {
1901         disable_popup();
1902     });
1904     // When "add a new value" is clicked, append an empty text field
1905     // Needs live() to work also in the Create table dialog
1906     $("a[class='add_value']").live('click', function() {
1907         $("#enum_editor #values").append("<input type='text' />");
1908     });
1910     // When the submit button is clicked, put the data back into the original form
1911     // Needs live() to work also in the Create table dialog
1912     $("#enum_editor input[type='submit']").live('click', function() {
1913         var value_array = new Array();
1914         $.each($("#enum_editor #values input"), function(index, input_element) {
1915             val = jQuery.trim(input_element.value);
1916             if(val != "") {
1917                 value_array.push("'" + val.replace(/\\/g, '\\\\').replace(/'/g, "''") + "'");
1918             }
1919         });
1920         // get the Length/Values text field where this value belongs
1921         var values_id = $("#enum_editor input[type='hidden']").attr("value");
1922         $("input[id='" + values_id + "']").attr("value", value_array.join(","));
1923         disable_popup();
1924      });
1926     /**
1927      * Hides certain table structure actions, replacing them with the word "More". They are displayed
1928      * in a dropdown menu when the user hovers over the word "More."
1929      */
1930     // Remove the actions from the table cells (they are available by default for JavaScript-disabled browsers)
1931     // if the table is not a view or information_schema (otherwise there is only one action to hide and there's no point)
1932     if($("input[type='hidden'][name='table_type']").val() == "table") {
1933         var $table = $("table[id='tablestructure']");
1934         $table.find("td[class='browse']").remove();
1935         $table.find("td[class='primary']").remove();
1936         $table.find("td[class='unique']").remove();
1937         $table.find("td[class='index']").remove();
1938         $table.find("td[class='fulltext']").remove();
1939         $table.find("th[class='action']").attr("colspan", 3);
1941         // Display the "more" text
1942         $table.find("td[class='more_opts']").show();
1944         // Position the dropdown
1945         $(".structure_actions_dropdown").each(function() {
1946             // Optimize DOM querying
1947             var $this_dropdown = $(this);
1948              // The top offset must be set for IE even if it didn't change
1949             var cell_right_edge_offset = $this_dropdown.parent().offset().left + $this_dropdown.parent().innerWidth();
1950             var left_offset = cell_right_edge_offset - $this_dropdown.innerWidth();
1951             var top_offset = $this_dropdown.parent().offset().top + $this_dropdown.parent().innerHeight();
1952             $this_dropdown.offset({ top: top_offset, left: left_offset });
1953         });
1955         // A hack for IE6 to prevent the after_field select element from being displayed on top of the dropdown by
1956         // positioning an iframe directly on top of it
1957         var $after_field = $("select[name='after_field']");
1958         $("iframe[class='IE_hack']")
1959             .width($after_field.width())
1960             .height($after_field.height())
1961             .offset({
1962                 top: $after_field.offset().top,
1963                 left: $after_field.offset().left
1964             });
1966         // When "more" is hovered over, show the hidden actions
1967         $table.find("td[class='more_opts']")
1968             .mouseenter(function() {
1969                 if($.browser.msie && $.browser.version == "6.0") {
1970                     $("iframe[class='IE_hack']")
1971                         .show()
1972                         .width($after_field.width()+4)
1973                         .height($after_field.height()+4)
1974                         .offset({
1975                             top: $after_field.offset().top,
1976                             left: $after_field.offset().left
1977                         });
1978                 }
1979                 $(".structure_actions_dropdown").hide(); // Hide all the other ones that may be open
1980                 $(this).children(".structure_actions_dropdown").show();
1981                 // Need to do this again for IE otherwise the offset is wrong
1982                 if($.browser.msie) {
1983                     var left_offset_IE = $(this).offset().left + $(this).innerWidth() - $(this).children(".structure_actions_dropdown").innerWidth();
1984                     var top_offset_IE = $(this).offset().top + $(this).innerHeight();
1985                     $(this).children(".structure_actions_dropdown").offset({
1986                         top: top_offset_IE,
1987                         left: left_offset_IE });
1988                 }
1989             })
1990             .mouseleave(function() {
1991                 $(this).children(".structure_actions_dropdown").hide();
1992                 if($.browser.msie && $.browser.version == "6.0") {
1993                     $("iframe[class='IE_hack']").hide();
1994                 }
1995             });
1996     }
1999 /* Displays tooltips */
2000 $(document).ready(function() {
2001     // Hide the footnotes from the footer (which are displayed for
2002     // JavaScript-disabled browsers) since the tooltip is sufficient
2003     $(".footnotes").hide();
2004     $(".footnotes span").each(function() {
2005         $(this).children("sup").remove();
2006     });
2007     // The border and padding must be removed otherwise a thin yellow box remains visible
2008     $(".footnotes").css("border", "none");
2009     $(".footnotes").css("padding", "0px");
2011     // Replace the superscripts with the help icon
2012     $("sup[class='footnotemarker']").hide();
2013     $("img[class='footnotemarker']").show();
2015     $("img[class='footnotemarker']").each(function() {
2016         var span_id = $(this).attr("id");
2017         span_id = span_id.split("_")[1];
2018         var tooltip_text = $(".footnotes span[id='footnote_" + span_id + "']").html();
2019         $(this).qtip({
2020             content: tooltip_text,
2021             show: { delay: 0 },
2022             hide: { delay: 1000 },
2023             style: { background: '#ffffcc' }
2024         });
2025     });
2028 function menuResize()
2030     var cnt = $('#topmenu');
2031     var wmax = cnt.innerWidth() - 5; // 5 px margin for jumping menu in Chrome
2032     var submenu = cnt.find('.submenu');
2033     var submenu_w = submenu.outerWidth(true);
2034     var submenu_ul = submenu.find('ul');
2035     var li = cnt.find('> li');
2036     var li2 = submenu_ul.find('li');
2037     var more_shown = li2.length > 0;
2038     var w = more_shown ? submenu_w : 0;
2040     // hide menu items
2041     var hide_start = 0;
2042     for (var i = 0; i < li.length-1; i++) { // li.length-1: skip .submenu element
2043         var el = $(li[i]);
2044         var el_width = el.outerWidth(true);
2045         el.data('width', el_width);
2046         w += el_width;
2047         if (w > wmax) {
2048             w -= el_width;
2049             if (w + submenu_w < wmax) {
2050                 hide_start = i;
2051             } else {
2052                 hide_start = i-1;
2053                 w -= $(li[i-1]).data('width');
2054             }
2055             break;
2056         }
2057     }
2059     if (hide_start > 0) {
2060         for (var i = hide_start; i < li.length-1; i++) {
2061             $(li[i])[more_shown ? 'prependTo' : 'appendTo'](submenu_ul);
2062         }
2063         submenu.addClass('shown');
2064     } else if (more_shown) {
2065         w -= submenu_w;
2066         // nothing hidden, maybe something can be restored
2067         for (var i = 0; i < li2.length; i++) {
2068             //console.log(li2[i], submenu_w);
2069             w += $(li2[i]).data('width');
2070             // item fits or (it is the last item and it would fit if More got removed)
2071             if (w+submenu_w < wmax || (i == li2.length-1 && w < wmax)) {
2072                 $(li2[i]).insertBefore(submenu);
2073                 if (i == li2.length-1) {
2074                     submenu.removeClass('shown');
2075                 }
2076                 continue;
2077             }
2078             break;
2079         }
2080     }
2081     if (submenu.find('.tabactive').length) {
2082         submenu.addClass('active').find('> a').removeClass('tab').addClass('tabactive');
2083     } else {
2084         submenu.removeClass('active').find('> a').addClass('tab').removeClass('tabactive');
2085     }
2088 $(function() {
2089     var topmenu = $('#topmenu');
2090     if (topmenu.length == 0) {
2091         return;
2092     }
2093     // create submenu container
2094     var link = $('<a />', {href: '#', 'class': 'tab'})
2095         .text(PMA_messages['strMore'])
2096         .click(function(e) {
2097             e.preventDefault();
2098         });
2099     var img = topmenu.find('li:first-child img');
2100     if (img.length) {
2101         img.clone().attr('src', img.attr('src').replace(/\/[^\/]+$/, '/b_more.png')).prependTo(link);
2102     }
2103     var submenu = $('<li />', {'class': 'submenu'})
2104         .append(link)
2105         .append($('<ul />'))
2106         .mouseenter(function() {
2107             if ($(this).find('ul .tabactive').length == 0) {
2108                 $(this).addClass('submenuhover').find('> a').addClass('tabactive');
2109             }
2110         })
2111         .mouseleave(function() {
2112             if ($(this).find('ul .tabactive').length == 0) {
2113                 $(this).removeClass('submenuhover').find('> a').removeClass('tabactive');
2114             }
2115         });
2116     topmenu.append(submenu);
2118     // populate submenu and register resize event
2119     $(window).resize(menuResize);
2120     menuResize();
2124  * For the checkboxes in browse mode, handles the shift/click (only works
2125  * in horizontal mode) and propagates the click to the "companion" checkbox
2126  * (in both horizontal and vertical). Works also for pages reached via AJAX.
2127  */
2128 $(document).ready(function() {
2129     $('.multi_checkbox').live('click',function(e) {
2130         var current_checkbox_id = this.id;
2131         var left_checkbox_id = current_checkbox_id.replace('_right', '_left');
2132         var right_checkbox_id = current_checkbox_id.replace('_left', '_right');
2133         var other_checkbox_id = '';
2134         if (current_checkbox_id == left_checkbox_id) {
2135             other_checkbox_id = right_checkbox_id;
2136         } else {
2137             other_checkbox_id = left_checkbox_id;
2138         }
2140         var $current_checkbox = $('#' + current_checkbox_id);
2141         var $other_checkbox = $('#' + other_checkbox_id);
2143         if (e.shiftKey) {
2144             var index_of_current_checkbox = $('.multi_checkbox').index($current_checkbox);
2145             var $last_checkbox = $('.multi_checkbox').filter('.last_clicked');
2146             var index_of_last_click = $('.multi_checkbox').index($last_checkbox);
2147             $('.multi_checkbox')
2148                 .filter(function(index) {
2149                     // the first clicked row can be on a row above or below the
2150                     // shift-clicked row
2151                     return (index_of_current_checkbox > index_of_last_click && index > index_of_last_click && index < index_of_current_checkbox)
2152                      || (index_of_last_click > index_of_current_checkbox && index < index_of_last_click && index > index_of_current_checkbox);
2153                 })
2154                 .each(function(index) {
2155                     var $intermediate_checkbox = $(this);
2156                     if ($current_checkbox.is(':checked')) {
2157                         $intermediate_checkbox.attr('checked', true);
2158                     } else {
2159                         $intermediate_checkbox.attr('checked', false);
2160                     }
2161                 });
2162         }
2164         $('.multi_checkbox').removeClass('last_clicked');
2165         $current_checkbox.addClass('last_clicked');
2167         // When there is a checkbox on both ends of the row, propagate the
2168         // click on one of them to the other one.
2169         // (the default action has not been prevented so if we have
2170         // just clicked, this "if" is true)
2171         if ($current_checkbox.is(':checked')) {
2172             $other_checkbox.attr('checked', true);
2173         } else {
2174             $other_checkbox.attr('checked', false);
2175         }
2176     });
2177 }) // end of $(document).ready() for multi checkbox
2180  * Get the row number from the classlist (for example, row_1)
2181  */
2182 function PMA_getRowNumber(classlist) {
2183     return parseInt(classlist.split(/row_/)[1]);
2187  * Changes status of slider
2188  */
2189 function PMA_set_status_label(id) {
2190     if ($('#' + id).css('display') == 'none') {
2191         $('#anchor_status_' + id).text('+ ');
2192     } else {
2193         $('#anchor_status_' + id).text('- ');
2194     }
2198  * Initializes slider effect.
2199  */
2200 function PMA_init_slider() {
2201     $('.pma_auto_slider').each(function(idx, e) {
2202         if ($(e).hasClass('slider_init_done')) return;
2203         $(e).addClass('slider_init_done');
2204         $('<span id="anchor_status_' + e.id + '"></span>')
2205             .insertBefore(e);
2206         PMA_set_status_label(e.id);
2208         $('<a href="#' + e.id + '" id="anchor_' + e.id + '">' + e.title + '</a>')
2209             .insertBefore(e)
2210             .click(function() {
2211                 $('#' + e.id).toggle('clip', function() {
2212                     PMA_set_status_label(e.id);
2213                 });
2214                 return false;
2215             });
2216     });
2220  * Vertical pointer
2221  */
2222 $(document).ready(function() {
2223     $('.vpointer').live('hover',
2224         //handlerInOut
2225         function(e) {
2226         var $this_td = $(this);
2227         var row_num = PMA_getRowNumber($this_td.attr('class'));
2228         // for all td of the same vertical row, toggle hover
2229         $('.vpointer').filter('.row_' + row_num).toggleClass('hover');
2230         }
2231         );
2232 }) // end of $(document).ready() for vertical pointer
2234 $(document).ready(function() {
2235     /**
2236      * Vertical marker
2237      */
2238     $('.vmarker').live('click', function(e) {
2239         var $this_td = $(this);
2240         var row_num = PMA_getRowNumber($this_td.attr('class'));
2241         // for all td of the same vertical row, toggle the marked class
2242         $('.vmarker').filter('.row_' + row_num).toggleClass('marked');
2243         });
2245     /**
2246      * Reveal visual builder anchor
2247      */
2249     $('#visual_builder_anchor').show();
2251     /**
2252      * Page selector in db Structure (non-AJAX)
2253      */
2254     $('#tableslistcontainer').find('#pageselector').live('change', function() {
2255         $(this).parent("form").submit();
2256     });
2258     /**
2259      * Page selector in navi panel (non-AJAX)
2260      */
2261     $('#navidbpageselector').find('#pageselector').live('change', function() {
2262         $(this).parent("form").submit();
2263     });
2265     /**
2266      * Page selector in browse_foreigners windows (non-AJAX)
2267      */
2268     $('#body_browse_foreigners').find('#pageselector').live('change', function() {
2269         $(this).closest("form").submit();
2270     });
2272     /**
2273      * Load version information asynchronously.
2274      */
2275     if ($('.jsversioncheck').length > 0) {
2276         (function() {
2277             var s = document.createElement('script');
2278             s.type = 'text/javascript';
2279             s.async = true;
2280             s.src = 'http://www.phpmyadmin.net/home_page/version.js';
2281             s.onload = PMA_current_version;
2282             var x = document.getElementsByTagName('script')[0];
2283             x.parentNode.insertBefore(s, x);
2284         })();
2285     }
2287     /**
2288      * Slider effect.
2289      */
2290     PMA_init_slider();
2292     /**
2293      * Enables the text generated by PMA_linkOrButton() to be clickable
2294      */
2295     $('.clickprevimage')
2296         .css('color', function(index) {
2297             return $('a').css('color');
2298         })
2299         .css('cursor', function(index) {
2300             return $('a').css('cursor');
2301         }) //todo: hover effect
2302         .live('click',function(e) {
2303             $this_span = $(this);
2304             if ($this_span.closest('td').is('.inline_edit_anchor')) {
2305             // this would bind a second click event to the inline edit
2306             // anchor and would disturb its behavior
2307             } else {
2308                 $this_span.parent().find('input:image').click();
2309             }
2310         });
2312 }) // end of $(document).ready()
2315  * HTML escaping
2316  */
2317 function escapeHtml(unsafe) {
2318     return unsafe
2319         .replace(/&/g, "&amp;")
2320         .replace(/</g, "&lt;")
2321         .replace(/>/g, "&gt;")
2322         .replace(/"/g, "&quot;")
2323         .replace(/'/g, "&#039;");