Conditional Ajax for other db operations
[phpmyadmin/crack.git] / js / functions.js
bloba13758ef9e780caf7d23f9fc822d5f6d0e91b814
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         PMA_ajaxShowMessage();
1683         if (! $form.find('input:hidden').is('#ajax_request_hidden')) {
1684             $form.append('<input type="hidden" id="ajax_request_hidden" name="ajax_request" value="true" />');
1685         }
1687         $.get($form.attr('action'), $form.serialize(), function(data) {
1688             $('<div id="create_table_dialog"></div>')
1689             .append(data)
1690             .dialog({
1691                 title: PMA_messages['strCreateTable'],
1692                 height: 600,
1693                 width: 900,
1694                 open: PMA_verifyTypeOfAllColumns, 
1695                 buttons : button_options
1696             }); // end dialog options
1697         }) // end $.get()
1699         // empty table name and number of columns from the minimal form 
1700         $form.find('input[name=table],input[name=num_fields]').val('');
1701     });
1703     /**
1704      * Attach event handler for submission of create table form (save)
1705      *
1706      * @uses    PMA_ajaxShowMessage()
1707      * @uses    $.PMA_sort_table()
1708      *
1709      */
1710     // .live() must be called after a selector, see http://api.jquery.com/live
1711     $("#create_table_form.ajax input[name=do_save_data]").live('click', function(event) {
1712         event.preventDefault();
1714         /**
1715          *  @var    the_form    object referring to the create table form
1716          */
1717         var $form = $("#create_table_form");
1719         PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
1720         if (! $form.find('input:hidden').is('#ajax_request_hidden')) {
1721             $form.append('<input type="hidden" id="ajax_request_hidden" name="ajax_request" value="true" />');
1722         }
1723         //User wants to submit the form
1724         $.post($form.attr('action'), $form.serialize() + "&do_save_data=" + $(this).val(), function(data) {
1725             if(data.success == true) {
1726                 PMA_ajaxShowMessage(data.message);
1727                 $("#create_table_dialog").dialog("close").remove();
1729                 /**
1730                  * @var tables_table    Object referring to the <tbody> element that holds the list of tables
1731                  */
1732                 var tables_table = $("#tablesForm").find("tbody").not("#tbl_summary_row");
1733                 // this is the first table created in this db
1734                 if (tables_table.length == 0) {
1735                     if (window.parent && window.parent.frame_content) {
1736                         window.parent.frame_content.location.reload();
1737                     }
1738                 } else {
1739                     /**
1740                      * @var curr_last_row   Object referring to the last <tr> element in {@link tables_table}
1741                      */
1742                     var curr_last_row = $(tables_table).find('tr:last');
1743                     /**
1744                      * @var curr_last_row_index_string   String containing the index of {@link curr_last_row}
1745                      */
1746                     var curr_last_row_index_string = $(curr_last_row).find('input:checkbox').attr('id').match(/\d+/)[0];
1747                     /**
1748                      * @var curr_last_row_index Index of {@link curr_last_row}
1749                      */
1750                     var curr_last_row_index = parseFloat(curr_last_row_index_string);
1751                     /**
1752                      * @var new_last_row_index   Index of the new row to be appended to {@link tables_table}
1753                      */
1754                     var new_last_row_index = curr_last_row_index + 1;
1755                     /**
1756                      * @var new_last_row_id String containing the id of the row to be appended to {@link tables_table}
1757                      */
1758                     var new_last_row_id = 'checkbox_tbl_' + new_last_row_index;
1760                     //append to table
1761                     $(data.new_table_string)
1762                      .find('input:checkbox')
1763                      .val(new_last_row_id)
1764                      .end()
1765                      .appendTo(tables_table);
1767                     //Sort the table
1768                     $(tables_table).PMA_sort_table('th');
1769                 }
1771                 //Refresh navigation frame as a new table has been added
1772                 if (window.parent && window.parent.frame_navigation) {
1773                     window.parent.frame_navigation.location.reload();
1774                 }
1775             }
1776             else {
1777                 PMA_ajaxShowMessage(data.error);
1778             }
1779         }) // end $.post()
1780     }) // end create table form (save) 
1782     /**
1783      * Attach event handler for create table form (add fields)
1784      *
1785      * @uses    PMA_ajaxShowMessage()
1786      * @uses    $.PMA_sort_table()
1787      * @uses    window.parent.refreshNavigation()
1788      *
1789      */
1790     // .live() must be called after a selector, see http://api.jquery.com/live
1791     $("#create_table_form.ajax input[name=submit_num_fields]").live('click', function(event) {
1792         event.preventDefault();
1794         /**
1795          *  @var    the_form    object referring to the create table form
1796          */
1797         var $form = $("#create_table_form");
1799         PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
1800         if (! $form.find('input:hidden').is('#ajax_request_hidden')) {
1801             $form.append('<input type="hidden" id="ajax_request_hidden" name="ajax_request" value="true" />');
1802         }
1804         //User wants to add more fields to the table
1805         $.post($form.attr('action'), $form.serialize() + "&submit_num_fields=" + $(this).val(), function(data) {
1806             $("#create_table_dialog").html(data);
1807         }) //end $.post()
1809     }) // end create table form (add fields) 
1811 }, 'top.frame_content'); //end $(document).ready for 'Create Table'
1814  * Attach event handlers for Empty Table and Drop Table.  Used wherever libraries/
1815  * tbl_links.inc.php is used.
1816  */
1817 $(document).ready(function() {
1819     /**
1820      * Attach Ajax event handlers for Empty Table
1821      *
1822      * @uses    PMA_ajaxShowMessage()
1823      * @uses    $.PMA_confirm()
1824      */
1825     $("#empty_table_anchor").live('click', function(event) {
1826         event.preventDefault();
1828         /**
1829          * @var question    String containing the question to be asked for confirmation
1830          */
1831         var question = 'TRUNCATE TABLE ' + window.parent.table;
1833         $(this).PMA_confirm(question, $(this).attr('href'), function(url) {
1835             PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
1836             $.get(url, {'is_js_confirmed': 1, 'ajax_request': true}, function(data) {
1837                 if(data.success == true) {
1838                     PMA_ajaxShowMessage(data.message);
1839                     $("#topmenucontainer")
1840                     .next('div')
1841                     .remove()
1842                     .end()
1843                     .after(data.sql_query);
1844                 }
1845                 else {
1846                     PMA_ajaxShowMessage(data.error);
1847                 }
1848             }) // end $.get
1849         }) // end $.PMA_confirm()
1850     }) // end Empty Table
1852     /**
1853      * Attach Ajax event handler for Drop Table
1854      *
1855      * @uses    PMA_ajaxShowMessage()
1856      * @uses    $.PMA_confirm()
1857      * @uses    window.parent.refreshNavigation()
1858      */
1859     $("#drop_table_anchor").live('click', function(event) {
1860         event.preventDefault();
1862         /**
1863          * @var question    String containing the question to be asked for confirmation
1864          */
1865         var question = 'DROP TABLE/VIEW ' + window.parent.table;
1866         $(this).PMA_confirm(question, $(this).attr('href'), function(url) {
1868             PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
1869             $.get(url, {'is_js_confirmed': 1, 'ajax_request': true}, function(data) {
1870                 if(data.success == true) {
1871                     PMA_ajaxShowMessage(data.message);
1872                     $("#topmenucontainer")
1873                     .next('div')
1874                     .remove()
1875                     .end()
1876                     .after(data.sql_query);
1877                     window.parent.table = '';
1878                     if (window.parent && window.parent.frame_navigation) {
1879                         window.parent.frame_navigation.location.reload();
1880                     }
1881                 }
1882                 else {
1883                     PMA_ajaxShowMessage(data.error);
1884                 }
1885             }) // end $.get
1886         }) // end $.PMA_confirm()
1887     }) // end $().live()
1888 }, 'top.frame_content'); //end $(document).ready() for libraries/tbl_links.inc.php
1891  * Attach Ajax event handlers for Drop Trigger.  Used on tbl_structure.php
1892  */
1893 $(document).ready(function() {
1895     $(".drop_trigger_anchor").live('click', function(event) {
1896         event.preventDefault();
1898         /**
1899          * @var curr_row    Object reference to the current trigger's <tr>
1900          */
1901         var curr_row = $(this).parents('tr');
1902         /**
1903          * @var question    String containing the question to be asked for confirmation
1904          */
1905         var question = 'DROP TRIGGER IF EXISTS `' + $(curr_row).children('td:first').text() + '`';
1907         $(this).PMA_confirm(question, $(this).attr('href'), function(url) {
1909             PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
1910             $.get(url, {'is_js_confirmed': 1, 'ajax_request': true}, function(data) {
1911                 if(data.success == true) {
1912                     PMA_ajaxShowMessage(data.message);
1913                     $("#topmenucontainer")
1914                     .next('div')
1915                     .remove()
1916                     .end()
1917                     .after(data.sql_query);
1918                     $(curr_row).hide("medium").remove();
1919                 }
1920                 else {
1921                     PMA_ajaxShowMessage(data.error);
1922                 }
1923             }) // end $.get()
1924         }) // end $.PMA_confirm()
1925     }) // end $().live()
1926 }, 'top.frame_content'); //end $(document).ready() for Drop Trigger
1929  * Attach Ajax event handlers for Drop Database. Moved here from db_structure.js
1930  * as it was also required on db_create.php
1932  * @uses    $.PMA_confirm()
1933  * @uses    PMA_ajaxShowMessage()
1934  * @uses    window.parent.refreshNavigation()
1935  * @uses    window.parent.refreshMain()
1936  */
1937 $(document).ready(function() {
1938     $("#drop_db_anchor").live('click', function(event) {
1939         event.preventDefault();
1941         //context is top.frame_content, so we need to use window.parent.db to access the db var
1942         /**
1943          * @var question    String containing the question to be asked for confirmation
1944          */
1945         var question = PMA_messages['strDropDatabaseStrongWarning'] + '\n' + PMA_messages['strDoYouReally'] + ' :\n' + 'DROP DATABASE ' + window.parent.db;
1947         $(this).PMA_confirm(question, $(this).attr('href') ,function(url) {
1949             PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
1950             $.get(url, {'is_js_confirmed': '1', 'ajax_request': true}, function(data) {
1951                 //Database deleted successfully, refresh both the frames
1952                 window.parent.refreshNavigation();
1953                 window.parent.refreshMain();
1954             }) // end $.get()
1955         }); // end $.PMA_confirm()
1956     }); //end of Drop Database Ajax action
1957 }) // end of $(document).ready() for Drop Database
1960  * Attach Ajax event handlers for 'Create Database'.  Used wherever libraries/
1961  * display_create_database.lib.php is used, ie main.php and server_databases.php
1963  * @uses    PMA_ajaxShowMessage()
1964  */
1965 $(document).ready(function() {
1967     $('#create_database_form').live('submit', function(event) {
1968         event.preventDefault();
1970         $form = $(this);
1972         PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
1974         if (! $form.find('input:hidden').is('#ajax_request_hidden')) {
1975             $form.append('<input type="hidden" id="ajax_request_hidden" name="ajax_request" value="true" />');
1976         }
1978         $.post($form.attr('action'), $form.serialize(), function(data) {
1979             if(data.success == true) {
1980                 PMA_ajaxShowMessage(data.message);
1982                 //Append database's row to table
1983                 $("#tabledatabases")
1984                 .find('tbody')
1985                 .append(data.new_db_string)
1986                 .PMA_sort_table('.name')
1987                 .find('#db_summary_row')
1988                 .appendTo('#tabledatabases tbody')
1989                 .removeClass('odd even');
1991                 var $databases_count_object = $('#databases_count');
1992                 var databases_count = parseInt($databases_count_object.text()); 
1993                 $databases_count_object.text(++databases_count);
1994                 //Refresh navigation frame as a new database has been added
1995                 if (window.parent && window.parent.frame_navigation) {
1996                     window.parent.frame_navigation.location.reload();
1997                 }
1998             }
1999             else {
2000                 PMA_ajaxShowMessage(data.error);
2001             }
2002         }) // end $.post()
2003     }) // end $().live()
2004 })  // end $(document).ready() for Create Database
2007  * Attach Ajax event handlers for 'Change Password' on main.php
2008  */
2009 $(document).ready(function() {
2011     /**
2012      * Attach Ajax event handler on the change password anchor
2013      */
2014     $('#change_password_anchor').live('click', function(event) {
2015         event.preventDefault();
2017         /**
2018          * @var button_options  Object containing options to be passed to jQueryUI's dialog
2019          */
2020         var button_options = {};
2022         button_options[PMA_messages['strCancel']] = function() {$(this).dialog('close').remove();}
2024         $.get($(this).attr('href'), {'ajax_request': true}, function(data) {
2025             $('<div id="change_password_dialog"></div>')
2026             .dialog({
2027                 title: PMA_messages['strChangePassword'],
2028                 width: 600,
2029                 buttons : button_options
2030             })
2031             .append(data);
2032             displayPasswordGenerateButton();
2033         }) // end $.get()
2034     }) // end handler for change password anchor
2036     /**
2037      * Attach Ajax event handler for Change Password form submission
2038      *
2039      * @uses    PMA_ajaxShowMessage()
2040      */
2041     $("#change_password_form").find('input[name=change_pw]').live('click', function(event) {
2042         event.preventDefault();
2044         /**
2045          * @var the_form    Object referring to the change password form
2046          */
2047         var the_form = $("#change_password_form");
2049         /**
2050          * @var this_value  String containing the value of the submit button.
2051          * Need to append this for the change password form on Server Privileges
2052          * page to work
2053          */
2054         var this_value = $(this).val();
2056         PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
2057         $(the_form).append('<input type="hidden" name="ajax_request" value="true" />');
2059         $.post($(the_form).attr('action'), $(the_form).serialize() + '&change_pw='+ this_value, function(data) {
2060             if(data.success == true) {
2062                 PMA_ajaxShowMessage(data.message);
2064                 $("#topmenucontainer").after(data.sql_query);
2066                 $("#change_password_dialog").hide().remove();
2067                 $("#edit_user_dialog").dialog("close").remove();
2068             }
2069             else {
2070                 PMA_ajaxShowMessage(data.error);
2071             }
2072         }) // end $.post()
2073     }) // end handler for Change Password form submission
2074 }) // end $(document).ready() for Change Password
2077  * Toggle the hiding/showing of the "Open in ENUM/SET editor" message when
2078  * the page loads and when the selected data type changes
2079  */
2080 $(document).ready(function() {
2081     // is called here for normal page loads and also when opening
2082     // the Create table dialog
2083     PMA_verifyTypeOfAllColumns();
2084     //
2085     // needs live() to work also in the Create Table dialog
2086     $("select[class='column_type']").live('change', function() {
2087         toggle_enum_notice($(this));
2088     });
2091 function PMA_verifyTypeOfAllColumns() {
2092     $("select[class='column_type']").each(function() {
2093         toggle_enum_notice($(this));
2094     });
2098  * Closes the ENUM/SET editor and removes the data in it
2099  */
2100 function disable_popup() {
2101     $("#popup_background").fadeOut("fast");
2102     $("#enum_editor").fadeOut("fast");
2103     // clear the data from the text boxes
2104     $("#enum_editor #values input").remove();
2105     $("#enum_editor input[type='hidden']").remove();
2109  * Opens the ENUM/SET editor and controls its functions
2110  */
2111 $(document).ready(function() {
2112     // Needs live() to work also in the Create table dialog
2113     $("a[class='open_enum_editor']").live('click', function() {
2114         // Center the popup
2115         var windowWidth = document.documentElement.clientWidth;
2116         var windowHeight = document.documentElement.clientHeight;
2117         var popupWidth = windowWidth/2;
2118         var popupHeight = windowHeight*0.8;
2119         var popupOffsetTop = windowHeight/2 - popupHeight/2;
2120         var popupOffsetLeft = windowWidth/2 - popupWidth/2;
2121         $("#enum_editor").css({"position":"absolute", "top": popupOffsetTop, "left": popupOffsetLeft, "width": popupWidth, "height": popupHeight});
2123         // Make it appear
2124         $("#popup_background").css({"opacity":"0.7"});
2125         $("#popup_background").fadeIn("fast");
2126         $("#enum_editor").fadeIn("fast");
2128         // Get the values
2129         var values = $(this).parent().prev("input").attr("value").split(",");
2130         $.each(values, function(index, val) {
2131             if(jQuery.trim(val) != "") {
2132                  // enclose the string in single quotes if it's not already
2133                  if(val.substr(0, 1) != "'") {
2134                       val = "'" + val;
2135                  }
2136                  if(val.substr(val.length-1, val.length) != "'") {
2137                       val = val + "'";
2138                  }
2139                 // escape the single quotes, except the mandatory ones enclosing the entire string
2140                 val = val.substr(1, val.length-2).replace(/''/g, "'").replace(/\\\\/g, '\\').replace(/\\'/g, "'").replace(/'/g, "&#039;");
2141                 // escape the greater-than symbol
2142                 val = val.replace(/>/g, "&gt;");
2143                 $("#enum_editor #values").append("<input type='text' value=" + val + " />");
2144             }
2145         });
2146         // So we know which column's data is being edited
2147         $("#enum_editor").append("<input type='hidden' value='" + $(this).parent().prev("input").attr("id") + "' />");
2148         return false;
2149     });
2151     // If the "close" link is clicked, close the enum editor
2152     // Needs live() to work also in the Create table dialog
2153     $("a[class='close_enum_editor']").live('click', function() {
2154         disable_popup();
2155     });
2157     // If the "cancel" link is clicked, close the enum editor
2158     // Needs live() to work also in the Create table dialog
2159     $("a[class='cancel_enum_editor']").live('click', function() {
2160         disable_popup();
2161     });
2163     // When "add a new value" is clicked, append an empty text field
2164     // Needs live() to work also in the Create table dialog
2165     $("a[class='add_value']").live('click', function() {
2166         $("#enum_editor #values").append("<input type='text' />");
2167     });
2169     // When the submit button is clicked, put the data back into the original form
2170     // Needs live() to work also in the Create table dialog
2171     $("#enum_editor input[type='submit']").live('click', function() {
2172         var value_array = new Array();
2173         $.each($("#enum_editor #values input"), function(index, input_element) {
2174             val = jQuery.trim(input_element.value);
2175             if(val != "") {
2176                 value_array.push("'" + val.replace(/\\/g, '\\\\').replace(/'/g, "''") + "'");
2177             }
2178         });
2179         // get the Length/Values text field where this value belongs
2180         var values_id = $("#enum_editor input[type='hidden']").attr("value");
2181         $("input[id='" + values_id + "']").attr("value", value_array.join(","));
2182         disable_popup();
2183      });
2185     /**
2186      * Hides certain table structure actions, replacing them with the word "More". They are displayed
2187      * in a dropdown menu when the user hovers over the word "More."
2188      */
2189     // Remove the actions from the table cells (they are available by default for JavaScript-disabled browsers)
2190     // if the table is not a view or information_schema (otherwise there is only one action to hide and there's no point)
2191     if($("input[type='hidden'][name='table_type']").val() == "table") {
2192             var $table = $("table[id='tablestructure']");
2193         $table.find("td[class='browse']").remove();
2194         $table.find("td[class='primary']").remove();
2195         $table.find("td[class='unique']").remove();
2196         $table.find("td[class='index']").remove();
2197         $table.find("td[class='fulltext']").remove();
2198         $table.find("th[class='action']").attr("colspan", 3);
2200         // Display the "more" text
2201         $table.find("td[class='more_opts']").show();
2203         // Position the dropdown
2204         $(".structure_actions_dropdown").each(function() {
2205             // Optimize DOM querying
2206             var $this_dropdown = $(this);
2207              // The top offset must be set for IE even if it didn't change
2208             var cell_right_edge_offset = $this_dropdown.parent().offset().left + $this_dropdown.parent().innerWidth();
2209             var left_offset = cell_right_edge_offset - $this_dropdown.innerWidth();
2210             var top_offset = $this_dropdown.parent().offset().top + $this_dropdown.parent().innerHeight();
2211             $this_dropdown.offset({ top: top_offset, left: left_offset });
2212         });
2214         // A hack for IE6 to prevent the after_field select element from being displayed on top of the dropdown by
2215         // positioning an iframe directly on top of it
2216         var $after_field = $("select[name='after_field']");
2217             $("iframe[class='IE_hack']")
2218                     .width($after_field.width())
2219             .height($after_field.height())
2220             .offset({
2221                 top: $after_field.offset().top,
2222                 left: $after_field.offset().left
2223             });
2225         // When "more" is hovered over, show the hidden actions
2226         $table.find("td[class='more_opts']")
2227                     .mouseenter(function() {
2228                 if($.browser.msie && $.browser.version == "6.0") {
2229                     $("iframe[class='IE_hack']")
2230                                 .show()
2231                         .width($after_field.width()+4)
2232                         .height($after_field.height()+4)
2233                         .offset({
2234                             top: $after_field.offset().top,
2235                             left: $after_field.offset().left
2236                         });
2237                 }
2238                 $(".structure_actions_dropdown").hide(); // Hide all the other ones that may be open
2239                 $(this).children(".structure_actions_dropdown").show();
2240                 // Need to do this again for IE otherwise the offset is wrong
2241                 if($.browser.msie) {
2242                     var left_offset_IE = $(this).offset().left + $(this).innerWidth() - $(this).children(".structure_actions_dropdown").innerWidth();
2243                     var top_offset_IE = $(this).offset().top + $(this).innerHeight();
2244                     $(this).children(".structure_actions_dropdown").offset({
2245                             top: top_offset_IE,
2246                             left: left_offset_IE });
2247                 }
2248             })
2249             .mouseleave(function() {
2250                 $(this).children(".structure_actions_dropdown").hide();
2251                 if($.browser.msie && $.browser.version == "6.0") {
2252                     $("iframe[class='IE_hack']").hide();
2253                 }
2254             });
2255     }
2258 /* Displays tooltips */
2259 $(document).ready(function() {
2260     // Hide the footnotes from the footer (which are displayed for
2261     // JavaScript-disabled browsers) since the tooltip is sufficient
2262     $(".footnotes").hide();
2263     $(".footnotes span").each(function() {
2264         $(this).children("sup").remove();
2265     });
2266     // The border and padding must be removed otherwise a thin yellow box remains visible
2267     $(".footnotes").css("border", "none");
2268     $(".footnotes").css("padding", "0px");
2270     // Replace the superscripts with the help icon
2271     $("sup[class='footnotemarker']").hide();
2272     $("img[class='footnotemarker']").show();
2274     $("img[class='footnotemarker']").each(function() {
2275         var span_id = $(this).attr("id");
2276         span_id = span_id.split("_")[1];
2277         var tooltip_text = $(".footnotes span[id='footnote_" + span_id + "']").html();
2278         $(this).qtip({
2279             content: tooltip_text,
2280             show: { delay: 0 },
2281             hide: { when: 'unfocus', delay: 0 },
2282             style: { background: '#ffffcc' }
2283         });
2284     });
2287 function menuResize()
2289     var cnt = $('#topmenu');
2290     var wmax = cnt.width() - 5; // 5 px margin for jumping menu in Chrome
2291     var submenu = cnt.find('.submenu');
2292     var submenu_w = submenu.outerWidth(true);
2293     var submenu_ul = submenu.find('ul');
2294     var li = cnt.find('> li');
2295     var li2 = submenu_ul.find('li');
2296     var more_shown = li2.length > 0;
2297     var w = more_shown ? submenu_w : 0;
2299     // hide menu items
2300     var hide_start = 0;
2301     for (var i = 0; i < li.length-1; i++) { // li.length-1: skip .submenu element
2302         var el = $(li[i]);
2303         var el_width = el.outerWidth(true);
2304         el.data('width', el_width);
2305         w += el_width;
2306         if (w > wmax) {
2307             w -= el_width;
2308             if (w + submenu_w < wmax) {
2309                 hide_start = i;
2310             } else {
2311                 hide_start = i-1;
2312                 w -= $(li[i-1]).data('width');
2313             }
2314             break;
2315         }
2316     }
2318     if (hide_start > 0) {
2319         for (var i = hide_start; i < li.length-1; i++) {
2320             $(li[i])[more_shown ? 'prependTo' : 'appendTo'](submenu_ul);
2321         }
2322         submenu.show();
2323     } else if (more_shown) {
2324         w -= submenu_w;
2325         // nothing hidden, maybe something can be restored
2326         for (var i = 0; i < li2.length; i++) {
2327             //console.log(li2[i], submenu_w);
2328             w += $(li2[i]).data('width');
2329             // item fits or (it is the last item and it would fit if More got removed)
2330             if (w+submenu_w < wmax || (i == li2.length-1 && w < wmax)) {
2331                 $(li2[i]).insertBefore(submenu);
2332                 if (i == li2.length-1) {
2333                     submenu.hide();
2334                 }
2335                 continue;
2336             }
2337             break;
2338         }
2339     }
2340     if (submenu.find('.tabactive').length) {
2341         submenu.addClass('active').find('> a').removeClass('tab').addClass('tabactive');
2342     } else {
2343         submenu.removeClass('active').find('> a').addClass('tab').removeClass('tabactive');
2344     }
2347 $(function() {
2348     var topmenu = $('#topmenu');
2349     if (topmenu.length == 0) {
2350         return;
2351     }
2352     // create submenu container
2353     var link = $('<a />', {href: '#', 'class': 'tab'})
2354         .text(PMA_messages['strMore'])
2355         .click(function(e) {
2356             e.preventDefault();
2357         });
2358     var img = topmenu.find('li:first-child img');
2359     if (img.length) {
2360         img.clone().attr('src', img.attr('src').replace(/\/[^\/]+$/, '/b_more.png')).prependTo(link);
2361     }
2362     var submenu = $('<li />', {'class': 'submenu'})
2363         .append(link)
2364         .append($('<ul />'))
2365         .mouseenter(function() {
2366             if ($(this).find('ul .tabactive').length == 0) {
2367                 $(this).addClass('submenuhover').find('> a').addClass('tabactive');
2368             }
2369         })
2370         .mouseleave(function() {
2371             if ($(this).find('ul .tabactive').length == 0) {
2372                 $(this).removeClass('submenuhover').find('> a').removeClass('tabactive');
2373             }
2374         })
2375         .hide();
2376     topmenu.append(submenu);
2378     // populate submenu and register resize event
2379     $(window).resize(menuResize);
2380     menuResize();
2384  * For the checkboxes in browse mode, handles the shift/click (only works
2385  * in horizontal mode) and propagates the click to the "companion" checkbox
2386  * (in both horizontal and vertical). Works also for pages reached via AJAX.
2387  */
2388 $(document).ready(function() {
2389     $('.multi_checkbox').live('click',function(e) {
2390         var current_checkbox_id = this.id;
2391         var left_checkbox_id = current_checkbox_id.replace('_right', '_left');
2392         var right_checkbox_id = current_checkbox_id.replace('_left', '_right');
2393         var other_checkbox_id = '';
2394         if (current_checkbox_id == left_checkbox_id) {
2395             other_checkbox_id = right_checkbox_id; 
2396         } else {
2397             other_checkbox_id = left_checkbox_id;
2398         }
2400         var $current_checkbox = $('#' + current_checkbox_id);
2401         var $other_checkbox = $('#' + other_checkbox_id);
2403         if (e.shiftKey) {
2404             var index_of_current_checkbox = $('.multi_checkbox').index($current_checkbox);
2405             var $last_checkbox = $('.multi_checkbox').filter('.last_clicked');
2406             var index_of_last_click = $('.multi_checkbox').index($last_checkbox);
2407             $('.multi_checkbox')
2408                 .filter(function(index) {
2409                     // the first clicked row can be on a row above or below the
2410                     // shift-clicked row
2411                     return (index_of_current_checkbox > index_of_last_click && index > index_of_last_click && index < index_of_current_checkbox) 
2412                      || (index_of_last_click > index_of_current_checkbox && index < index_of_last_click && index > index_of_current_checkbox);
2413                 })
2414                 .each(function(index) {
2415                     var $intermediate_checkbox = $(this);
2416                     if ($current_checkbox.is(':checked')) {
2417                         $intermediate_checkbox.attr('checked', true);
2418                     } else {
2419                         $intermediate_checkbox.attr('checked', false);
2420                     }
2421                 });
2422         }
2424         $('.multi_checkbox').removeClass('last_clicked');
2425         $current_checkbox.addClass('last_clicked');
2426         
2427         // When there is a checkbox on both ends of the row, propagate the 
2428         // click on one of them to the other one.
2429         // (the default action has not been prevented so if we have
2430         // just clicked, this "if" is true)
2431         if ($current_checkbox.is(':checked')) {
2432             $other_checkbox.attr('checked', true);
2433         } else {
2434             $other_checkbox.attr('checked', false);
2435         }
2436     });
2437 }) // end of $(document).ready() for multi checkbox
2440  * Get the row number from the classlist (for example, row_1)
2441  */
2442 function PMA_getRowNumber(classlist) {
2443     return parseInt(classlist.split(/row_/)[1]);
2447  * Vertical pointer
2448  */
2449 $(document).ready(function() {
2450     $('.vpointer').live('hover',
2451         //handlerInOut
2452         function(e) {
2453         var $this_td = $(this);
2454         var row_num = PMA_getRowNumber($this_td.attr('class'));
2455         // for all td of the same vertical row, toggle hover
2456         $('.vpointer').filter('.row_' + row_num).toggleClass('hover'); 
2457         }
2458         );
2459 }) // end of $(document).ready() for vertical pointer
2461 $(document).ready(function() {
2462     /**
2463      * Vertical marker 
2464      */
2465     $('.vmarker').live('click', function(e) {
2466         var $this_td = $(this);
2467         var row_num = PMA_getRowNumber($this_td.attr('class'));
2468         // for all td of the same vertical row, toggle the marked class 
2469         $('.vmarker').filter('.row_' + row_num).toggleClass('marked'); 
2470         });
2472     /**
2473      * Reveal visual builder anchor
2474      */
2476     $('#visual_builder_anchor').show();
2478     /**
2479      * Page selector in db Structure (non-AJAX)
2480      */
2481     $('#tableslistcontainer').find('#pageselector').live('change', function() {
2482         $(this).parent("form").submit();
2483     });
2485     /**
2486      * Page selector in navi panel (non-AJAX)
2487      */
2488     $('#navidbpageselector').find('#pageselector').live('change', function() {
2489         $(this).parent("form").submit();
2490     });
2492     /**
2493      * Page selector in browse_foreigners windows (non-AJAX)
2494      */
2495     $('#body_browse_foreigners').find('#pageselector').live('change', function() {
2496         $(this).closest("form").submit();
2497     });
2499 }) // end of $(document).ready()