Unneeded wrapping of jQuery object
[phpmyadmin/mlewandow.git] / js / functions.js
blob74a4fb8d0eaf861b7f3a405020f9c6c5da3cdb93
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  * Generate a new password and copy it to the password input areas
25  *
26  * @param   object   the form that holds the password fields
27  *
28  * @return  boolean  always true
29  */
30 function suggestPassword(passwd_form) {
31     // restrict the password to just letters and numbers to avoid problems:
32     // "editors and viewers regard the password as multiple words and
33     // things like double click no longer work"
34     var pwchars = "abcdefhjmnpqrstuvwxyz23456789ABCDEFGHJKLMNPQRSTUVWYXZ";
35     var passwordlength = 16;    // do we want that to be dynamic?  no, keep it simple :)
36     var passwd = passwd_form.generated_pw;
37     passwd.value = '';
39     for ( i = 0; i < passwordlength; i++ ) {
40         passwd.value += pwchars.charAt( Math.floor( Math.random() * pwchars.length ) )
41     }
42     passwd_form.text_pma_pw.value = passwd.value;
43     passwd_form.text_pma_pw2.value = passwd.value;
44     return true;
47 /**
48  * for libraries/display_change_password.lib.php 
49  *     libraries/user_password.php
50  *
51  */
53 function displayPasswordGenerateButton() {
54     $('#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>');
55     $('#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>');
59  * Adds a date/time picker to an element
60  *
61  * @param   object  $this_element   a jQuery object pointing to the element 
62  */
63 function PMA_addDatepicker($this_element) {
64     var showTimeOption = false;
65     if ($this_element.is('.datetimefield')) {
66         showTimeOption = true;
67     }
69     $this_element
70         .datepicker({
71         showOn: 'button',
72         buttonImage: themeCalendarImage, // defined in js/messages.php
73         buttonImageOnly: true,
74         duration: '',
75         time24h: true,
76         stepMinutes: 1,
77         stepHours: 1,
78         showTime: showTimeOption, 
79         dateFormat: 'yy-mm-dd', // yy means year with four digits
80         altTimeField: '',
81         beforeShow: function(input, inst) {
82             // Remember that we came from the datepicker; this is used
83             // in tbl_change.js by verificationsAfterFieldChange()
84             $this_element.data('comes_from', 'datepicker');
85         },
86         constrainInput: false
87      });
90 /**
91  * selects the content of a given object, f.e. a textarea
92  *
93  * @param   object  element     element of which the content will be selected
94  * @param   var     lock        variable which holds the lock for this element
95  *                              or true, if no lock exists
96  * @param   boolean only_once   if true this is only done once
97  *                              f.e. only on first focus
98  */
99 function selectContent( element, lock, only_once ) {
100     if ( only_once && only_once_elements[element.name] ) {
101         return;
102     }
104     only_once_elements[element.name] = true;
106     if ( lock  ) {
107         return;
108     }
110     element.select();
114  * Displays a confirmation box before submitting a "DROP DATABASE" query.
115  * This function is called while clicking links
117  * @param   object   the link
118  * @param   object   the sql query to submit
120  * @return  boolean  whether to run the query or not
121  */
122 function confirmLinkDropDB(theLink, theSqlQuery)
124     // Confirmation is not required in the configuration file
125     // or browser is Opera (crappy js implementation)
126     if (PMA_messages['strDoYouReally'] == '' || typeof(window.opera) != 'undefined') {
127         return true;
128     }
130     var is_confirmed = confirm(PMA_messages['strDropDatabaseStrongWarning'] + '\n' + PMA_messages['strDoYouReally'] + ' :\n' + theSqlQuery);
131     if (is_confirmed) {
132         theLink.href += '&is_js_confirmed=1';
133     }
135     return is_confirmed;
136 } // end of the 'confirmLinkDropDB()' function
139  * Displays a confirmation box before to submit a "DROP/DELETE/ALTER" query.
140  * This function is called while clicking links
142  * @param   object   the link
143  * @param   object   the sql query to submit
145  * @return  boolean  whether to run the query or not
146  */
147 function confirmLink(theLink, theSqlQuery)
149     // Confirmation is not required in the configuration file
150     // or browser is Opera (crappy js implementation)
151     if (PMA_messages['strDoYouReally'] == '' || typeof(window.opera) != 'undefined') {
152         return true;
153     }
155     var is_confirmed = confirm(PMA_messages['strDoYouReally'] + ' :\n' + theSqlQuery);
156     if (is_confirmed) {
157         if ( typeof(theLink.href) != 'undefined' ) {
158             theLink.href += '&is_js_confirmed=1';
159         } else if ( typeof(theLink.form) != 'undefined' ) {
160             theLink.form.action += '?is_js_confirmed=1';
161         }
162     }
164     return is_confirmed;
165 } // end of the 'confirmLink()' function
169  * Displays a confirmation box before doing some action
171  * @param   object   the message to display
173  * @return  boolean  whether to run the query or not
175  * @todo used only by libraries/display_tbl.lib.php. figure out how it is used
176  *       and replace with a jQuery equivalent
177  */
178 function confirmAction(theMessage)
180     // TODO: Confirmation is not required in the configuration file
181     // or browser is Opera (crappy js implementation)
182     if (typeof(window.opera) != 'undefined') {
183         return true;
184     }
186     var is_confirmed = confirm(theMessage);
188     return is_confirmed;
189 } // end of the 'confirmAction()' function
193  * Displays an error message if a "DROP DATABASE" statement is submitted
194  * while it isn't allowed, else confirms a "DROP/DELETE/ALTER" query before
195  * sumitting it if required.
196  * This function is called by the 'checkSqlQuery()' js function.
198  * @param   object   the form
199  * @param   object   the sql query textarea
201  * @return  boolean  whether to run the query or not
203  * @see     checkSqlQuery()
204  */
205 function confirmQuery(theForm1, sqlQuery1)
207     // Confirmation is not required in the configuration file
208     if (PMA_messages['strDoYouReally'] == '') {
209         return true;
210     }
212     // The replace function (js1.2) isn't supported
213     else if (typeof(sqlQuery1.value.replace) == 'undefined') {
214         return true;
215     }
217     // js1.2+ -> validation with regular expressions
218     else {
219         // "DROP DATABASE" statement isn't allowed
220         if (PMA_messages['strNoDropDatabases'] != '') {
221             var drop_re = new RegExp('(^|;)\\s*DROP\\s+(IF EXISTS\\s+)?DATABASE\\s', 'i');
222             if (drop_re.test(sqlQuery1.value)) {
223                 alert(PMA_messages['strNoDropDatabases']);
224                 theForm1.reset();
225                 sqlQuery1.focus();
226                 return false;
227             } // end if
228         } // end if
230         // Confirms a "DROP/DELETE/ALTER/TRUNCATE" statement
231         //
232         // TODO: find a way (if possible) to use the parser-analyser
233         // for this kind of verification
234         // For now, I just added a ^ to check for the statement at
235         // beginning of expression
237         var do_confirm_re_0 = new RegExp('^\\s*DROP\\s+(IF EXISTS\\s+)?(TABLE|DATABASE|PROCEDURE)\\s', 'i');
238         var do_confirm_re_1 = new RegExp('^\\s*ALTER\\s+TABLE\\s+((`[^`]+`)|([A-Za-z0-9_$]+))\\s+DROP\\s', 'i');
239         var do_confirm_re_2 = new RegExp('^\\s*DELETE\\s+FROM\\s', 'i');
240         var do_confirm_re_3 = new RegExp('^\\s*TRUNCATE\\s', 'i');
242         if (do_confirm_re_0.test(sqlQuery1.value)
243             || do_confirm_re_1.test(sqlQuery1.value)
244             || do_confirm_re_2.test(sqlQuery1.value)
245             || do_confirm_re_3.test(sqlQuery1.value)) {
246             var message      = (sqlQuery1.value.length > 100)
247                              ? sqlQuery1.value.substr(0, 100) + '\n    ...'
248                              : sqlQuery1.value;
249             var is_confirmed = confirm(PMA_messages['strDoYouReally'] + ' :\n' + message);
250             // statement is confirmed -> update the
251             // "is_js_confirmed" form field so the confirm test won't be
252             // run on the server side and allows to submit the form
253             if (is_confirmed) {
254                 theForm1.elements['is_js_confirmed'].value = 1;
255                 return true;
256             }
257             // statement is rejected -> do not submit the form
258             else {
259                 window.focus();
260                 sqlQuery1.focus();
261                 return false;
262             } // end if (handle confirm box result)
263         } // end if (display confirm box)
264     } // end confirmation stuff
266     return true;
267 } // end of the 'confirmQuery()' function
271  * Displays a confirmation box before disabling the BLOB repository for a given database.
272  * This function is called while clicking links
274  * @param   object   the database
276  * @return  boolean  whether to disable the repository or not
277  */
278 function confirmDisableRepository(theDB)
280     // Confirmation is not required in the configuration file
281     // or browser is Opera (crappy js implementation)
282     if (PMA_messages['strDoYouReally'] == '' || typeof(window.opera) != 'undefined') {
283         return true;
284     }
286     var is_confirmed = confirm(PMA_messages['strBLOBRepositoryDisableStrongWarning'] + '\n' + PMA_messages['strBLOBRepositoryDisableAreYouSure']);
288     return is_confirmed;
289 } // end of the 'confirmDisableBLOBRepository()' function
293  * Displays an error message if the user submitted the sql query form with no
294  * sql query, else checks for "DROP/DELETE/ALTER" statements
296  * @param   object   the form
298  * @return  boolean  always false
300  * @see     confirmQuery()
301  */
302 function checkSqlQuery(theForm)
304     var sqlQuery = theForm.elements['sql_query'];
305     var isEmpty  = 1;
307     // The replace function (js1.2) isn't supported -> basic tests
308     if (typeof(sqlQuery.value.replace) == 'undefined') {
309         isEmpty      = (sqlQuery.value == '') ? 1 : 0;
310         if (isEmpty && typeof(theForm.elements['sql_file']) != 'undefined') {
311             isEmpty  = (theForm.elements['sql_file'].value == '') ? 1 : 0;
312         }
313         if (isEmpty && typeof(theForm.elements['sql_localfile']) != 'undefined') {
314             isEmpty  = (theForm.elements['sql_localfile'].value == '') ? 1 : 0;
315         }
316         if (isEmpty && typeof(theForm.elements['id_bookmark']) != 'undefined') {
317             isEmpty  = (theForm.elements['id_bookmark'].value == null || theForm.elements['id_bookmark'].value == '');
318         }
319     }
320     // js1.2+ -> validation with regular expressions
321     else {
322         var space_re = new RegExp('\\s+');
323         if (typeof(theForm.elements['sql_file']) != 'undefined' &&
324                 theForm.elements['sql_file'].value.replace(space_re, '') != '') {
325             return true;
326         }
327         if (typeof(theForm.elements['sql_localfile']) != 'undefined' &&
328                 theForm.elements['sql_localfile'].value.replace(space_re, '') != '') {
329             return true;
330         }
331         if (isEmpty && typeof(theForm.elements['id_bookmark']) != 'undefined' &&
332                 (theForm.elements['id_bookmark'].value != null || theForm.elements['id_bookmark'].value != '') &&
333                 theForm.elements['id_bookmark'].selectedIndex != 0
334                 ) {
335             return true;
336         }
337         // Checks for "DROP/DELETE/ALTER" statements
338         if (sqlQuery.value.replace(space_re, '') != '') {
339             if (confirmQuery(theForm, sqlQuery)) {
340                 return true;
341             } else {
342                 return false;
343             }
344         }
345         theForm.reset();
346         isEmpty = 1;
347     }
349     if (isEmpty) {
350         sqlQuery.select();
351         alert(PMA_messages['strFormEmpty']);
352         sqlQuery.focus();
353         return false;
354     }
356     return true;
357 } // end of the 'checkSqlQuery()' function
359 // Global variable row_class is set to even
360 var row_class = 'even';
363 * Generates a row dynamically in the differences table displaying
364 * the complete statistics of difference in  table like number of
365 * rows to be updated, number of rows to be inserted, number of
366 * columns to be added, number of columns to be removed, etc.
368 * @param  index         index of matching table
369 * @param  update_size   number of rows/column to be updated
370 * @param  insert_size   number of rows/coulmns to be inserted
371 * @param  remove_size   number of columns to be removed
372 * @param  insert_index  number of indexes to be inserted
373 * @param  remove_index  number of indexes to be removed
374 * @param  img_obj       image object
375 * @param  table_name    name of the table
378 function showDetails(i, update_size, insert_size, remove_size, insert_index, remove_index, img_obj, table_name)
380     // The path of the image is split to facilitate comparison
381     var relative_path = (img_obj.src).split("themes/");
383     // The image source is changed when the showDetails function is called.
384     if (relative_path[1] == 'original/img/new_data_hovered.jpg') {
385         img_obj.src = "./themes/original/img/new_data_selected_hovered.jpg";
386         img_obj.alt = PMA_messages['strClickToUnselect'];  //only for IE browser
387     } else if (relative_path[1] == 'original/img/new_struct_hovered.jpg') {
388         img_obj.src = "./themes/original/img/new_struct_selected_hovered.jpg";
389         img_obj.alt = PMA_messages['strClickToUnselect'];
390     } else if (relative_path[1] == 'original/img/new_struct_selected_hovered.jpg') {
391         img_obj.src = "./themes/original/img/new_struct_hovered.jpg";
392         img_obj.alt = PMA_messages['strClickToSelect'];
393     } else if (relative_path[1] == 'original/img/new_data_selected_hovered.jpg') {
394         img_obj.src = "./themes/original/img/new_data_hovered.jpg";
395         img_obj.alt = PMA_messages['strClickToSelect'];
396     }
398     var div = document.getElementById("list");
399     var table = div.getElementsByTagName("table")[0];
400     var table_body = table.getElementsByTagName("tbody")[0];
402     //Global variable row_class is being used
403     if (row_class == 'even') {
404         row_class = 'odd';
405     } else {
406         row_class = 'even';
407     }
408     // If the red or green button against a table name is pressed then append a new row to show the details of differences of this table.
409     if ((relative_path[1] != 'original/img/new_struct_selected_hovered.jpg') && (relative_path[1] != 'original/img/new_data_selected_hovered.jpg')) {
411         var newRow = document.createElement("tr");
412         newRow.setAttribute("class", row_class);
413         newRow.className = row_class;
414         // Id assigned to this row element is same as the index of this table name in the  matching_tables/source_tables_uncommon array
415         newRow.setAttribute("id" , i);
417         var table_name_cell = document.createElement("td");
418         table_name_cell.align = "center";
419         table_name_cell.innerHTML = table_name ;
421         newRow.appendChild(table_name_cell);
423         var create_table = document.createElement("td");
424         create_table.align = "center";
426         var add_cols = document.createElement("td");
427         add_cols.align = "center";
429         var remove_cols = document.createElement("td");
430         remove_cols.align = "center";
432         var alter_cols = document.createElement("td");
433         alter_cols.align = "center";
435         var add_index = document.createElement("td");
436         add_index.align = "center";
438         var delete_index = document.createElement("td");
439         delete_index.align = "center";
441         var update_rows = document.createElement("td");
442         update_rows.align = "center";
444         var insert_rows = document.createElement("td");
445         insert_rows.align = "center";
447         var tick_image = document.createElement("img");
448         tick_image.src = "./themes/original/img/s_success.png";
450         if (update_size == '' && insert_size == '' && remove_size == '') {
451           /**
452           This is the case when the table needs to be created in target database.
453           */
454             create_table.appendChild(tick_image);
455             add_cols.innerHTML = "--";
456             remove_cols.innerHTML = "--";
457             alter_cols.innerHTML = "--";
458             delete_index.innerHTML = "--";
459             add_index.innerHTML = "--";
460             update_rows.innerHTML = "--";
461             insert_rows.innerHTML = "--";
463             newRow.appendChild(create_table);
464             newRow.appendChild(add_cols);
465             newRow.appendChild(remove_cols);
466             newRow.appendChild(alter_cols);
467             newRow.appendChild(delete_index);
468             newRow.appendChild(add_index);
469             newRow.appendChild(update_rows);
470             newRow.appendChild(insert_rows);
472         } else if (update_size == '' && remove_size == '') {
473            /**
474            This is the case when data difference is displayed in the
475            table which is present in source but absent from target database
476           */
477             create_table.innerHTML = "--";
478             add_cols.innerHTML = "--";
479             remove_cols.innerHTML = "--";
480             alter_cols.innerHTML = "--";
481             add_index.innerHTML = "--";
482             delete_index.innerHTML = "--";
483             update_rows.innerHTML = "--";
484             insert_rows.innerHTML = insert_size;
486             newRow.appendChild(create_table);
487             newRow.appendChild(add_cols);
488             newRow.appendChild(remove_cols);
489             newRow.appendChild(alter_cols);
490             newRow.appendChild(delete_index);
491             newRow.appendChild(add_index);
492             newRow.appendChild(update_rows);
493             newRow.appendChild(insert_rows);
495         } else if (remove_size == '') {
496             /**
497              This is the case when data difference between matching_tables is displayed.
498             */
499             create_table.innerHTML = "--";
500             add_cols.innerHTML = "--";
501             remove_cols.innerHTML = "--";
502             alter_cols.innerHTML = "--";
503             add_index.innerHTML = "--";
504             delete_index.innerHTML = "--";
505             update_rows.innerHTML = update_size;
506             insert_rows.innerHTML = insert_size;
508             newRow.appendChild(create_table);
509             newRow.appendChild(add_cols);
510             newRow.appendChild(remove_cols);
511             newRow.appendChild(alter_cols);
512             newRow.appendChild(delete_index);
513             newRow.appendChild(add_index);
514             newRow.appendChild(update_rows);
515             newRow.appendChild(insert_rows);
517         } else {
518             /**
519             This is the case when structure difference between matching_tables id displayed
520             */
521             create_table.innerHTML = "--";
522             add_cols.innerHTML = insert_size;
523             remove_cols.innerHTML = remove_size;
524             alter_cols.innerHTML = update_size;
525             delete_index.innerHTML = remove_index;
526             add_index.innerHTML = insert_index;
527             update_rows.innerHTML = "--";
528             insert_rows.innerHTML = "--";
530             newRow.appendChild(create_table);
531             newRow.appendChild(add_cols);
532             newRow.appendChild(remove_cols);
533             newRow.appendChild(alter_cols);
534             newRow.appendChild(delete_index);
535             newRow.appendChild(add_index);
536             newRow.appendChild(update_rows);
537             newRow.appendChild(insert_rows);
538         }
539         table_body.appendChild(newRow);
541     } else if ((relative_path[1] != 'original/img/new_struct_hovered.jpg') && (relative_path[1] != 'original/img/new_data_hovered.jpg')) {
542       //The case when the row showing the details need to be removed from the table i.e. the difference button is deselected now.
543         var table_rows = table_body.getElementsByTagName("tr");
544         var j;
545         var index = 0;
546         for (j=0; j < table_rows.length; j++)
547         {
548             if (table_rows[j].id == i) {
549                 index = j;
550                 table_rows[j].parentNode.removeChild(table_rows[j]);
551             }
552         }
553         //The table row css is being adjusted. Class "odd" for odd rows and "even" for even rows should be maintained.
554         for(index = 0; index < table_rows.length; index++)
555         {
556             row_class_element = table_rows[index].getAttribute('class');
557             if (row_class_element == "even") {
558                 table_rows[index].setAttribute("class","odd");  // for Mozilla firefox
559                 table_rows[index].className = "odd";            // for IE browser
560             } else {
561                 table_rows[index].setAttribute("class","even"); // for Mozilla firefox
562                 table_rows[index].className = "even";           // for IE browser
563             }
564         }
565     }
569  * Changes the image on hover effects
571  * @param   img_obj   the image object whose source needs to be changed
573  */
574 function change_Image(img_obj)
576      var relative_path = (img_obj.src).split("themes/");
578     if (relative_path[1] == 'original/img/new_data.jpg') {
579         img_obj.src = "./themes/original/img/new_data_hovered.jpg";
580     } else if (relative_path[1] == 'original/img/new_struct.jpg') {
581         img_obj.src = "./themes/original/img/new_struct_hovered.jpg";
582     } else if (relative_path[1] == 'original/img/new_struct_hovered.jpg') {
583         img_obj.src = "./themes/original/img/new_struct.jpg";
584     } else if (relative_path[1] == 'original/img/new_data_hovered.jpg') {
585         img_obj.src = "./themes/original/img/new_data.jpg";
586     } else if (relative_path[1] == 'original/img/new_data_selected.jpg') {
587         img_obj.src = "./themes/original/img/new_data_selected_hovered.jpg";
588     } else if(relative_path[1] == 'original/img/new_struct_selected.jpg') {
589         img_obj.src = "./themes/original/img/new_struct_selected_hovered.jpg";
590     } else if (relative_path[1] == 'original/img/new_struct_selected_hovered.jpg') {
591         img_obj.src = "./themes/original/img/new_struct_selected.jpg";
592     } else if (relative_path[1] == 'original/img/new_data_selected_hovered.jpg') {
593         img_obj.src = "./themes/original/img/new_data_selected.jpg";
594     }
598  * Generates the URL containing the list of selected table ids for synchronization and
599  * a variable checked for confirmation of deleting previous rows from target tables
601  * @param   token   the token generated for each PMA form
603  */
604 function ApplySelectedChanges(token)
606     var div =  document.getElementById("list");
607     var table = div.getElementsByTagName('table')[0];
608     var table_body = table.getElementsByTagName('tbody')[0];
609     // Get all the rows from the details table
610     var table_rows = table_body.getElementsByTagName('tr');
611     var x = table_rows.length;
612     var i;
613     /**
614      Append the token at the beginning of the query string followed by
615     Table_ids that shows that "Apply Selected Changes" button is pressed
616     */
617     var append_string = "?token="+token+"&Table_ids="+1;
618     for(i=0; i<x; i++){
619            append_string += "&";
620            append_string += i+"="+table_rows[i].id;
621     }
623     // Getting the value of checkbox delete_rows
624     var checkbox = document.getElementById("delete_rows");
625     if (checkbox.checked){
626         append_string += "&checked=true";
627     } else {
628          append_string += "&checked=false";
629     }
630     //Appending the token and list of table ids in the URL
631     location.href += token;
632     location.href += append_string;
636 * Displays an error message if any text field
637 * is left empty other than the port field.
639 * @param  string   the form name
640 * @param  object   the form
642 * @return  boolean  whether the form field is empty or not
644 function validateConnection(form_name, form_obj)
646     var check = true;
647     var src_hostfilled = true;
648     var trg_hostfilled = true;
650     for (var i=1; i<form_name.elements.length; i++)
651     {
652         // All the text fields are checked excluding the port field because the default port can be used.
653         if ((form_name.elements[i].type == 'text') && (form_name.elements[i].name != 'src_port') && (form_name.elements[i].name != 'trg_port')) {
654             check = emptyFormElements(form_obj, form_name.elements[i].name);
655             if (check==false) {
656                 element = form_name.elements[i].name;
657                 if (form_name.elements[i].name == 'src_host') {
658                     src_hostfilled = false;
659                     continue;
660                 }
661                 if (form_name.elements[i].name == 'trg_host') {
662                     trg_hostfilled = false;
663                     continue;
664                 }
665                 if ((form_name.elements[i].name == 'src_socket' && src_hostfilled==false) || (form_name.elements[i].name == 'trg_socket' && trg_hostfilled==false))
666                     break;
667                 else
668                     continue;
669             }
670         }
671     }
672     if (!check) {
673         form_obj.reset();
674         element.select();
675         alert(PMA_messages['strFormEmpty']);
676         element.focus();
677     }
678     return check;
682  * Check if a form's element is empty.
683  * An element containing only spaces is also considered empty
685  * @param   object   the form
686  * @param   string   the name of the form field to put the focus on
688  * @return  boolean  whether the form field is empty or not
689  */
690 function emptyCheckTheField(theForm, theFieldName)
692     var isEmpty  = 1;
693     var theField = theForm.elements[theFieldName];
694     // Whether the replace function (js1.2) is supported or not
695     var isRegExp = (typeof(theField.value.replace) != 'undefined');
697     if (!isRegExp) {
698         isEmpty      = (theField.value == '') ? 1 : 0;
699     } else {
700         var space_re = new RegExp('\\s+');
701         isEmpty      = (theField.value.replace(space_re, '') == '') ? 1 : 0;
702     }
704     return isEmpty;
705 } // end of the 'emptyCheckTheField()' function
709  * Check whether a form field is empty or not
711  * @param   object   the form
712  * @param   string   the name of the form field to put the focus on
714  * @return  boolean  whether the form field is empty or not
715  */
716 function emptyFormElements(theForm, theFieldName)
718     var theField = theForm.elements[theFieldName];
719     var isEmpty = emptyCheckTheField(theForm, theFieldName);
722     return isEmpty;
723 } // end of the 'emptyFormElements()' function
727  * Ensures a value submitted in a form is numeric and is in a range
729  * @param   object   the form
730  * @param   string   the name of the form field to check
731  * @param   integer  the minimum authorized value
732  * @param   integer  the maximum authorized value
734  * @return  boolean  whether a valid number has been submitted or not
735  */
736 function checkFormElementInRange(theForm, theFieldName, message, min, max)
738     var theField         = theForm.elements[theFieldName];
739     var val              = parseInt(theField.value);
741     if (typeof(min) == 'undefined') {
742         min = 0;
743     }
744     if (typeof(max) == 'undefined') {
745         max = Number.MAX_VALUE;
746     }
748     // It's not a number
749     if (isNaN(val)) {
750         theField.select();
751         alert(PMA_messages['strNotNumber']);
752         theField.focus();
753         return false;
754     }
755     // It's a number but it is not between min and max
756     else if (val < min || val > max) {
757         theField.select();
758         alert(message.replace('%d', val));
759         theField.focus();
760         return false;
761     }
762     // It's a valid number
763     else {
764         theField.value = val;
765     }
766     return true;
768 } // end of the 'checkFormElementInRange()' function
771 function checkTableEditForm(theForm, fieldsCnt)
773     // TODO: avoid sending a message if user just wants to add a line
774     // on the form but has not completed at least one field name
776     var atLeastOneField = 0;
777     var i, elm, elm2, elm3, val, id;
779     for (i=0; i<fieldsCnt; i++)
780     {
781         id = "#field_" + i + "_2";
782         elm = $(id);
783         val = elm.val()
784         if (val == 'VARCHAR' || val == 'CHAR' || val == 'BIT' || val == 'VARBINARY' || val == 'BINARY') {
785             elm2 = $("#field_" + i + "_3");
786             val = parseInt(elm2.val());
787             elm3 = $("#field_" + i + "_1");
788             if (isNaN(val) && elm3.val() != "") {
789                 elm2.select();
790                 alert(PMA_messages['strNotNumber']);
791                 elm2.focus();
792                 return false;
793             }
794         }
796         if (atLeastOneField == 0) {
797             id = "field_" + i + "_1";
798             if (!emptyCheckTheField(theForm, id)) {
799                 atLeastOneField = 1;
800             }
801         }
802     }
803     if (atLeastOneField == 0) {
804         var theField = theForm.elements["field_0_1"];
805         alert(PMA_messages['strFormEmpty']);
806         theField.focus();
807         return false;
808     }
810     return true;
811 } // enf of the 'checkTableEditForm()' function
815  * Ensures the choice between 'transmit', 'zipped', 'gzipped' and 'bzipped'
816  * checkboxes is consistant
818  * @param   object   the form
819  * @param   string   a code for the action that causes this function to be run
821  * @return  boolean  always true
822  */
823 function checkTransmitDump(theForm, theAction)
825     var formElts = theForm.elements;
827     // 'zipped' option has been checked
828     if (theAction == 'zip' && formElts['zip'].checked) {
829         if (!formElts['asfile'].checked) {
830             theForm.elements['asfile'].checked = true;
831         }
832         if (typeof(formElts['gzip']) != 'undefined' && formElts['gzip'].checked) {
833             theForm.elements['gzip'].checked = false;
834         }
835         if (typeof(formElts['bzip']) != 'undefined' && formElts['bzip'].checked) {
836             theForm.elements['bzip'].checked = false;
837         }
838     }
839     // 'gzipped' option has been checked
840     else if (theAction == 'gzip' && formElts['gzip'].checked) {
841         if (!formElts['asfile'].checked) {
842             theForm.elements['asfile'].checked = true;
843         }
844         if (typeof(formElts['zip']) != 'undefined' && formElts['zip'].checked) {
845             theForm.elements['zip'].checked = false;
846         }
847         if (typeof(formElts['bzip']) != 'undefined' && formElts['bzip'].checked) {
848             theForm.elements['bzip'].checked = false;
849         }
850     }
851     // 'bzipped' option has been checked
852     else if (theAction == 'bzip' && formElts['bzip'].checked) {
853         if (!formElts['asfile'].checked) {
854             theForm.elements['asfile'].checked = true;
855         }
856         if (typeof(formElts['zip']) != 'undefined' && formElts['zip'].checked) {
857             theForm.elements['zip'].checked = false;
858         }
859         if (typeof(formElts['gzip']) != 'undefined' && formElts['gzip'].checked) {
860             theForm.elements['gzip'].checked = false;
861         }
862     }
863     // 'transmit' option has been unchecked
864     else if (theAction == 'transmit' && !formElts['asfile'].checked) {
865         if (typeof(formElts['zip']) != 'undefined' && formElts['zip'].checked) {
866             theForm.elements['zip'].checked = false;
867         }
868         if ((typeof(formElts['gzip']) != 'undefined' && formElts['gzip'].checked)) {
869             theForm.elements['gzip'].checked = false;
870         }
871         if ((typeof(formElts['bzip']) != 'undefined' && formElts['bzip'].checked)) {
872             theForm.elements['bzip'].checked = false;
873         }
874     }
876     return true;
877 } // end of the 'checkTransmitDump()' function
879 $(document).ready(function() {
880     /**
881      * Row marking in horizontal mode (use "live" so that it works also for 
882      * next pages reached via AJAX); a tr may have the class noclick to remove
883      * this behavior.
884      */
885     $('tr.odd:not(.noclick), tr.even:not(.noclick)').live('click',function() {
886         var $tr = $(this);
887         $tr.toggleClass('marked');
888         $tr.children().toggleClass('marked');
889     });
891     /**
892      * Add a date/time picker to each element that needs it 
893      */
894     $('.datefield, .datetimefield').each(function() {
895         PMA_addDatepicker($(this));
896         });
900  * Row highlighting in horizontal mode (use "live"
901  * so that it works also for pages reached via AJAX)
902  */
903 $(document).ready(function() {
904     $('tr.odd, tr.even').live('hover',function() {
905         var $tr = $(this);
906         $tr.toggleClass('hover');
907         $tr.children().toggleClass('hover');
908     });
912  * This array is used to remember mark status of rows in browse mode
913  */
914 var marked_row = new Array;
917  * marks all rows and selects its first checkbox inside the given element
918  * the given element is usaly a table or a div containing the table or tables
920  * @param    container    DOM element
921  */
922 function markAllRows( container_id ) {
924     $("#"+container_id).find("input:checkbox:enabled").attr('checked', 'checked')
925     .parents("tr").addClass("marked");
926     return true;
930  * marks all rows and selects its first checkbox inside the given element
931  * the given element is usaly a table or a div containing the table or tables
933  * @param    container    DOM element
934  */
935 function unMarkAllRows( container_id ) {
937     $("#"+container_id).find("input:checkbox:enabled").removeAttr('checked')
938     .parents("tr").removeClass("marked");
939     return true;
943  * Checks/unchecks all checkbox in given conainer (f.e. a form, fieldset or div)
945  * @param   string   container_id  the container id
946  * @param   boolean  state         new value for checkbox (true or false)
947  * @return  boolean  always true
948  */
949 function setCheckboxes( container_id, state ) {
951     if(state) {
952         $("#"+container_id).find("input:checkbox").attr('checked', 'checked');
953     }
954     else {
955         $("#"+container_id).find("input:checkbox").removeAttr('checked');
956     }
958     return true;
959 } // end of the 'setCheckboxes()' function
962   * Checks/unchecks all options of a <select> element
963   *
964   * @param   string   the form name
965   * @param   string   the element name
966   * @param   boolean  whether to check or to uncheck the element
967   *
968   * @return  boolean  always true
969   */
970 function setSelectOptions(the_form, the_select, do_check)
973     if( do_check ) {
974         $("form[name='"+ the_form +"']").find("select[name='"+the_select+"']").find("option").attr('selected', 'selected');
975     }
976     else {
977         $("form[name='"+ the_form +"']").find("select[name="+the_select+"]").find("option").removeAttr('selected');
978     }
979     return true;
980 } // end of the 'setSelectOptions()' function
984   * Create quick sql statements.
985   *
986   */
987 function insertQuery(queryType) {
988     var myQuery = document.sqlform.sql_query;
989     var myListBox = document.sqlform.dummy;
990     var query = "";
991     var table = document.sqlform.table.value;
993     if (myListBox.options.length > 0) {
994         sql_box_locked = true;
995         var chaineAj = "";
996         var valDis = "";
997         var editDis = "";
998         var NbSelect = 0;
999         for (var i=0; i < myListBox.options.length; i++) {
1000             NbSelect++;
1001             if (NbSelect > 1) {
1002                 chaineAj += ", ";
1003                 valDis += ",";
1004                 editDis += ",";
1005             }
1006             chaineAj += myListBox.options[i].value;
1007             valDis += "[value-" + NbSelect + "]";
1008             editDis += myListBox.options[i].value + "=[value-" + NbSelect + "]";
1009         }
1010     if (queryType == "selectall") {
1011         query = "SELECT * FROM `" + table + "` WHERE 1";
1012     } else if (queryType == "select") {
1013         query = "SELECT " + chaineAj + " FROM `" + table + "` WHERE 1";
1014     } else if (queryType == "insert") {
1015            query = "INSERT INTO `" + table + "`(" + chaineAj + ") VALUES (" + valDis + ")";
1016     } else if (queryType == "update") {
1017         query = "UPDATE `" + table + "` SET " + editDis + " WHERE 1";
1018     } else if(queryType == "delete") {
1019         query = "DELETE FROM `" + table + "` WHERE 1";
1020     }
1021     document.sqlform.sql_query.value = query;
1022     sql_box_locked = false;
1023     }
1028   * Inserts multiple fields.
1029   *
1030   */
1031 function insertValueQuery() {
1032     var myQuery = document.sqlform.sql_query;
1033     var myListBox = document.sqlform.dummy;
1035     if(myListBox.options.length > 0) {
1036         sql_box_locked = true;
1037         var chaineAj = "";
1038         var NbSelect = 0;
1039         for(var i=0; i<myListBox.options.length; i++) {
1040             if (myListBox.options[i].selected){
1041                 NbSelect++;
1042                 if (NbSelect > 1)
1043                     chaineAj += ", ";
1044                 chaineAj += myListBox.options[i].value;
1045             }
1046         }
1048         //IE support
1049         if (document.selection) {
1050             myQuery.focus();
1051             sel = document.selection.createRange();
1052             sel.text = chaineAj;
1053             document.sqlform.insert.focus();
1054         }
1055         //MOZILLA/NETSCAPE support
1056         else if (document.sqlform.sql_query.selectionStart || document.sqlform.sql_query.selectionStart == "0") {
1057             var startPos = document.sqlform.sql_query.selectionStart;
1058             var endPos = document.sqlform.sql_query.selectionEnd;
1059             var chaineSql = document.sqlform.sql_query.value;
1061             myQuery.value = chaineSql.substring(0, startPos) + chaineAj + chaineSql.substring(endPos, chaineSql.length);
1062         } else {
1063             myQuery.value += chaineAj;
1064         }
1065         sql_box_locked = false;
1066     }
1070   * listbox redirection
1071   */
1072 function goToUrl(selObj, goToLocation) {
1073     eval("document.location.href = '" + goToLocation + "pos=" + selObj.options[selObj.selectedIndex].value + "'");
1077  * getElement
1078  */
1079 function getElement(e,f){
1080     if(document.layers){
1081         f=(f)?f:self;
1082         if(f.document.layers[e]) {
1083             return f.document.layers[e];
1084         }
1085         for(W=0;W<f.document.layers.length;W++) {
1086             return(getElement(e,f.document.layers[W]));
1087         }
1088     }
1089     if(document.all) {
1090         return document.all[e];
1091     }
1092     return document.getElementById(e);
1096   * Refresh the WYSIWYG scratchboard after changes have been made
1097   */
1098 function refreshDragOption(e) {
1099     var elm = $('#' + e);
1100     if (elm.css('visibility') == 'visible') {
1101         refreshLayout();
1102         TableDragInit();
1103     }
1107   * Refresh/resize the WYSIWYG scratchboard
1108   */
1109 function refreshLayout() {
1110     var elm = $('#pdflayout')
1111     var orientation = $('#orientation_opt').val();
1112     if($('#paper_opt').length==1){
1113         var paper = $('#paper_opt').val();
1114     }else{
1115         var paper = 'A4';
1116     }
1117     if (orientation == 'P') {
1118         posa = 'x';
1119         posb = 'y';
1120     } else {
1121         posa = 'y';
1122         posb = 'x';
1123     }
1124     elm.css('width', pdfPaperSize(paper, posa) + 'px');
1125     elm.css('height', pdfPaperSize(paper, posb) + 'px');
1129   * Show/hide the WYSIWYG scratchboard
1130   */
1131 function ToggleDragDrop(e) {
1132     var elm = $('#' + e);
1133     if (elm.css('visibility') == 'hidden') {
1134         PDFinit(); /* Defined in pdf_pages.php */
1135         elm.css('visibility', 'visible');
1136         elm.css('display', 'block');
1137         $('#showwysiwyg').val('1')
1138     } else {
1139         elm.css('visibility', 'hidden');
1140         elm.css('display', 'none');
1141         $('#showwysiwyg').val('0')
1142     }
1146   * PDF scratchboard: When a position is entered manually, update
1147   * the fields inside the scratchboard.
1148   */
1149 function dragPlace(no, axis, value) {
1150     var elm = $('#table_' + no);
1151     if (axis == 'x') {
1152         elm.css('left', value + 'px');
1153     } else {
1154         elm.css('top', value + 'px');
1155     }
1159  * Returns paper sizes for a given format
1160  */
1161 function pdfPaperSize(format, axis) {
1162     switch (format.toUpperCase()) {
1163         case '4A0':
1164             if (axis == 'x') return 4767.87; else return 6740.79;
1165             break;
1166         case '2A0':
1167             if (axis == 'x') return 3370.39; else return 4767.87;
1168             break;
1169         case 'A0':
1170             if (axis == 'x') return 2383.94; else return 3370.39;
1171             break;
1172         case 'A1':
1173             if (axis == 'x') return 1683.78; else return 2383.94;
1174             break;
1175         case 'A2':
1176             if (axis == 'x') return 1190.55; else return 1683.78;
1177             break;
1178         case 'A3':
1179             if (axis == 'x') return 841.89; else return 1190.55;
1180             break;
1181         case 'A4':
1182             if (axis == 'x') return 595.28; else return 841.89;
1183             break;
1184         case 'A5':
1185             if (axis == 'x') return 419.53; else return 595.28;
1186             break;
1187         case 'A6':
1188             if (axis == 'x') return 297.64; else return 419.53;
1189             break;
1190         case 'A7':
1191             if (axis == 'x') return 209.76; else return 297.64;
1192             break;
1193         case 'A8':
1194             if (axis == 'x') return 147.40; else return 209.76;
1195             break;
1196         case 'A9':
1197             if (axis == 'x') return 104.88; else return 147.40;
1198             break;
1199         case 'A10':
1200             if (axis == 'x') return 73.70; else return 104.88;
1201             break;
1202         case 'B0':
1203             if (axis == 'x') return 2834.65; else return 4008.19;
1204             break;
1205         case 'B1':
1206             if (axis == 'x') return 2004.09; else return 2834.65;
1207             break;
1208         case 'B2':
1209             if (axis == 'x') return 1417.32; else return 2004.09;
1210             break;
1211         case 'B3':
1212             if (axis == 'x') return 1000.63; else return 1417.32;
1213             break;
1214         case 'B4':
1215             if (axis == 'x') return 708.66; else return 1000.63;
1216             break;
1217         case 'B5':
1218             if (axis == 'x') return 498.90; else return 708.66;
1219             break;
1220         case 'B6':
1221             if (axis == 'x') return 354.33; else return 498.90;
1222             break;
1223         case 'B7':
1224             if (axis == 'x') return 249.45; else return 354.33;
1225             break;
1226         case 'B8':
1227             if (axis == 'x') return 175.75; else return 249.45;
1228             break;
1229         case 'B9':
1230             if (axis == 'x') return 124.72; else return 175.75;
1231             break;
1232         case 'B10':
1233             if (axis == 'x') return 87.87; else return 124.72;
1234             break;
1235         case 'C0':
1236             if (axis == 'x') return 2599.37; else return 3676.54;
1237             break;
1238         case 'C1':
1239             if (axis == 'x') return 1836.85; else return 2599.37;
1240             break;
1241         case 'C2':
1242             if (axis == 'x') return 1298.27; else return 1836.85;
1243             break;
1244         case 'C3':
1245             if (axis == 'x') return 918.43; else return 1298.27;
1246             break;
1247         case 'C4':
1248             if (axis == 'x') return 649.13; else return 918.43;
1249             break;
1250         case 'C5':
1251             if (axis == 'x') return 459.21; else return 649.13;
1252             break;
1253         case 'C6':
1254             if (axis == 'x') return 323.15; else return 459.21;
1255             break;
1256         case 'C7':
1257             if (axis == 'x') return 229.61; else return 323.15;
1258             break;
1259         case 'C8':
1260             if (axis == 'x') return 161.57; else return 229.61;
1261             break;
1262         case 'C9':
1263             if (axis == 'x') return 113.39; else return 161.57;
1264             break;
1265         case 'C10':
1266             if (axis == 'x') return 79.37; else return 113.39;
1267             break;
1268         case 'RA0':
1269             if (axis == 'x') return 2437.80; else return 3458.27;
1270             break;
1271         case 'RA1':
1272             if (axis == 'x') return 1729.13; else return 2437.80;
1273             break;
1274         case 'RA2':
1275             if (axis == 'x') return 1218.90; else return 1729.13;
1276             break;
1277         case 'RA3':
1278             if (axis == 'x') return 864.57; else return 1218.90;
1279             break;
1280         case 'RA4':
1281             if (axis == 'x') return 609.45; else return 864.57;
1282             break;
1283         case 'SRA0':
1284             if (axis == 'x') return 2551.18; else return 3628.35;
1285             break;
1286         case 'SRA1':
1287             if (axis == 'x') return 1814.17; else return 2551.18;
1288             break;
1289         case 'SRA2':
1290             if (axis == 'x') return 1275.59; else return 1814.17;
1291             break;
1292         case 'SRA3':
1293             if (axis == 'x') return 907.09; else return 1275.59;
1294             break;
1295         case 'SRA4':
1296             if (axis == 'x') return 637.80; else return 907.09;
1297             break;
1298         case 'LETTER':
1299             if (axis == 'x') return 612.00; else return 792.00;
1300             break;
1301         case 'LEGAL':
1302             if (axis == 'x') return 612.00; else return 1008.00;
1303             break;
1304         case 'EXECUTIVE':
1305             if (axis == 'x') return 521.86; else return 756.00;
1306             break;
1307         case 'FOLIO':
1308             if (axis == 'x') return 612.00; else return 936.00;
1309             break;
1310     } // end switch
1312     return 0;
1316  * for playing media from the BLOB repository
1318  * @param   var
1319  * @param   var     url_params  main purpose is to pass the token
1320  * @param   var     bs_ref      BLOB repository reference
1321  * @param   var     m_type      type of BLOB repository media
1322  * @param   var     w_width     width of popup window
1323  * @param   var     w_height    height of popup window
1324  */
1325 function popupBSMedia(url_params, bs_ref, m_type, is_cust_type, w_width, w_height)
1327     // if width not specified, use default
1328     if (w_width == undefined)
1329         w_width = 640;
1331     // if height not specified, use default
1332     if (w_height == undefined)
1333         w_height = 480;
1335     // open popup window (for displaying video/playing audio)
1336     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');
1340  * popups a request for changing MIME types for files in the BLOB repository
1342  * @param   var     db                      database name
1343  * @param   var     table                   table name
1344  * @param   var     reference               BLOB repository reference
1345  * @param   var     current_mime_type       current MIME type associated with BLOB repository reference
1346  */
1347 function requestMIMETypeChange(db, table, reference, current_mime_type)
1349     // no mime type specified, set to default (nothing)
1350     if (undefined == current_mime_type)
1351         current_mime_type = "";
1353     // prompt user for new mime type
1354     var new_mime_type = prompt("Enter custom MIME type", current_mime_type);
1356     // if new mime_type is specified and is not the same as the previous type, request for mime type change
1357     if (new_mime_type && new_mime_type != current_mime_type)
1358         changeMIMEType(db, table, reference, new_mime_type);
1362  * changes MIME types for files in the BLOB repository
1364  * @param   var     db              database name
1365  * @param   var     table           table name
1366  * @param   var     reference       BLOB repository reference
1367  * @param   var     mime_type       new MIME type to be associated with BLOB repository reference
1368  */
1369 function changeMIMEType(db, table, reference, mime_type)
1371     // specify url and parameters for jQuery POST
1372     var mime_chg_url = 'bs_change_mime_type.php';
1373     var params = {bs_db: db, bs_table: table, bs_reference: reference, bs_new_mime_type: mime_type};
1375     // jQuery POST
1376     jQuery.post(mime_chg_url, params);
1380  * Jquery Coding for inline editing SQL_QUERY
1381  */
1382 $(document).ready(function(){
1383     var oldText,db,table,token,sql_query;
1384     oldText=$(".inner_sql").html();
1385     $("#inline_edit").click(function(){
1386         db=$("input[name='db']").val();
1387         table=$("input[name='table']").val();
1388         token=$("input[name='token']").val();
1389         sql_query=$("input[name='sql_query']").val();
1390         $(".inner_sql").replaceWith("<textarea name=\"sql_query_edit\" id=\"sql_query_edit\">"+ sql_query +"</textarea><input type=\"button\" id=\"btnSave\" value=\"" + PMA_messages['strGo'] + "\"><input type=\"button\" id=\"btnDiscard\" value=\"" + PMA_messages['strCancel'] + "\">");
1391         return false;
1392     });
1394     $("#btnSave").live("click",function(){
1395         window.location.replace("import.php?db=" + db +"&table=" + table + "&sql_query=" + $("#sql_query_edit").val()+"&show_query=1&token=" + token + "");
1396     });
1398     $("#btnDiscard").live("click",function(){
1399         $(".sql").html("<span class=\"syntax\"><span class=\"inner_sql\">" + oldText + "</span></span>");
1400     });
1402     $('.sqlbutton').click(function(evt){
1403         insertQuery(evt.target.id);
1404         return false;
1405     });
1407     $("#export_type").change(function(){
1408         if($("#export_type").val()=='svg'){
1409             $("#show_grid_opt").attr("disabled","disabled");
1410             $("#orientation_opt").attr("disabled","disabled");
1411             $("#with_doc").attr("disabled","disabled");
1412             $("#show_table_dim_opt").removeAttr("disabled");
1413             $("#all_table_same_wide").removeAttr("disabled");
1414             $("#paper_opt").removeAttr("disabled","disabled");
1415             $("#show_color_opt").removeAttr("disabled","disabled");
1416             //$(this).css("background-color","yellow");
1417         }else if($("#export_type").val()=='dia'){
1418             $("#show_grid_opt").attr("disabled","disabled");
1419             $("#with_doc").attr("disabled","disabled");
1420             $("#show_table_dim_opt").attr("disabled","disabled");
1421             $("#all_table_same_wide").attr("disabled","disabled");
1422             $("#paper_opt").removeAttr("disabled","disabled");
1423             $("#show_color_opt").removeAttr("disabled","disabled");
1424             $("#orientation_opt").removeAttr("disabled","disabled");
1425         }else if($("#export_type").val()=='eps'){
1426             $("#show_grid_opt").attr("disabled","disabled");
1427             $("#orientation_opt").removeAttr("disabled");
1428             $("#with_doc").attr("disabled","disabled");
1429             $("#show_table_dim_opt").attr("disabled","disabled");
1430             $("#all_table_same_wide").attr("disabled","disabled");
1431             $("#paper_opt").attr("disabled","disabled");
1432             $("#show_color_opt").attr("disabled","disabled");
1434         }else if($("#export_type").val()=='pdf'){
1435             $("#show_grid_opt").removeAttr("disabled");
1436             $("#orientation_opt").removeAttr("disabled");
1437             $("#with_doc").removeAttr("disabled","disabled");
1438             $("#show_table_dim_opt").removeAttr("disabled","disabled");
1439             $("#all_table_same_wide").removeAttr("disabled","disabled");
1440             $("#paper_opt").removeAttr("disabled","disabled");
1441             $("#show_color_opt").removeAttr("disabled","disabled");
1442         }else{
1443             // nothing
1444         }
1445     });
1447     $('#sqlquery').focus();
1448     if ($('#input_username')) {
1449         if ($('#input_username').val() == '') {
1450             $('#input_username').focus();
1451         } else {
1452             $('#input_password').focus();
1453         }
1454     }
1458  * Function to process the plain HTML response from an Ajax request.  Inserts
1459  * the various HTML divisions from the response at the proper locations.  The
1460  * array relates the divisions to be inserted to their placeholders.
1462  * @param   var divisions_map   an associative array of id names
1464  * <code>
1465  * PMA_ajaxInsertResponse({'resultsTable':'resultsTable_response',
1466  *                         'profilingData':'profilingData_response'});
1467  * </code>
1469  */
1471 function PMA_ajaxInsertResponse(divisions_map) {
1472     $.each(divisions_map, function(key, value) {
1473         var content_div = '#'+value;
1474         var target_div = '#'+key;
1475         var content = $(content_div).html();
1477         //replace content of target_div with that from the response
1478         $(target_div).html(content);
1479     });
1483  * Show a message on the top of the page for an Ajax request
1485  * @param   var     message     string containing the message to be shown.
1486  *                              optional, defaults to 'Loading...'
1487  * @param   var     timeout     number of milliseconds for the message to be visible
1488  *                              optional, defaults to 5000
1489  */
1491 function PMA_ajaxShowMessage(message, timeout) {
1493     //Handle the case when a empty data.message is passed.  We don't want the empty message
1494     if(message == '') {
1495         return true;
1496     }
1498     /**
1499      * @var msg String containing the message that has to be displayed
1500      * @default PMA_messages['strLoading']
1501      */
1502     if(!message) {
1503         var msg = PMA_messages['strLoading'];
1504     }
1505     else {
1506         var msg = message;
1507     }
1509     /**
1510      * @var timeout Number of milliseconds for which {@link msg} will be visible
1511      * @default 5000 ms
1512      */
1513     if(!timeout) {
1514         var to = 5000;
1515     }
1516     else {
1517         var to = timeout;
1518     }
1520     if( !ajax_message_init) {
1521         //For the first time this function is called, append a new div
1522         $(function(){
1523             $('<div id="loading_parent"></div>')
1524             .insertBefore("#serverinfo");
1526             $('<span id="loading" class="ajax_notification"></span>')
1527             .appendTo("#loading_parent")
1528             .html(msg)
1529             .slideDown('medium')
1530             .delay(to)
1531             .slideUp('medium', function(){
1532                 $(this)
1533                 .html("") //Clear the message
1534                 .hide();
1535             });
1536         }, 'top.frame_content');
1537         ajax_message_init = true;
1538     }
1539     else {
1540         //Otherwise, just show the div again after inserting the message
1541         $("#loading")
1542         .clearQueue()
1543         .html(msg)
1544         .slideDown('medium')
1545         .delay(to)
1546         .slideUp('medium', function() {
1547             $(this)
1548             .html("")
1549             .hide();
1550         })
1551     }
1555  * Hides/shows the "Open in ENUM/SET editor" message, depending on the data type of the column currently selected
1556  */
1557 function toggle_enum_notice(selectElement) {
1558     var enum_notice_id = selectElement.attr("id").split("_")[1];
1559     enum_notice_id += "_" + (parseInt(selectElement.attr("id").split("_")[2]) + 1);
1560     var selectedType = selectElement.attr("value");
1561     if (selectedType == "ENUM" || selectedType == "SET") {
1562         $("p[id='enum_notice_" + enum_notice_id + "']").show();
1563     } else {
1564         $("p[id='enum_notice_" + enum_notice_id + "']").hide();
1565     }
1569  * jQuery function that uses jQueryUI's dialogs to confirm with user. Does not
1570  *  return a jQuery object yet and hence cannot be chained
1572  * @param   string      question
1573  * @param   string      url         URL to be passed to the callbackFn to make
1574  *                                  an Ajax call to
1575  * @param   function    callbackFn  callback to execute after user clicks on OK
1576  */
1578 jQuery.fn.PMA_confirm = function(question, url, callbackFn) {
1579     if (PMA_messages['strDoYouReally'] == '') {
1580         return true;
1581     }
1583     /**
1584      *  @var    button_options  Object that stores the options passed to jQueryUI
1585      *                          dialog
1586      */
1587     var button_options = {};
1588     button_options[PMA_messages['strOK']] = function(){
1589                                                 $(this).dialog("close").remove();
1591                                                 if($.isFunction(callbackFn)) {
1592                                                     callbackFn.call(this, url);
1593                                                 }
1594                                             };
1595     button_options[PMA_messages['strCancel']] = function() {$(this).dialog("close").remove();}
1597     $('<div id="confirm_dialog"></div>')
1598     .prepend(question)
1599     .dialog({buttons: button_options});
1603  * jQuery function to sort a table's body after a new row has been appended to it.
1604  * Also fixes the even/odd classes of the table rows at the end.
1606  * @param   string      text_selector   string to select the sortKey's text
1608  * @return  jQuery Object for chaining purposes
1609  */
1610 jQuery.fn.PMA_sort_table = function(text_selector) {
1611     return this.each(function() {
1613         /**
1614          * @var table_body  Object referring to the table's <tbody> element
1615          */
1616         var table_body = $(this);
1617         /**
1618          * @var rows    Object referring to the collection of rows in {@link table_body}
1619          */
1620         var rows = $(this).find('tr').get();
1622         //get the text of the field that we will sort by
1623         $.each(rows, function(index, row) {
1624             row.sortKey = $.trim($(row).find(text_selector).text().toLowerCase());
1625         })
1627         //get the sorted order
1628         rows.sort(function(a,b) {
1629             if(a.sortKey < b.sortKey) {
1630                 return -1;
1631             }
1632             if(a.sortKey > b.sortKey) {
1633                 return 1;
1634             }
1635             return 0;
1636         })
1638         //pull out each row from the table and then append it according to it's order
1639         $.each(rows, function(index, row) {
1640             $(table_body).append(row);
1641             row.sortKey = null;
1642         })
1644         //Re-check the classes of each row
1645         $(this).find('tr:odd')
1646         .removeClass('even').addClass('odd')
1647         .end()
1648         .find('tr:even')
1649         .removeClass('odd').addClass('even');
1650     })
1654  * jQuery coding for 'Create Table'.  Used on db_operations.php,
1655  * db_structure.php and db_tracking.php (i.e., wherever
1656  * libraries/display_create_table.lib.php is used)
1658  * Attach Ajax Event handlers for Create Table
1659  */
1660 $(document).ready(function() {
1662     /**
1663      * Attach event handler to the submit action of the create table minimal form
1664      * and retrieve the full table form and display it in a dialog
1665      *
1666      * @uses    PMA_ajaxShowMessage()
1667      */
1668     $("#create_table_form_minimal.ajax").live('submit', function(event) {
1669         event.preventDefault();
1670         $form = $(this);
1672         /* @todo Validate this form! */
1674         /**
1675          *  @var    button_options  Object that stores the options passed to jQueryUI
1676          *                          dialog
1677          */
1678         var button_options = {};
1679         // in the following function we need to use $(this)
1680         button_options[PMA_messages['strCancel']] = function() {$(this).dialog('close').remove();}
1682         var button_options_error = {};
1683         button_options_error[PMA_messages['strOK']] = function() {$(this).dialog('close').remove();}
1685         PMA_ajaxShowMessage();
1686         if (! $form.find('input:hidden').is('#ajax_request_hidden')) {
1687             $form.append('<input type="hidden" id="ajax_request_hidden" name="ajax_request" value="true" />');
1688         }
1690         $.get($form.attr('action'), $form.serialize(), function(data) {
1691             //in the case of an error, show the error message returned.
1692             if (data.success != undefined && data.success == false) {
1693                 $('<div id="create_table_dialog"></div>')
1694                 .append(data.error)
1695                 .dialog({
1696                     title: PMA_messages['strCreateTable'],
1697                     height: 230,
1698                     width: 900,
1699                     open: PMA_verifyTypeOfAllColumns,
1700                     buttons : button_options_error
1701                 })// end dialog options
1702                 //remove the redundant [Back] link in the error message.
1703                 .find('fieldset').remove();
1704             } else {
1705                 $('<div id="create_table_dialog"></div>')
1706                 .append(data)
1707                 .dialog({
1708                     title: PMA_messages['strCreateTable'],
1709                     height: 600,
1710                     width: 900,
1711                     open: PMA_verifyTypeOfAllColumns,
1712                     buttons : button_options
1713                 }); // end dialog options
1714             }
1715         }) // end $.get()
1717         // empty table name and number of columns from the minimal form 
1718         $form.find('input[name=table],input[name=num_fields]').val('');
1719     });
1721     /**
1722      * Attach event handler for submission of create table form (save)
1723      *
1724      * @uses    PMA_ajaxShowMessage()
1725      * @uses    $.PMA_sort_table()
1726      *
1727      */
1728     // .live() must be called after a selector, see http://api.jquery.com/live
1729     $("#create_table_form.ajax input[name=do_save_data]").live('click', function(event) {
1730         event.preventDefault();
1732         /**
1733          *  @var    the_form    object referring to the create table form
1734          */
1735         var $form = $("#create_table_form");
1737         PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
1738         if (! $form.find('input:hidden').is('#ajax_request_hidden')) {
1739             $form.append('<input type="hidden" id="ajax_request_hidden" name="ajax_request" value="true" />');
1740         }
1741         //User wants to submit the form
1742         $.post($form.attr('action'), $form.serialize() + "&do_save_data=" + $(this).val(), function(data) {
1743             if(data.success == true) {
1744                 PMA_ajaxShowMessage(data.message);
1745                 $("#create_table_dialog").dialog("close").remove();
1747                 /**
1748                  * @var tables_table    Object referring to the <tbody> element that holds the list of tables
1749                  */
1750                 var tables_table = $("#tablesForm").find("tbody").not("#tbl_summary_row");
1751                 // this is the first table created in this db
1752                 if (tables_table.length == 0) {
1753                     if (window.parent && window.parent.frame_content) {
1754                         window.parent.frame_content.location.reload();
1755                     }
1756                 } else {
1757                     /**
1758                      * @var curr_last_row   Object referring to the last <tr> element in {@link tables_table}
1759                      */
1760                     var curr_last_row = $(tables_table).find('tr:last');
1761                     /**
1762                      * @var curr_last_row_index_string   String containing the index of {@link curr_last_row}
1763                      */
1764                     var curr_last_row_index_string = $(curr_last_row).find('input:checkbox').attr('id').match(/\d+/)[0];
1765                     /**
1766                      * @var curr_last_row_index Index of {@link curr_last_row}
1767                      */
1768                     var curr_last_row_index = parseFloat(curr_last_row_index_string);
1769                     /**
1770                      * @var new_last_row_index   Index of the new row to be appended to {@link tables_table}
1771                      */
1772                     var new_last_row_index = curr_last_row_index + 1;
1773                     /**
1774                      * @var new_last_row_id String containing the id of the row to be appended to {@link tables_table}
1775                      */
1776                     var new_last_row_id = 'checkbox_tbl_' + new_last_row_index;
1778                     //append to table
1779                     $(data.new_table_string)
1780                      .find('input:checkbox')
1781                      .val(new_last_row_id)
1782                      .end()
1783                      .appendTo(tables_table);
1785                     //Sort the table
1786                     $(tables_table).PMA_sort_table('th');
1787                 }
1789                 //Refresh navigation frame as a new table has been added
1790                 if (window.parent && window.parent.frame_navigation) {
1791                     window.parent.frame_navigation.location.reload();
1792                 }
1793             }
1794             else {
1795                 PMA_ajaxShowMessage(data.error);
1796             }
1797         }) // end $.post()
1798     }) // end create table form (save) 
1800     /**
1801      * Attach event handler for create table form (add fields)
1802      *
1803      * @uses    PMA_ajaxShowMessage()
1804      * @uses    $.PMA_sort_table()
1805      * @uses    window.parent.refreshNavigation()
1806      *
1807      */
1808     // .live() must be called after a selector, see http://api.jquery.com/live
1809     $("#create_table_form.ajax input[name=submit_num_fields]").live('click', function(event) {
1810         event.preventDefault();
1812         /**
1813          *  @var    the_form    object referring to the create table form
1814          */
1815         var $form = $("#create_table_form");
1817         PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
1818         if (! $form.find('input:hidden').is('#ajax_request_hidden')) {
1819             $form.append('<input type="hidden" id="ajax_request_hidden" name="ajax_request" value="true" />');
1820         }
1822         //User wants to add more fields to the table
1823         $.post($form.attr('action'), $form.serialize() + "&submit_num_fields=" + $(this).val(), function(data) {
1824             $("#create_table_dialog").html(data);
1825         }) //end $.post()
1827     }) // end create table form (add fields) 
1829 }, 'top.frame_content'); //end $(document).ready for 'Create Table'
1832  * Attach Ajax event handlers for Drop Trigger.  Used on tbl_structure.php
1833  * @see $cfg['AjaxEnable']
1834  */
1835 $(document).ready(function() {
1837     $(".drop_trigger_anchor").live('click', function(event) {
1838         event.preventDefault();
1840         $anchor = $(this);
1841         /**
1842          * @var curr_row    Object reference to the current trigger's <tr>
1843          */
1844         var $curr_row = $anchor.parents('tr');
1845         /**
1846          * @var question    String containing the question to be asked for confirmation
1847          */
1848         var question = 'DROP TRIGGER IF EXISTS `' + $curr_row.children('td:first').text() + '`';
1850         $anchor.PMA_confirm(question, $anchor.attr('href'), function(url) {
1852             PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
1853             $.get(url, {'is_js_confirmed': 1, 'ajax_request': true}, function(data) {
1854                 if(data.success == true) {
1855                     PMA_ajaxShowMessage(data.message);
1856                     $("#topmenucontainer")
1857                     .next('div')
1858                     .remove()
1859                     .end()
1860                     .after(data.sql_query);
1861                     $curr_row.hide("medium").remove();
1862                 }
1863                 else {
1864                     PMA_ajaxShowMessage(data.error);
1865                 }
1866             }) // end $.get()
1867         }) // end $.PMA_confirm()
1868     }) // end $().live()
1869 }, 'top.frame_content'); //end $(document).ready() for Drop Trigger
1872  * Attach Ajax event handlers for Drop Database. Moved here from db_structure.js
1873  * as it was also required on db_create.php
1875  * @uses    $.PMA_confirm()
1876  * @uses    PMA_ajaxShowMessage()
1877  * @uses    window.parent.refreshNavigation()
1878  * @uses    window.parent.refreshMain()
1879  */
1880 $(document).ready(function() {
1881     $("#drop_db_anchor").live('click', function(event) {
1882         event.preventDefault();
1884         //context is top.frame_content, so we need to use window.parent.db to access the db var
1885         /**
1886          * @var question    String containing the question to be asked for confirmation
1887          */
1888         var question = PMA_messages['strDropDatabaseStrongWarning'] + '\n' + PMA_messages['strDoYouReally'] + ' :\n' + 'DROP DATABASE ' + window.parent.db;
1890         $(this).PMA_confirm(question, $(this).attr('href') ,function(url) {
1892             PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
1893             $.get(url, {'is_js_confirmed': '1', 'ajax_request': true}, function(data) {
1894                 //Database deleted successfully, refresh both the frames
1895                 window.parent.refreshNavigation();
1896                 window.parent.refreshMain();
1897             }) // end $.get()
1898         }); // end $.PMA_confirm()
1899     }); //end of Drop Database Ajax action
1900 }) // end of $(document).ready() for Drop Database
1903  * Attach Ajax event handlers for 'Create Database'.  Used wherever libraries/
1904  * display_create_database.lib.php is used, ie main.php and server_databases.php
1906  * @uses    PMA_ajaxShowMessage()
1907  */
1908 $(document).ready(function() {
1910     $('#create_database_form').live('submit', function(event) {
1911         event.preventDefault();
1913         $form = $(this);
1915         PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
1917         if (! $form.find('input:hidden').is('#ajax_request_hidden')) {
1918             $form.append('<input type="hidden" id="ajax_request_hidden" name="ajax_request" value="true" />');
1919         }
1921         $.post($form.attr('action'), $form.serialize(), function(data) {
1922             if(data.success == true) {
1923                 PMA_ajaxShowMessage(data.message);
1925                 //Append database's row to table
1926                 $("#tabledatabases")
1927                 .find('tbody')
1928                 .append(data.new_db_string)
1929                 .PMA_sort_table('.name')
1930                 .find('#db_summary_row')
1931                 .appendTo('#tabledatabases tbody')
1932                 .removeClass('odd even');
1934                 var $databases_count_object = $('#databases_count');
1935                 var databases_count = parseInt($databases_count_object.text()); 
1936                 $databases_count_object.text(++databases_count);
1937                 //Refresh navigation frame as a new database has been added
1938                 if (window.parent && window.parent.frame_navigation) {
1939                     window.parent.frame_navigation.location.reload();
1940                 }
1941             }
1942             else {
1943                 PMA_ajaxShowMessage(data.error);
1944             }
1945         }) // end $.post()
1946     }) // end $().live()
1947 })  // end $(document).ready() for Create Database
1950  * Attach Ajax event handlers for 'Change Password' on main.php
1951  */
1952 $(document).ready(function() {
1954     /**
1955      * Attach Ajax event handler on the change password anchor
1956      */
1957     $('#change_password_anchor').live('click', function(event) {
1958         event.preventDefault();
1960         /**
1961          * @var button_options  Object containing options to be passed to jQueryUI's dialog
1962          */
1963         var button_options = {};
1965         button_options[PMA_messages['strCancel']] = function() {$(this).dialog('close').remove();}
1967         $.get($(this).attr('href'), {'ajax_request': true}, function(data) {
1968             $('<div id="change_password_dialog"></div>')
1969             .dialog({
1970                 title: PMA_messages['strChangePassword'],
1971                 width: 600,
1972                 buttons : button_options
1973             })
1974             .append(data);
1975             displayPasswordGenerateButton();
1976         }) // end $.get()
1977     }) // end handler for change password anchor
1979     /**
1980      * Attach Ajax event handler for Change Password form submission
1981      *
1982      * @uses    PMA_ajaxShowMessage()
1983      */
1984     $("#change_password_form").find('input[name=change_pw]').live('click', function(event) {
1985         event.preventDefault();
1987         /**
1988          * @var the_form    Object referring to the change password form
1989          */
1990         var the_form = $("#change_password_form");
1992         /**
1993          * @var this_value  String containing the value of the submit button.
1994          * Need to append this for the change password form on Server Privileges
1995          * page to work
1996          */
1997         var this_value = $(this).val();
1999         PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
2000         $(the_form).append('<input type="hidden" name="ajax_request" value="true" />');
2002         $.post($(the_form).attr('action'), $(the_form).serialize() + '&change_pw='+ this_value, function(data) {
2003             if(data.success == true) {
2005                 PMA_ajaxShowMessage(data.message);
2007                 $("#topmenucontainer").after(data.sql_query);
2009                 $("#change_password_dialog").hide().remove();
2010                 $("#edit_user_dialog").dialog("close").remove();
2011             }
2012             else {
2013                 PMA_ajaxShowMessage(data.error);
2014             }
2015         }) // end $.post()
2016     }) // end handler for Change Password form submission
2017 }) // end $(document).ready() for Change Password
2020  * Toggle the hiding/showing of the "Open in ENUM/SET editor" message when
2021  * the page loads and when the selected data type changes
2022  */
2023 $(document).ready(function() {
2024     // is called here for normal page loads and also when opening
2025     // the Create table dialog
2026     PMA_verifyTypeOfAllColumns();
2027     //
2028     // needs live() to work also in the Create Table dialog
2029     $("select[class='column_type']").live('change', function() {
2030         toggle_enum_notice($(this));
2031     });
2034 function PMA_verifyTypeOfAllColumns() {
2035     $("select[class='column_type']").each(function() {
2036         toggle_enum_notice($(this));
2037     });
2041  * Closes the ENUM/SET editor and removes the data in it
2042  */
2043 function disable_popup() {
2044     $("#popup_background").fadeOut("fast");
2045     $("#enum_editor").fadeOut("fast");
2046     // clear the data from the text boxes
2047     $("#enum_editor #values input").remove();
2048     $("#enum_editor input[type='hidden']").remove();
2052  * Opens the ENUM/SET editor and controls its functions
2053  */
2054 $(document).ready(function() {
2055     // Needs live() to work also in the Create table dialog
2056     $("a[class='open_enum_editor']").live('click', function() {
2057         // Center the popup
2058         var windowWidth = document.documentElement.clientWidth;
2059         var windowHeight = document.documentElement.clientHeight;
2060         var popupWidth = windowWidth/2;
2061         var popupHeight = windowHeight*0.8;
2062         var popupOffsetTop = windowHeight/2 - popupHeight/2;
2063         var popupOffsetLeft = windowWidth/2 - popupWidth/2;
2064         $("#enum_editor").css({"position":"absolute", "top": popupOffsetTop, "left": popupOffsetLeft, "width": popupWidth, "height": popupHeight});
2066         // Make it appear
2067         $("#popup_background").css({"opacity":"0.7"});
2068         $("#popup_background").fadeIn("fast");
2069         $("#enum_editor").fadeIn("fast");
2071         // Get the values
2072         var values = $(this).parent().prev("input").attr("value").split(",");
2073         $.each(values, function(index, val) {
2074             if(jQuery.trim(val) != "") {
2075                  // enclose the string in single quotes if it's not already
2076                  if(val.substr(0, 1) != "'") {
2077                       val = "'" + val;
2078                  }
2079                  if(val.substr(val.length-1, val.length) != "'") {
2080                       val = val + "'";
2081                  }
2082                 // escape the single quotes, except the mandatory ones enclosing the entire string
2083                 val = val.substr(1, val.length-2).replace(/''/g, "'").replace(/\\\\/g, '\\').replace(/\\'/g, "'").replace(/'/g, "&#039;");
2084                 // escape the greater-than symbol
2085                 val = val.replace(/>/g, "&gt;");
2086                 $("#enum_editor #values").append("<input type='text' value=" + val + " />");
2087             }
2088         });
2089         // So we know which column's data is being edited
2090         $("#enum_editor").append("<input type='hidden' value='" + $(this).parent().prev("input").attr("id") + "' />");
2091         return false;
2092     });
2094     // If the "close" link is clicked, close the enum editor
2095     // Needs live() to work also in the Create table dialog
2096     $("a[class='close_enum_editor']").live('click', function() {
2097         disable_popup();
2098     });
2100     // If the "cancel" link is clicked, close the enum editor
2101     // Needs live() to work also in the Create table dialog
2102     $("a[class='cancel_enum_editor']").live('click', function() {
2103         disable_popup();
2104     });
2106     // When "add a new value" is clicked, append an empty text field
2107     // Needs live() to work also in the Create table dialog
2108     $("a[class='add_value']").live('click', function() {
2109         $("#enum_editor #values").append("<input type='text' />");
2110     });
2112     // When the submit button is clicked, put the data back into the original form
2113     // Needs live() to work also in the Create table dialog
2114     $("#enum_editor input[type='submit']").live('click', function() {
2115         var value_array = new Array();
2116         $.each($("#enum_editor #values input"), function(index, input_element) {
2117             val = jQuery.trim(input_element.value);
2118             if(val != "") {
2119                 value_array.push("'" + val.replace(/\\/g, '\\\\').replace(/'/g, "''") + "'");
2120             }
2121         });
2122         // get the Length/Values text field where this value belongs
2123         var values_id = $("#enum_editor input[type='hidden']").attr("value");
2124         $("input[id='" + values_id + "']").attr("value", value_array.join(","));
2125         disable_popup();
2126      });
2128     /**
2129      * Hides certain table structure actions, replacing them with the word "More". They are displayed
2130      * in a dropdown menu when the user hovers over the word "More."
2131      */
2132     // Remove the actions from the table cells (they are available by default for JavaScript-disabled browsers)
2133     // if the table is not a view or information_schema (otherwise there is only one action to hide and there's no point)
2134     if($("input[type='hidden'][name='table_type']").val() == "table") {
2135             var $table = $("table[id='tablestructure']");
2136         $table.find("td[class='browse']").remove();
2137         $table.find("td[class='primary']").remove();
2138         $table.find("td[class='unique']").remove();
2139         $table.find("td[class='index']").remove();
2140         $table.find("td[class='fulltext']").remove();
2141         $table.find("th[class='action']").attr("colspan", 3);
2143         // Display the "more" text
2144         $table.find("td[class='more_opts']").show();
2146         // Position the dropdown
2147         $(".structure_actions_dropdown").each(function() {
2148             // Optimize DOM querying
2149             var $this_dropdown = $(this);
2150              // The top offset must be set for IE even if it didn't change
2151             var cell_right_edge_offset = $this_dropdown.parent().offset().left + $this_dropdown.parent().innerWidth();
2152             var left_offset = cell_right_edge_offset - $this_dropdown.innerWidth();
2153             var top_offset = $this_dropdown.parent().offset().top + $this_dropdown.parent().innerHeight();
2154             $this_dropdown.offset({ top: top_offset, left: left_offset });
2155         });
2157         // A hack for IE6 to prevent the after_field select element from being displayed on top of the dropdown by
2158         // positioning an iframe directly on top of it
2159         var $after_field = $("select[name='after_field']");
2160             $("iframe[class='IE_hack']")
2161                     .width($after_field.width())
2162             .height($after_field.height())
2163             .offset({
2164                 top: $after_field.offset().top,
2165                 left: $after_field.offset().left
2166             });
2168         // When "more" is hovered over, show the hidden actions
2169         $table.find("td[class='more_opts']")
2170                     .mouseenter(function() {
2171                 if($.browser.msie && $.browser.version == "6.0") {
2172                     $("iframe[class='IE_hack']")
2173                                 .show()
2174                         .width($after_field.width()+4)
2175                         .height($after_field.height()+4)
2176                         .offset({
2177                             top: $after_field.offset().top,
2178                             left: $after_field.offset().left
2179                         });
2180                 }
2181                 $(".structure_actions_dropdown").hide(); // Hide all the other ones that may be open
2182                 $(this).children(".structure_actions_dropdown").show();
2183                 // Need to do this again for IE otherwise the offset is wrong
2184                 if($.browser.msie) {
2185                     var left_offset_IE = $(this).offset().left + $(this).innerWidth() - $(this).children(".structure_actions_dropdown").innerWidth();
2186                     var top_offset_IE = $(this).offset().top + $(this).innerHeight();
2187                     $(this).children(".structure_actions_dropdown").offset({
2188                             top: top_offset_IE,
2189                             left: left_offset_IE });
2190                 }
2191             })
2192             .mouseleave(function() {
2193                 $(this).children(".structure_actions_dropdown").hide();
2194                 if($.browser.msie && $.browser.version == "6.0") {
2195                     $("iframe[class='IE_hack']").hide();
2196                 }
2197             });
2198     }
2201 /* Displays tooltips */
2202 $(document).ready(function() {
2203     // Hide the footnotes from the footer (which are displayed for
2204     // JavaScript-disabled browsers) since the tooltip is sufficient
2205     $(".footnotes").hide();
2206     $(".footnotes span").each(function() {
2207         $(this).children("sup").remove();
2208     });
2209     // The border and padding must be removed otherwise a thin yellow box remains visible
2210     $(".footnotes").css("border", "none");
2211     $(".footnotes").css("padding", "0px");
2213     // Replace the superscripts with the help icon
2214     $("sup[class='footnotemarker']").hide();
2215     $("img[class='footnotemarker']").show();
2217     $("img[class='footnotemarker']").each(function() {
2218         var span_id = $(this).attr("id");
2219         span_id = span_id.split("_")[1];
2220         var tooltip_text = $(".footnotes span[id='footnote_" + span_id + "']").html();
2221         $(this).qtip({
2222             content: tooltip_text,
2223             show: { delay: 0 },
2224             hide: { when: 'unfocus', delay: 0 },
2225             style: { background: '#ffffcc' }
2226         });
2227     });
2230 function menuResize()
2232     var cnt = $('#topmenu');
2233     var wmax = cnt.width() - 5; // 5 px margin for jumping menu in Chrome
2234     var submenu = cnt.find('.submenu');
2235     var submenu_w = submenu.outerWidth(true);
2236     var submenu_ul = submenu.find('ul');
2237     var li = cnt.find('> li');
2238     var li2 = submenu_ul.find('li');
2239     var more_shown = li2.length > 0;
2240     var w = more_shown ? submenu_w : 0;
2242     // hide menu items
2243     var hide_start = 0;
2244     for (var i = 0; i < li.length-1; i++) { // li.length-1: skip .submenu element
2245         var el = $(li[i]);
2246         var el_width = el.outerWidth(true);
2247         el.data('width', el_width);
2248         w += el_width;
2249         if (w > wmax) {
2250             w -= el_width;
2251             if (w + submenu_w < wmax) {
2252                 hide_start = i;
2253             } else {
2254                 hide_start = i-1;
2255                 w -= $(li[i-1]).data('width');
2256             }
2257             break;
2258         }
2259     }
2261     if (hide_start > 0) {
2262         for (var i = hide_start; i < li.length-1; i++) {
2263             $(li[i])[more_shown ? 'prependTo' : 'appendTo'](submenu_ul);
2264         }
2265         submenu.show();
2266     } else if (more_shown) {
2267         w -= submenu_w;
2268         // nothing hidden, maybe something can be restored
2269         for (var i = 0; i < li2.length; i++) {
2270             //console.log(li2[i], submenu_w);
2271             w += $(li2[i]).data('width');
2272             // item fits or (it is the last item and it would fit if More got removed)
2273             if (w+submenu_w < wmax || (i == li2.length-1 && w < wmax)) {
2274                 $(li2[i]).insertBefore(submenu);
2275                 if (i == li2.length-1) {
2276                     submenu.hide();
2277                 }
2278                 continue;
2279             }
2280             break;
2281         }
2282     }
2283     if (submenu.find('.tabactive').length) {
2284         submenu.addClass('active').find('> a').removeClass('tab').addClass('tabactive');
2285     } else {
2286         submenu.removeClass('active').find('> a').addClass('tab').removeClass('tabactive');
2287     }
2290 $(function() {
2291     var topmenu = $('#topmenu');
2292     if (topmenu.length == 0) {
2293         return;
2294     }
2295     // create submenu container
2296     var link = $('<a />', {href: '#', 'class': 'tab'})
2297         .text(PMA_messages['strMore'])
2298         .click(function(e) {
2299             e.preventDefault();
2300         });
2301     var img = topmenu.find('li:first-child img');
2302     if (img.length) {
2303         img.clone().attr('src', img.attr('src').replace(/\/[^\/]+$/, '/b_more.png')).prependTo(link);
2304     }
2305     var submenu = $('<li />', {'class': 'submenu'})
2306         .append(link)
2307         .append($('<ul />'))
2308         .mouseenter(function() {
2309             if ($(this).find('ul .tabactive').length == 0) {
2310                 $(this).addClass('submenuhover').find('> a').addClass('tabactive');
2311             }
2312         })
2313         .mouseleave(function() {
2314             if ($(this).find('ul .tabactive').length == 0) {
2315                 $(this).removeClass('submenuhover').find('> a').removeClass('tabactive');
2316             }
2317         })
2318         .hide();
2319     topmenu.append(submenu);
2321     // populate submenu and register resize event
2322     $(window).resize(menuResize);
2323     menuResize();
2327  * For the checkboxes in browse mode, handles the shift/click (only works
2328  * in horizontal mode) and propagates the click to the "companion" checkbox
2329  * (in both horizontal and vertical). Works also for pages reached via AJAX.
2330  */
2331 $(document).ready(function() {
2332     $('.multi_checkbox').live('click',function(e) {
2333         var current_checkbox_id = this.id;
2334         var left_checkbox_id = current_checkbox_id.replace('_right', '_left');
2335         var right_checkbox_id = current_checkbox_id.replace('_left', '_right');
2336         var other_checkbox_id = '';
2337         if (current_checkbox_id == left_checkbox_id) {
2338             other_checkbox_id = right_checkbox_id; 
2339         } else {
2340             other_checkbox_id = left_checkbox_id;
2341         }
2343         var $current_checkbox = $('#' + current_checkbox_id);
2344         var $other_checkbox = $('#' + other_checkbox_id);
2346         if (e.shiftKey) {
2347             var index_of_current_checkbox = $('.multi_checkbox').index($current_checkbox);
2348             var $last_checkbox = $('.multi_checkbox').filter('.last_clicked');
2349             var index_of_last_click = $('.multi_checkbox').index($last_checkbox);
2350             $('.multi_checkbox')
2351                 .filter(function(index) {
2352                     // the first clicked row can be on a row above or below the
2353                     // shift-clicked row
2354                     return (index_of_current_checkbox > index_of_last_click && index > index_of_last_click && index < index_of_current_checkbox) 
2355                      || (index_of_last_click > index_of_current_checkbox && index < index_of_last_click && index > index_of_current_checkbox);
2356                 })
2357                 .each(function(index) {
2358                     var $intermediate_checkbox = $(this);
2359                     if ($current_checkbox.is(':checked')) {
2360                         $intermediate_checkbox.attr('checked', true);
2361                     } else {
2362                         $intermediate_checkbox.attr('checked', false);
2363                     }
2364                 });
2365         }
2367         $('.multi_checkbox').removeClass('last_clicked');
2368         $current_checkbox.addClass('last_clicked');
2369         
2370         // When there is a checkbox on both ends of the row, propagate the 
2371         // click on one of them to the other one.
2372         // (the default action has not been prevented so if we have
2373         // just clicked, this "if" is true)
2374         if ($current_checkbox.is(':checked')) {
2375             $other_checkbox.attr('checked', true);
2376         } else {
2377             $other_checkbox.attr('checked', false);
2378         }
2379     });
2380 }) // end of $(document).ready() for multi checkbox
2383  * Get the row number from the classlist (for example, row_1)
2384  */
2385 function PMA_getRowNumber(classlist) {
2386     return parseInt(classlist.split(/row_/)[1]);
2390  * Vertical pointer
2391  */
2392 $(document).ready(function() {
2393     $('.vpointer').live('hover',
2394         //handlerInOut
2395         function(e) {
2396         var $this_td = $(this);
2397         var row_num = PMA_getRowNumber($this_td.attr('class'));
2398         // for all td of the same vertical row, toggle hover
2399         $('.vpointer').filter('.row_' + row_num).toggleClass('hover'); 
2400         }
2401         );
2402 }) // end of $(document).ready() for vertical pointer
2404 $(document).ready(function() {
2405     /**
2406      * Vertical marker 
2407      */
2408     $('.vmarker').live('click', function(e) {
2409         var $this_td = $(this);
2410         var row_num = PMA_getRowNumber($this_td.attr('class'));
2411         // for all td of the same vertical row, toggle the marked class 
2412         $('.vmarker').filter('.row_' + row_num).toggleClass('marked'); 
2413         });
2415     /**
2416      * Reveal visual builder anchor
2417      */
2419     $('#visual_builder_anchor').show();
2421     /**
2422      * Page selector in db Structure (non-AJAX)
2423      */
2424     $('#tableslistcontainer').find('#pageselector').live('change', function() {
2425         $(this).parent("form").submit();
2426     });
2428     /**
2429      * Page selector in navi panel (non-AJAX)
2430      */
2431     $('#navidbpageselector').find('#pageselector').live('change', function() {
2432         $(this).parent("form").submit();
2433     });
2435     /**
2436      * Page selector in browse_foreigners windows (non-AJAX)
2437      */
2438     $('#body_browse_foreigners').find('#pageselector').live('change', function() {
2439         $(this).closest("form").submit();
2440     });
2442 }) // end of $(document).ready()