Should use only inner width here
[phpmyadmin-themes.git] / js / functions.js
blobad51fd0b733fc674d1bf423b3155096be1ed72ca
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  * Version string to integer conversion.
49  */
50 function parseVersionString (str) {
51     if (typeof(str) != 'string') { return false; }
52     var add = 0;
53     // Parse possible alpha/beta/rc/
54     var state = str.split('-');
55     if (state.length >= 2) {
56         if (state[1].substr(0, 2) == 'rc') {
57             add = - 20 - parseInt(state[1].substr(2));
58         } else if (state[1].substr(0, 4) == 'beta') {
59             add =  - 40 - parseInt(state[1].substr(4));
60         } else if (state[1].substr(0, 5) == 'alpha') {
61             add =  - 60 - parseInt(state[1].substr(5));
62         } else if (state[1].substr(0, 3) == 'dev') {
63             /* We don't handle dev, it's git snapshot */
64             add = 0;
65         }
66     }
67     // Parse version
68     var x = str.split('.');
69     // Use 0 for non existing parts
70     var maj = parseInt(x[0]) || 0;
71     var min = parseInt(x[1]) || 0;
72     var pat = parseInt(x[2]) || 0;
73     var hotfix = parseInt(x[3]) || 0;
74     return  maj * 100000000 + min * 1000000 + pat * 10000 + hotfix * 100 + add;
77 /**
78  * Indicates current available version on main page.
79  */
80 function PMA_current_version() {
81     var current = parseVersionString('3.4.0'/*pmaversion*/);
82     var latest = parseVersionString(PMA_latest_version);
83     $('#li_pma_version').append(PMA_messages['strLatestAvailable'] + ' ' + PMA_latest_version);
84     if (latest > current) {
85         var message = $.sprintf(PMA_messages['strNewerVersion'], PMA_latest_version, PMA_latest_date);
86         if (Math.floor(latest / 10000) == Math.floor(current / 10000)) {
87             /* Security update */
88             klass = 'warning';
89         } else {
90             klass = 'notice';
91         }
92         $('#maincontainer').after('<div class="' + klass + '">' + message + '</div>');
93     }
96 /**
97  * for libraries/display_change_password.lib.php
98  *     libraries/user_password.php
99  *
100  */
102 function displayPasswordGenerateButton() {
103     $('#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>');
104     $('#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>');
108  * Adds a date/time picker to an element
110  * @param   object  $this_element   a jQuery object pointing to the element
111  */
112 function PMA_addDatepicker($this_element) {
113     var showTimeOption = false;
114     if ($this_element.is('.datetimefield')) {
115         showTimeOption = true;
116     }
118     $this_element
119         .datepicker({
120         showOn: 'button',
121         buttonImage: themeCalendarImage, // defined in js/messages.php
122         buttonImageOnly: true,
123         duration: '',
124         time24h: true,
125         stepMinutes: 1,
126         stepHours: 1,
127         showTime: showTimeOption,
128         dateFormat: 'yy-mm-dd', // yy means year with four digits
129         altTimeField: '',
130         beforeShow: function(input, inst) {
131             // Remember that we came from the datepicker; this is used
132             // in tbl_change.js by verificationsAfterFieldChange()
133             $this_element.data('comes_from', 'datepicker');
134         },
135         constrainInput: false
136      });
140  * selects the content of a given object, f.e. a textarea
142  * @param   object  element     element of which the content will be selected
143  * @param   var     lock        variable which holds the lock for this element
144  *                              or true, if no lock exists
145  * @param   boolean only_once   if true this is only done once
146  *                              f.e. only on first focus
147  */
148 function selectContent( element, lock, only_once ) {
149     if ( only_once && only_once_elements[element.name] ) {
150         return;
151     }
153     only_once_elements[element.name] = true;
155     if ( lock  ) {
156         return;
157     }
159     element.select();
163  * Displays a confirmation box before to submit a "DROP/DELETE/ALTER" query.
164  * This function is called while clicking links
166  * @param   object   the link
167  * @param   object   the sql query to submit
169  * @return  boolean  whether to run the query or not
170  */
171 function confirmLink(theLink, theSqlQuery)
173     // Confirmation is not required in the configuration file
174     // or browser is Opera (crappy js implementation)
175     if (PMA_messages['strDoYouReally'] == '' || typeof(window.opera) != 'undefined') {
176         return true;
177     }
179     var is_confirmed = confirm(PMA_messages['strDoYouReally'] + ' :\n' + theSqlQuery);
180     if (is_confirmed) {
181         if ( typeof(theLink.href) != 'undefined' ) {
182             theLink.href += '&is_js_confirmed=1';
183         } else if ( typeof(theLink.form) != 'undefined' ) {
184             theLink.form.action += '?is_js_confirmed=1';
185         }
186     }
188     return is_confirmed;
189 } // end of the 'confirmLink()' function
193  * Displays a confirmation box before doing some action
195  * @param   object   the message to display
197  * @return  boolean  whether to run the query or not
199  * @todo used only by libraries/display_tbl.lib.php. figure out how it is used
200  *       and replace with a jQuery equivalent
201  */
202 function confirmAction(theMessage)
204     // TODO: Confirmation is not required in the configuration file
205     // or browser is Opera (crappy js implementation)
206     if (typeof(window.opera) != 'undefined') {
207         return true;
208     }
210     var is_confirmed = confirm(theMessage);
212     return is_confirmed;
213 } // end of the 'confirmAction()' function
217  * Displays an error message if a "DROP DATABASE" statement is submitted
218  * while it isn't allowed, else confirms a "DROP/DELETE/ALTER" query before
219  * sumitting it if required.
220  * This function is called by the 'checkSqlQuery()' js function.
222  * @param   object   the form
223  * @param   object   the sql query textarea
225  * @return  boolean  whether to run the query or not
227  * @see     checkSqlQuery()
228  */
229 function confirmQuery(theForm1, sqlQuery1)
231     // Confirmation is not required in the configuration file
232     if (PMA_messages['strDoYouReally'] == '') {
233         return true;
234     }
236     // The replace function (js1.2) isn't supported
237     else if (typeof(sqlQuery1.value.replace) == 'undefined') {
238         return true;
239     }
241     // js1.2+ -> validation with regular expressions
242     else {
243         // "DROP DATABASE" statement isn't allowed
244         if (PMA_messages['strNoDropDatabases'] != '') {
245             var drop_re = new RegExp('(^|;)\\s*DROP\\s+(IF EXISTS\\s+)?DATABASE\\s', 'i');
246             if (drop_re.test(sqlQuery1.value)) {
247                 alert(PMA_messages['strNoDropDatabases']);
248                 theForm1.reset();
249                 sqlQuery1.focus();
250                 return false;
251             } // end if
252         } // end if
254         // Confirms a "DROP/DELETE/ALTER/TRUNCATE" statement
255         //
256         // TODO: find a way (if possible) to use the parser-analyser
257         // for this kind of verification
258         // For now, I just added a ^ to check for the statement at
259         // beginning of expression
261         var do_confirm_re_0 = new RegExp('^\\s*DROP\\s+(IF EXISTS\\s+)?(TABLE|DATABASE|PROCEDURE)\\s', 'i');
262         var do_confirm_re_1 = new RegExp('^\\s*ALTER\\s+TABLE\\s+((`[^`]+`)|([A-Za-z0-9_$]+))\\s+DROP\\s', 'i');
263         var do_confirm_re_2 = new RegExp('^\\s*DELETE\\s+FROM\\s', 'i');
264         var do_confirm_re_3 = new RegExp('^\\s*TRUNCATE\\s', 'i');
266         if (do_confirm_re_0.test(sqlQuery1.value)
267             || do_confirm_re_1.test(sqlQuery1.value)
268             || do_confirm_re_2.test(sqlQuery1.value)
269             || do_confirm_re_3.test(sqlQuery1.value)) {
270             var message      = (sqlQuery1.value.length > 100)
271                              ? sqlQuery1.value.substr(0, 100) + '\n    ...'
272                              : sqlQuery1.value;
273             var is_confirmed = confirm(PMA_messages['strDoYouReally'] + ' :\n' + message);
274             // statement is confirmed -> update the
275             // "is_js_confirmed" form field so the confirm test won't be
276             // run on the server side and allows to submit the form
277             if (is_confirmed) {
278                 theForm1.elements['is_js_confirmed'].value = 1;
279                 return true;
280             }
281             // statement is rejected -> do not submit the form
282             else {
283                 window.focus();
284                 sqlQuery1.focus();
285                 return false;
286             } // end if (handle confirm box result)
287         } // end if (display confirm box)
288     } // end confirmation stuff
290     return true;
291 } // end of the 'confirmQuery()' function
295  * Displays a confirmation box before disabling the BLOB repository for a given database.
296  * This function is called while clicking links
298  * @param   object   the database
300  * @return  boolean  whether to disable the repository or not
301  */
302 function confirmDisableRepository(theDB)
304     // Confirmation is not required in the configuration file
305     // or browser is Opera (crappy js implementation)
306     if (PMA_messages['strDoYouReally'] == '' || typeof(window.opera) != 'undefined') {
307         return true;
308     }
310     var is_confirmed = confirm(PMA_messages['strBLOBRepositoryDisableStrongWarning'] + '\n' + PMA_messages['strBLOBRepositoryDisableAreYouSure']);
312     return is_confirmed;
313 } // end of the 'confirmDisableBLOBRepository()' function
317  * Displays an error message if the user submitted the sql query form with no
318  * sql query, else checks for "DROP/DELETE/ALTER" statements
320  * @param   object   the form
322  * @return  boolean  always false
324  * @see     confirmQuery()
325  */
326 function checkSqlQuery(theForm)
328     var sqlQuery = theForm.elements['sql_query'];
329     var isEmpty  = 1;
331     // The replace function (js1.2) isn't supported -> basic tests
332     if (typeof(sqlQuery.value.replace) == 'undefined') {
333         isEmpty      = (sqlQuery.value == '') ? 1 : 0;
334         if (isEmpty && typeof(theForm.elements['sql_file']) != 'undefined') {
335             isEmpty  = (theForm.elements['sql_file'].value == '') ? 1 : 0;
336         }
337         if (isEmpty && typeof(theForm.elements['sql_localfile']) != 'undefined') {
338             isEmpty  = (theForm.elements['sql_localfile'].value == '') ? 1 : 0;
339         }
340         if (isEmpty && typeof(theForm.elements['id_bookmark']) != 'undefined') {
341             isEmpty  = (theForm.elements['id_bookmark'].value == null || theForm.elements['id_bookmark'].value == '');
342         }
343     }
344     // js1.2+ -> validation with regular expressions
345     else {
346         var space_re = new RegExp('\\s+');
347         if (typeof(theForm.elements['sql_file']) != 'undefined' &&
348                 theForm.elements['sql_file'].value.replace(space_re, '') != '') {
349             return true;
350         }
351         if (typeof(theForm.elements['sql_localfile']) != 'undefined' &&
352                 theForm.elements['sql_localfile'].value.replace(space_re, '') != '') {
353             return true;
354         }
355         if (isEmpty && typeof(theForm.elements['id_bookmark']) != 'undefined' &&
356                 (theForm.elements['id_bookmark'].value != null || theForm.elements['id_bookmark'].value != '') &&
357                 theForm.elements['id_bookmark'].selectedIndex != 0
358                 ) {
359             return true;
360         }
361         // Checks for "DROP/DELETE/ALTER" statements
362         if (sqlQuery.value.replace(space_re, '') != '') {
363             if (confirmQuery(theForm, sqlQuery)) {
364                 return true;
365             } else {
366                 return false;
367             }
368         }
369         theForm.reset();
370         isEmpty = 1;
371     }
373     if (isEmpty) {
374         sqlQuery.select();
375         alert(PMA_messages['strFormEmpty']);
376         sqlQuery.focus();
377         return false;
378     }
380     return true;
381 } // end of the 'checkSqlQuery()' function
383 // Global variable row_class is set to even
384 var row_class = 'even';
387 * Generates a row dynamically in the differences table displaying
388 * the complete statistics of difference in  table like number of
389 * rows to be updated, number of rows to be inserted, number of
390 * columns to be added, number of columns to be removed, etc.
392 * @param  index         index of matching table
393 * @param  update_size   number of rows/column to be updated
394 * @param  insert_size   number of rows/coulmns to be inserted
395 * @param  remove_size   number of columns to be removed
396 * @param  insert_index  number of indexes to be inserted
397 * @param  remove_index  number of indexes to be removed
398 * @param  img_obj       image object
399 * @param  table_name    name of the table
402 function showDetails(i, update_size, insert_size, remove_size, insert_index, remove_index, img_obj, table_name)
404     // The path of the image is split to facilitate comparison
405     var relative_path = (img_obj.src).split("themes/");
407     // The image source is changed when the showDetails function is called.
408     if (relative_path[1] == 'original/img/new_data_hovered.jpg') {
409         img_obj.src = "./themes/original/img/new_data_selected_hovered.jpg";
410         img_obj.alt = PMA_messages['strClickToUnselect'];  //only for IE browser
411     } else if (relative_path[1] == 'original/img/new_struct_hovered.jpg') {
412         img_obj.src = "./themes/original/img/new_struct_selected_hovered.jpg";
413         img_obj.alt = PMA_messages['strClickToUnselect'];
414     } else if (relative_path[1] == 'original/img/new_struct_selected_hovered.jpg') {
415         img_obj.src = "./themes/original/img/new_struct_hovered.jpg";
416         img_obj.alt = PMA_messages['strClickToSelect'];
417     } else if (relative_path[1] == 'original/img/new_data_selected_hovered.jpg') {
418         img_obj.src = "./themes/original/img/new_data_hovered.jpg";
419         img_obj.alt = PMA_messages['strClickToSelect'];
420     }
422     var div = document.getElementById("list");
423     var table = div.getElementsByTagName("table")[0];
424     var table_body = table.getElementsByTagName("tbody")[0];
426     //Global variable row_class is being used
427     if (row_class == 'even') {
428         row_class = 'odd';
429     } else {
430         row_class = 'even';
431     }
432     // 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.
433     if ((relative_path[1] != 'original/img/new_struct_selected_hovered.jpg') && (relative_path[1] != 'original/img/new_data_selected_hovered.jpg')) {
435         var newRow = document.createElement("tr");
436         newRow.setAttribute("class", row_class);
437         newRow.className = row_class;
438         // Id assigned to this row element is same as the index of this table name in the  matching_tables/source_tables_uncommon array
439         newRow.setAttribute("id" , i);
441         var table_name_cell = document.createElement("td");
442         table_name_cell.align = "center";
443         table_name_cell.innerHTML = table_name ;
445         newRow.appendChild(table_name_cell);
447         var create_table = document.createElement("td");
448         create_table.align = "center";
450         var add_cols = document.createElement("td");
451         add_cols.align = "center";
453         var remove_cols = document.createElement("td");
454         remove_cols.align = "center";
456         var alter_cols = document.createElement("td");
457         alter_cols.align = "center";
459         var add_index = document.createElement("td");
460         add_index.align = "center";
462         var delete_index = document.createElement("td");
463         delete_index.align = "center";
465         var update_rows = document.createElement("td");
466         update_rows.align = "center";
468         var insert_rows = document.createElement("td");
469         insert_rows.align = "center";
471         var tick_image = document.createElement("img");
472         tick_image.src = "./themes/original/img/s_success.png";
474         if (update_size == '' && insert_size == '' && remove_size == '') {
475           /**
476           This is the case when the table needs to be created in target database.
477           */
478             create_table.appendChild(tick_image);
479             add_cols.innerHTML = "--";
480             remove_cols.innerHTML = "--";
481             alter_cols.innerHTML = "--";
482             delete_index.innerHTML = "--";
483             add_index.innerHTML = "--";
484             update_rows.innerHTML = "--";
485             insert_rows.innerHTML = "--";
487             newRow.appendChild(create_table);
488             newRow.appendChild(add_cols);
489             newRow.appendChild(remove_cols);
490             newRow.appendChild(alter_cols);
491             newRow.appendChild(delete_index);
492             newRow.appendChild(add_index);
493             newRow.appendChild(update_rows);
494             newRow.appendChild(insert_rows);
496         } else if (update_size == '' && remove_size == '') {
497            /**
498            This is the case when data difference is displayed in the
499            table which is present in source but absent from target database
500           */
501             create_table.innerHTML = "--";
502             add_cols.innerHTML = "--";
503             remove_cols.innerHTML = "--";
504             alter_cols.innerHTML = "--";
505             add_index.innerHTML = "--";
506             delete_index.innerHTML = "--";
507             update_rows.innerHTML = "--";
508             insert_rows.innerHTML = insert_size;
510             newRow.appendChild(create_table);
511             newRow.appendChild(add_cols);
512             newRow.appendChild(remove_cols);
513             newRow.appendChild(alter_cols);
514             newRow.appendChild(delete_index);
515             newRow.appendChild(add_index);
516             newRow.appendChild(update_rows);
517             newRow.appendChild(insert_rows);
519         } else if (remove_size == '') {
520             /**
521              This is the case when data difference between matching_tables is displayed.
522             */
523             create_table.innerHTML = "--";
524             add_cols.innerHTML = "--";
525             remove_cols.innerHTML = "--";
526             alter_cols.innerHTML = "--";
527             add_index.innerHTML = "--";
528             delete_index.innerHTML = "--";
529             update_rows.innerHTML = update_size;
530             insert_rows.innerHTML = insert_size;
532             newRow.appendChild(create_table);
533             newRow.appendChild(add_cols);
534             newRow.appendChild(remove_cols);
535             newRow.appendChild(alter_cols);
536             newRow.appendChild(delete_index);
537             newRow.appendChild(add_index);
538             newRow.appendChild(update_rows);
539             newRow.appendChild(insert_rows);
541         } else {
542             /**
543             This is the case when structure difference between matching_tables id displayed
544             */
545             create_table.innerHTML = "--";
546             add_cols.innerHTML = insert_size;
547             remove_cols.innerHTML = remove_size;
548             alter_cols.innerHTML = update_size;
549             delete_index.innerHTML = remove_index;
550             add_index.innerHTML = insert_index;
551             update_rows.innerHTML = "--";
552             insert_rows.innerHTML = "--";
554             newRow.appendChild(create_table);
555             newRow.appendChild(add_cols);
556             newRow.appendChild(remove_cols);
557             newRow.appendChild(alter_cols);
558             newRow.appendChild(delete_index);
559             newRow.appendChild(add_index);
560             newRow.appendChild(update_rows);
561             newRow.appendChild(insert_rows);
562         }
563         table_body.appendChild(newRow);
565     } else if ((relative_path[1] != 'original/img/new_struct_hovered.jpg') && (relative_path[1] != 'original/img/new_data_hovered.jpg')) {
566       //The case when the row showing the details need to be removed from the table i.e. the difference button is deselected now.
567         var table_rows = table_body.getElementsByTagName("tr");
568         var j;
569         var index = 0;
570         for (j=0; j < table_rows.length; j++)
571         {
572             if (table_rows[j].id == i) {
573                 index = j;
574                 table_rows[j].parentNode.removeChild(table_rows[j]);
575             }
576         }
577         //The table row css is being adjusted. Class "odd" for odd rows and "even" for even rows should be maintained.
578         for(index = 0; index < table_rows.length; index++)
579         {
580             row_class_element = table_rows[index].getAttribute('class');
581             if (row_class_element == "even") {
582                 table_rows[index].setAttribute("class","odd");  // for Mozilla firefox
583                 table_rows[index].className = "odd";            // for IE browser
584             } else {
585                 table_rows[index].setAttribute("class","even"); // for Mozilla firefox
586                 table_rows[index].className = "even";           // for IE browser
587             }
588         }
589     }
593  * Changes the image on hover effects
595  * @param   img_obj   the image object whose source needs to be changed
597  */
598 function change_Image(img_obj)
600      var relative_path = (img_obj.src).split("themes/");
602     if (relative_path[1] == 'original/img/new_data.jpg') {
603         img_obj.src = "./themes/original/img/new_data_hovered.jpg";
604     } else if (relative_path[1] == 'original/img/new_struct.jpg') {
605         img_obj.src = "./themes/original/img/new_struct_hovered.jpg";
606     } else if (relative_path[1] == 'original/img/new_struct_hovered.jpg') {
607         img_obj.src = "./themes/original/img/new_struct.jpg";
608     } else if (relative_path[1] == 'original/img/new_data_hovered.jpg') {
609         img_obj.src = "./themes/original/img/new_data.jpg";
610     } else if (relative_path[1] == 'original/img/new_data_selected.jpg') {
611         img_obj.src = "./themes/original/img/new_data_selected_hovered.jpg";
612     } else if(relative_path[1] == 'original/img/new_struct_selected.jpg') {
613         img_obj.src = "./themes/original/img/new_struct_selected_hovered.jpg";
614     } else if (relative_path[1] == 'original/img/new_struct_selected_hovered.jpg') {
615         img_obj.src = "./themes/original/img/new_struct_selected.jpg";
616     } else if (relative_path[1] == 'original/img/new_data_selected_hovered.jpg') {
617         img_obj.src = "./themes/original/img/new_data_selected.jpg";
618     }
622  * Generates the URL containing the list of selected table ids for synchronization and
623  * a variable checked for confirmation of deleting previous rows from target tables
625  * @param   token   the token generated for each PMA form
627  */
628 function ApplySelectedChanges(token)
630     var div =  document.getElementById("list");
631     var table = div.getElementsByTagName('table')[0];
632     var table_body = table.getElementsByTagName('tbody')[0];
633     // Get all the rows from the details table
634     var table_rows = table_body.getElementsByTagName('tr');
635     var x = table_rows.length;
636     var i;
637     /**
638      Append the token at the beginning of the query string followed by
639     Table_ids that shows that "Apply Selected Changes" button is pressed
640     */
641     var append_string = "?token="+token+"&Table_ids="+1;
642     for(i=0; i<x; i++){
643            append_string += "&";
644            append_string += i+"="+table_rows[i].id;
645     }
647     // Getting the value of checkbox delete_rows
648     var checkbox = document.getElementById("delete_rows");
649     if (checkbox.checked){
650         append_string += "&checked=true";
651     } else {
652          append_string += "&checked=false";
653     }
654     //Appending the token and list of table ids in the URL
655     location.href += token;
656     location.href += append_string;
660 * Displays an error message if any text field
661 * is left empty other than the port field.
663 * @param  string   the form name
664 * @param  object   the form
666 * @return  boolean  whether the form field is empty or not
668 function validateConnection(form_name, form_obj)
670     var check = true;
671     var src_hostfilled = true;
672     var trg_hostfilled = true;
674     for (var i=1; i<form_name.elements.length; i++)
675     {
676         // All the text fields are checked excluding the port field because the default port can be used.
677         if ((form_name.elements[i].type == 'text') && (form_name.elements[i].name != 'src_port') && (form_name.elements[i].name != 'trg_port')) {
678             check = emptyFormElements(form_obj, form_name.elements[i].name);
679             if (check==false) {
680                 element = form_name.elements[i].name;
681                 if (form_name.elements[i].name == 'src_host') {
682                     src_hostfilled = false;
683                     continue;
684                 }
685                 if (form_name.elements[i].name == 'trg_host') {
686                     trg_hostfilled = false;
687                     continue;
688                 }
689                 if ((form_name.elements[i].name == 'src_socket' && src_hostfilled==false) || (form_name.elements[i].name == 'trg_socket' && trg_hostfilled==false))
690                     break;
691                 else
692                     continue;
693             }
694         }
695     }
696     if (!check) {
697         form_obj.reset();
698         element.select();
699         alert(PMA_messages['strFormEmpty']);
700         element.focus();
701     }
702     return check;
706  * Check if a form's element is empty.
707  * An element containing only spaces is also considered empty
709  * @param   object   the form
710  * @param   string   the name of the form field to put the focus on
712  * @return  boolean  whether the form field is empty or not
713  */
714 function emptyCheckTheField(theForm, theFieldName)
716     var isEmpty  = 1;
717     var theField = theForm.elements[theFieldName];
718     // Whether the replace function (js1.2) is supported or not
719     var isRegExp = (typeof(theField.value.replace) != 'undefined');
721     if (!isRegExp) {
722         isEmpty      = (theField.value == '') ? 1 : 0;
723     } else {
724         var space_re = new RegExp('\\s+');
725         isEmpty      = (theField.value.replace(space_re, '') == '') ? 1 : 0;
726     }
728     return isEmpty;
729 } // end of the 'emptyCheckTheField()' function
733  * Check whether a form field is empty or not
735  * @param   object   the form
736  * @param   string   the name of the form field to put the focus on
738  * @return  boolean  whether the form field is empty or not
739  */
740 function emptyFormElements(theForm, theFieldName)
742     var theField = theForm.elements[theFieldName];
743     var isEmpty = emptyCheckTheField(theForm, theFieldName);
746     return isEmpty;
747 } // end of the 'emptyFormElements()' function
751  * Ensures a value submitted in a form is numeric and is in a range
753  * @param   object   the form
754  * @param   string   the name of the form field to check
755  * @param   integer  the minimum authorized value
756  * @param   integer  the maximum authorized value
758  * @return  boolean  whether a valid number has been submitted or not
759  */
760 function checkFormElementInRange(theForm, theFieldName, message, min, max)
762     var theField         = theForm.elements[theFieldName];
763     var val              = parseInt(theField.value);
765     if (typeof(min) == 'undefined') {
766         min = 0;
767     }
768     if (typeof(max) == 'undefined') {
769         max = Number.MAX_VALUE;
770     }
772     // It's not a number
773     if (isNaN(val)) {
774         theField.select();
775         alert(PMA_messages['strNotNumber']);
776         theField.focus();
777         return false;
778     }
779     // It's a number but it is not between min and max
780     else if (val < min || val > max) {
781         theField.select();
782         alert(message.replace('%d', val));
783         theField.focus();
784         return false;
785     }
786     // It's a valid number
787     else {
788         theField.value = val;
789     }
790     return true;
792 } // end of the 'checkFormElementInRange()' function
795 function checkTableEditForm(theForm, fieldsCnt)
797     // TODO: avoid sending a message if user just wants to add a line
798     // on the form but has not completed at least one field name
800     var atLeastOneField = 0;
801     var i, elm, elm2, elm3, val, id;
803     for (i=0; i<fieldsCnt; i++)
804     {
805         id = "#field_" + i + "_2";
806         elm = $(id);
807         val = elm.val()
808         if (val == 'VARCHAR' || val == 'CHAR' || val == 'BIT' || val == 'VARBINARY' || val == 'BINARY') {
809             elm2 = $("#field_" + i + "_3");
810             val = parseInt(elm2.val());
811             elm3 = $("#field_" + i + "_1");
812             if (isNaN(val) && elm3.val() != "") {
813                 elm2.select();
814                 alert(PMA_messages['strNotNumber']);
815                 elm2.focus();
816                 return false;
817             }
818         }
820         if (atLeastOneField == 0) {
821             id = "field_" + i + "_1";
822             if (!emptyCheckTheField(theForm, id)) {
823                 atLeastOneField = 1;
824             }
825         }
826     }
827     if (atLeastOneField == 0) {
828         var theField = theForm.elements["field_0_1"];
829         alert(PMA_messages['strFormEmpty']);
830         theField.focus();
831         return false;
832     }
834     return true;
835 } // enf of the 'checkTableEditForm()' function
839  * Ensures the choice between 'transmit', 'zipped', 'gzipped' and 'bzipped'
840  * checkboxes is consistant
842  * @param   object   the form
843  * @param   string   a code for the action that causes this function to be run
845  * @return  boolean  always true
846  */
847 function checkTransmitDump(theForm, theAction)
849     var formElts = theForm.elements;
851     // 'zipped' option has been checked
852     if (theAction == 'zip' && formElts['zip'].checked) {
853         if (!formElts['asfile'].checked) {
854             theForm.elements['asfile'].checked = true;
855         }
856         if (typeof(formElts['gzip']) != 'undefined' && formElts['gzip'].checked) {
857             theForm.elements['gzip'].checked = false;
858         }
859         if (typeof(formElts['bzip']) != 'undefined' && formElts['bzip'].checked) {
860             theForm.elements['bzip'].checked = false;
861         }
862     }
863     // 'gzipped' option has been checked
864     else if (theAction == 'gzip' && formElts['gzip'].checked) {
865         if (!formElts['asfile'].checked) {
866             theForm.elements['asfile'].checked = true;
867         }
868         if (typeof(formElts['zip']) != 'undefined' && formElts['zip'].checked) {
869             theForm.elements['zip'].checked = false;
870         }
871         if (typeof(formElts['bzip']) != 'undefined' && formElts['bzip'].checked) {
872             theForm.elements['bzip'].checked = false;
873         }
874     }
875     // 'bzipped' option has been checked
876     else if (theAction == 'bzip' && formElts['bzip'].checked) {
877         if (!formElts['asfile'].checked) {
878             theForm.elements['asfile'].checked = true;
879         }
880         if (typeof(formElts['zip']) != 'undefined' && formElts['zip'].checked) {
881             theForm.elements['zip'].checked = false;
882         }
883         if (typeof(formElts['gzip']) != 'undefined' && formElts['gzip'].checked) {
884             theForm.elements['gzip'].checked = false;
885         }
886     }
887     // 'transmit' option has been unchecked
888     else if (theAction == 'transmit' && !formElts['asfile'].checked) {
889         if (typeof(formElts['zip']) != 'undefined' && formElts['zip'].checked) {
890             theForm.elements['zip'].checked = false;
891         }
892         if ((typeof(formElts['gzip']) != 'undefined' && formElts['gzip'].checked)) {
893             theForm.elements['gzip'].checked = false;
894         }
895         if ((typeof(formElts['bzip']) != 'undefined' && formElts['bzip'].checked)) {
896             theForm.elements['bzip'].checked = false;
897         }
898     }
900     return true;
901 } // end of the 'checkTransmitDump()' function
903 $(document).ready(function() {
904     /**
905      * Row marking in horizontal mode (use "live" so that it works also for
906      * next pages reached via AJAX); a tr may have the class noclick to remove
907      * this behavior.
908      */
909     $('tr.odd:not(.noclick), tr.even:not(.noclick)').live('click',function() {
910         var $tr = $(this);
911         $tr.toggleClass('marked');
912         $tr.children().toggleClass('marked');
913     });
915     /**
916      * Add a date/time picker to each element that needs it
917      */
918     $('.datefield, .datetimefield').each(function() {
919         PMA_addDatepicker($(this));
920         });
924  * Row highlighting in horizontal mode (use "live"
925  * so that it works also for pages reached via AJAX)
926  */
927 $(document).ready(function() {
928     $('tr.odd, tr.even').live('hover',function() {
929         var $tr = $(this);
930         $tr.toggleClass('hover');
931         $tr.children().toggleClass('hover');
932     });
936  * This array is used to remember mark status of rows in browse mode
937  */
938 var marked_row = new Array;
941  * marks all rows and selects its first checkbox inside the given element
942  * the given element is usaly a table or a div containing the table or tables
944  * @param    container    DOM element
945  */
946 function markAllRows( container_id ) {
948     $("#"+container_id).find("input:checkbox:enabled").attr('checked', 'checked')
949     .parents("tr").addClass("marked");
950     return true;
954  * marks all rows and selects its first checkbox inside the given element
955  * the given element is usaly a table or a div containing the table or tables
957  * @param    container    DOM element
958  */
959 function unMarkAllRows( container_id ) {
961     $("#"+container_id).find("input:checkbox:enabled").removeAttr('checked')
962     .parents("tr").removeClass("marked");
963     return true;
967  * Checks/unchecks all checkbox in given conainer (f.e. a form, fieldset or div)
969  * @param   string   container_id  the container id
970  * @param   boolean  state         new value for checkbox (true or false)
971  * @return  boolean  always true
972  */
973 function setCheckboxes( container_id, state ) {
975     if(state) {
976         $("#"+container_id).find("input:checkbox").attr('checked', 'checked');
977     }
978     else {
979         $("#"+container_id).find("input:checkbox").removeAttr('checked');
980     }
982     return true;
983 } // end of the 'setCheckboxes()' function
986   * Checks/unchecks all options of a <select> element
987   *
988   * @param   string   the form name
989   * @param   string   the element name
990   * @param   boolean  whether to check or to uncheck the element
991   *
992   * @return  boolean  always true
993   */
994 function setSelectOptions(the_form, the_select, do_check)
997     if( do_check ) {
998         $("form[name='"+ the_form +"']").find("select[name='"+the_select+"']").find("option").attr('selected', 'selected');
999     }
1000     else {
1001         $("form[name='"+ the_form +"']").find("select[name="+the_select+"]").find("option").removeAttr('selected');
1002     }
1003     return true;
1004 } // end of the 'setSelectOptions()' function
1008   * Create quick sql statements.
1009   *
1010   */
1011 function insertQuery(queryType) {
1012     var myQuery = document.sqlform.sql_query;
1013     var myListBox = document.sqlform.dummy;
1014     var query = "";
1015     var table = document.sqlform.table.value;
1017     if (myListBox.options.length > 0) {
1018         sql_box_locked = true;
1019         var chaineAj = "";
1020         var valDis = "";
1021         var editDis = "";
1022         var NbSelect = 0;
1023         for (var i=0; i < myListBox.options.length; i++) {
1024             NbSelect++;
1025             if (NbSelect > 1) {
1026                 chaineAj += ", ";
1027                 valDis += ",";
1028                 editDis += ",";
1029             }
1030             chaineAj += myListBox.options[i].value;
1031             valDis += "[value-" + NbSelect + "]";
1032             editDis += myListBox.options[i].value + "=[value-" + NbSelect + "]";
1033         }
1034     if (queryType == "selectall") {
1035         query = "SELECT * FROM `" + table + "` WHERE 1";
1036     } else if (queryType == "select") {
1037         query = "SELECT " + chaineAj + " FROM `" + table + "` WHERE 1";
1038     } else if (queryType == "insert") {
1039            query = "INSERT INTO `" + table + "`(" + chaineAj + ") VALUES (" + valDis + ")";
1040     } else if (queryType == "update") {
1041         query = "UPDATE `" + table + "` SET " + editDis + " WHERE 1";
1042     } else if(queryType == "delete") {
1043         query = "DELETE FROM `" + table + "` WHERE 1";
1044     }
1045     document.sqlform.sql_query.value = query;
1046     sql_box_locked = false;
1047     }
1052   * Inserts multiple fields.
1053   *
1054   */
1055 function insertValueQuery() {
1056     var myQuery = document.sqlform.sql_query;
1057     var myListBox = document.sqlform.dummy;
1059     if(myListBox.options.length > 0) {
1060         sql_box_locked = true;
1061         var chaineAj = "";
1062         var NbSelect = 0;
1063         for(var i=0; i<myListBox.options.length; i++) {
1064             if (myListBox.options[i].selected){
1065                 NbSelect++;
1066                 if (NbSelect > 1)
1067                     chaineAj += ", ";
1068                 chaineAj += myListBox.options[i].value;
1069             }
1070         }
1072         //IE support
1073         if (document.selection) {
1074             myQuery.focus();
1075             sel = document.selection.createRange();
1076             sel.text = chaineAj;
1077             document.sqlform.insert.focus();
1078         }
1079         //MOZILLA/NETSCAPE support
1080         else if (document.sqlform.sql_query.selectionStart || document.sqlform.sql_query.selectionStart == "0") {
1081             var startPos = document.sqlform.sql_query.selectionStart;
1082             var endPos = document.sqlform.sql_query.selectionEnd;
1083             var chaineSql = document.sqlform.sql_query.value;
1085             myQuery.value = chaineSql.substring(0, startPos) + chaineAj + chaineSql.substring(endPos, chaineSql.length);
1086         } else {
1087             myQuery.value += chaineAj;
1088         }
1089         sql_box_locked = false;
1090     }
1094   * listbox redirection
1095   */
1096 function goToUrl(selObj, goToLocation) {
1097     eval("document.location.href = '" + goToLocation + "pos=" + selObj.options[selObj.selectedIndex].value + "'");
1101  * getElement
1102  */
1103 function getElement(e,f){
1104     if(document.layers){
1105         f=(f)?f:self;
1106         if(f.document.layers[e]) {
1107             return f.document.layers[e];
1108         }
1109         for(W=0;W<f.document.layers.length;W++) {
1110             return(getElement(e,f.document.layers[W]));
1111         }
1112     }
1113     if(document.all) {
1114         return document.all[e];
1115     }
1116     return document.getElementById(e);
1120   * Refresh the WYSIWYG scratchboard after changes have been made
1121   */
1122 function refreshDragOption(e) {
1123     var elm = $('#' + e);
1124     if (elm.css('visibility') == 'visible') {
1125         refreshLayout();
1126         TableDragInit();
1127     }
1131   * Refresh/resize the WYSIWYG scratchboard
1132   */
1133 function refreshLayout() {
1134     var elm = $('#pdflayout')
1135     var orientation = $('#orientation_opt').val();
1136     if($('#paper_opt').length==1){
1137         var paper = $('#paper_opt').val();
1138     }else{
1139         var paper = 'A4';
1140     }
1141     if (orientation == 'P') {
1142         posa = 'x';
1143         posb = 'y';
1144     } else {
1145         posa = 'y';
1146         posb = 'x';
1147     }
1148     elm.css('width', pdfPaperSize(paper, posa) + 'px');
1149     elm.css('height', pdfPaperSize(paper, posb) + 'px');
1153   * Show/hide the WYSIWYG scratchboard
1154   */
1155 function ToggleDragDrop(e) {
1156     var elm = $('#' + e);
1157     if (elm.css('visibility') == 'hidden') {
1158         PDFinit(); /* Defined in pdf_pages.php */
1159         elm.css('visibility', 'visible');
1160         elm.css('display', 'block');
1161         $('#showwysiwyg').val('1')
1162     } else {
1163         elm.css('visibility', 'hidden');
1164         elm.css('display', 'none');
1165         $('#showwysiwyg').val('0')
1166     }
1170   * PDF scratchboard: When a position is entered manually, update
1171   * the fields inside the scratchboard.
1172   */
1173 function dragPlace(no, axis, value) {
1174     var elm = $('#table_' + no);
1175     if (axis == 'x') {
1176         elm.css('left', value + 'px');
1177     } else {
1178         elm.css('top', value + 'px');
1179     }
1183  * Returns paper sizes for a given format
1184  */
1185 function pdfPaperSize(format, axis) {
1186     switch (format.toUpperCase()) {
1187         case '4A0':
1188             if (axis == 'x') return 4767.87; else return 6740.79;
1189             break;
1190         case '2A0':
1191             if (axis == 'x') return 3370.39; else return 4767.87;
1192             break;
1193         case 'A0':
1194             if (axis == 'x') return 2383.94; else return 3370.39;
1195             break;
1196         case 'A1':
1197             if (axis == 'x') return 1683.78; else return 2383.94;
1198             break;
1199         case 'A2':
1200             if (axis == 'x') return 1190.55; else return 1683.78;
1201             break;
1202         case 'A3':
1203             if (axis == 'x') return 841.89; else return 1190.55;
1204             break;
1205         case 'A4':
1206             if (axis == 'x') return 595.28; else return 841.89;
1207             break;
1208         case 'A5':
1209             if (axis == 'x') return 419.53; else return 595.28;
1210             break;
1211         case 'A6':
1212             if (axis == 'x') return 297.64; else return 419.53;
1213             break;
1214         case 'A7':
1215             if (axis == 'x') return 209.76; else return 297.64;
1216             break;
1217         case 'A8':
1218             if (axis == 'x') return 147.40; else return 209.76;
1219             break;
1220         case 'A9':
1221             if (axis == 'x') return 104.88; else return 147.40;
1222             break;
1223         case 'A10':
1224             if (axis == 'x') return 73.70; else return 104.88;
1225             break;
1226         case 'B0':
1227             if (axis == 'x') return 2834.65; else return 4008.19;
1228             break;
1229         case 'B1':
1230             if (axis == 'x') return 2004.09; else return 2834.65;
1231             break;
1232         case 'B2':
1233             if (axis == 'x') return 1417.32; else return 2004.09;
1234             break;
1235         case 'B3':
1236             if (axis == 'x') return 1000.63; else return 1417.32;
1237             break;
1238         case 'B4':
1239             if (axis == 'x') return 708.66; else return 1000.63;
1240             break;
1241         case 'B5':
1242             if (axis == 'x') return 498.90; else return 708.66;
1243             break;
1244         case 'B6':
1245             if (axis == 'x') return 354.33; else return 498.90;
1246             break;
1247         case 'B7':
1248             if (axis == 'x') return 249.45; else return 354.33;
1249             break;
1250         case 'B8':
1251             if (axis == 'x') return 175.75; else return 249.45;
1252             break;
1253         case 'B9':
1254             if (axis == 'x') return 124.72; else return 175.75;
1255             break;
1256         case 'B10':
1257             if (axis == 'x') return 87.87; else return 124.72;
1258             break;
1259         case 'C0':
1260             if (axis == 'x') return 2599.37; else return 3676.54;
1261             break;
1262         case 'C1':
1263             if (axis == 'x') return 1836.85; else return 2599.37;
1264             break;
1265         case 'C2':
1266             if (axis == 'x') return 1298.27; else return 1836.85;
1267             break;
1268         case 'C3':
1269             if (axis == 'x') return 918.43; else return 1298.27;
1270             break;
1271         case 'C4':
1272             if (axis == 'x') return 649.13; else return 918.43;
1273             break;
1274         case 'C5':
1275             if (axis == 'x') return 459.21; else return 649.13;
1276             break;
1277         case 'C6':
1278             if (axis == 'x') return 323.15; else return 459.21;
1279             break;
1280         case 'C7':
1281             if (axis == 'x') return 229.61; else return 323.15;
1282             break;
1283         case 'C8':
1284             if (axis == 'x') return 161.57; else return 229.61;
1285             break;
1286         case 'C9':
1287             if (axis == 'x') return 113.39; else return 161.57;
1288             break;
1289         case 'C10':
1290             if (axis == 'x') return 79.37; else return 113.39;
1291             break;
1292         case 'RA0':
1293             if (axis == 'x') return 2437.80; else return 3458.27;
1294             break;
1295         case 'RA1':
1296             if (axis == 'x') return 1729.13; else return 2437.80;
1297             break;
1298         case 'RA2':
1299             if (axis == 'x') return 1218.90; else return 1729.13;
1300             break;
1301         case 'RA3':
1302             if (axis == 'x') return 864.57; else return 1218.90;
1303             break;
1304         case 'RA4':
1305             if (axis == 'x') return 609.45; else return 864.57;
1306             break;
1307         case 'SRA0':
1308             if (axis == 'x') return 2551.18; else return 3628.35;
1309             break;
1310         case 'SRA1':
1311             if (axis == 'x') return 1814.17; else return 2551.18;
1312             break;
1313         case 'SRA2':
1314             if (axis == 'x') return 1275.59; else return 1814.17;
1315             break;
1316         case 'SRA3':
1317             if (axis == 'x') return 907.09; else return 1275.59;
1318             break;
1319         case 'SRA4':
1320             if (axis == 'x') return 637.80; else return 907.09;
1321             break;
1322         case 'LETTER':
1323             if (axis == 'x') return 612.00; else return 792.00;
1324             break;
1325         case 'LEGAL':
1326             if (axis == 'x') return 612.00; else return 1008.00;
1327             break;
1328         case 'EXECUTIVE':
1329             if (axis == 'x') return 521.86; else return 756.00;
1330             break;
1331         case 'FOLIO':
1332             if (axis == 'x') return 612.00; else return 936.00;
1333             break;
1334     } // end switch
1336     return 0;
1340  * for playing media from the BLOB repository
1342  * @param   var
1343  * @param   var     url_params  main purpose is to pass the token
1344  * @param   var     bs_ref      BLOB repository reference
1345  * @param   var     m_type      type of BLOB repository media
1346  * @param   var     w_width     width of popup window
1347  * @param   var     w_height    height of popup window
1348  */
1349 function popupBSMedia(url_params, bs_ref, m_type, is_cust_type, w_width, w_height)
1351     // if width not specified, use default
1352     if (w_width == undefined)
1353         w_width = 640;
1355     // if height not specified, use default
1356     if (w_height == undefined)
1357         w_height = 480;
1359     // open popup window (for displaying video/playing audio)
1360     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');
1364  * popups a request for changing MIME types for files in the BLOB repository
1366  * @param   var     db                      database name
1367  * @param   var     table                   table name
1368  * @param   var     reference               BLOB repository reference
1369  * @param   var     current_mime_type       current MIME type associated with BLOB repository reference
1370  */
1371 function requestMIMETypeChange(db, table, reference, current_mime_type)
1373     // no mime type specified, set to default (nothing)
1374     if (undefined == current_mime_type)
1375         current_mime_type = "";
1377     // prompt user for new mime type
1378     var new_mime_type = prompt("Enter custom MIME type", current_mime_type);
1380     // if new mime_type is specified and is not the same as the previous type, request for mime type change
1381     if (new_mime_type && new_mime_type != current_mime_type)
1382         changeMIMEType(db, table, reference, new_mime_type);
1386  * changes MIME types for files in the BLOB repository
1388  * @param   var     db              database name
1389  * @param   var     table           table name
1390  * @param   var     reference       BLOB repository reference
1391  * @param   var     mime_type       new MIME type to be associated with BLOB repository reference
1392  */
1393 function changeMIMEType(db, table, reference, mime_type)
1395     // specify url and parameters for jQuery POST
1396     var mime_chg_url = 'bs_change_mime_type.php';
1397     var params = {bs_db: db, bs_table: table, bs_reference: reference, bs_new_mime_type: mime_type};
1399     // jQuery POST
1400     jQuery.post(mime_chg_url, params);
1404  * Jquery Coding for inline editing SQL_QUERY
1405  */
1406 $(document).ready(function(){
1407     var oldText,db,table,token,sql_query;
1408     oldText=$(".inner_sql").html();
1409     $("#inline_edit").click(function(){
1410         db=$("input[name='db']").val();
1411         table=$("input[name='table']").val();
1412         token=$("input[name='token']").val();
1413         sql_query=$("input[name='sql_query']").val();
1414         $(".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'] + "\">");
1415         return false;
1416     });
1418     $("#btnSave").live("click",function(){
1419         window.location.replace("import.php?db=" + db +"&table=" + table + "&sql_query=" + $("#sql_query_edit").val()+"&show_query=1&token=" + token + "");
1420     });
1422     $("#btnDiscard").live("click",function(){
1423         $(".sql").html("<span class=\"syntax\"><span class=\"inner_sql\">" + oldText + "</span></span>");
1424     });
1426     $('.sqlbutton').click(function(evt){
1427         insertQuery(evt.target.id);
1428         return false;
1429     });
1431     $("#export_type").change(function(){
1432         if($("#export_type").val()=='svg'){
1433             $("#show_grid_opt").attr("disabled","disabled");
1434             $("#orientation_opt").attr("disabled","disabled");
1435             $("#with_doc").attr("disabled","disabled");
1436             $("#show_table_dim_opt").removeAttr("disabled");
1437             $("#all_table_same_wide").removeAttr("disabled");
1438             $("#paper_opt").removeAttr("disabled","disabled");
1439             $("#show_color_opt").removeAttr("disabled","disabled");
1440             //$(this).css("background-color","yellow");
1441         }else if($("#export_type").val()=='dia'){
1442             $("#show_grid_opt").attr("disabled","disabled");
1443             $("#with_doc").attr("disabled","disabled");
1444             $("#show_table_dim_opt").attr("disabled","disabled");
1445             $("#all_table_same_wide").attr("disabled","disabled");
1446             $("#paper_opt").removeAttr("disabled","disabled");
1447             $("#show_color_opt").removeAttr("disabled","disabled");
1448             $("#orientation_opt").removeAttr("disabled","disabled");
1449         }else if($("#export_type").val()=='eps'){
1450             $("#show_grid_opt").attr("disabled","disabled");
1451             $("#orientation_opt").removeAttr("disabled");
1452             $("#with_doc").attr("disabled","disabled");
1453             $("#show_table_dim_opt").attr("disabled","disabled");
1454             $("#all_table_same_wide").attr("disabled","disabled");
1455             $("#paper_opt").attr("disabled","disabled");
1456             $("#show_color_opt").attr("disabled","disabled");
1458         }else if($("#export_type").val()=='pdf'){
1459             $("#show_grid_opt").removeAttr("disabled");
1460             $("#orientation_opt").removeAttr("disabled");
1461             $("#with_doc").removeAttr("disabled","disabled");
1462             $("#show_table_dim_opt").removeAttr("disabled","disabled");
1463             $("#all_table_same_wide").removeAttr("disabled","disabled");
1464             $("#paper_opt").removeAttr("disabled","disabled");
1465             $("#show_color_opt").removeAttr("disabled","disabled");
1466         }else{
1467             // nothing
1468         }
1469     });
1471     $('#sqlquery').focus();
1472     if ($('#input_username')) {
1473         if ($('#input_username').val() == '') {
1474             $('#input_username').focus();
1475         } else {
1476             $('#input_password').focus();
1477         }
1478     }
1482  * Function to process the plain HTML response from an Ajax request.  Inserts
1483  * the various HTML divisions from the response at the proper locations.  The
1484  * array relates the divisions to be inserted to their placeholders.
1486  * @param   var divisions_map   an associative array of id names
1488  * <code>
1489  * PMA_ajaxInsertResponse({'resultsTable':'resultsTable_response',
1490  *                         'profilingData':'profilingData_response'});
1491  * </code>
1493  */
1495 function PMA_ajaxInsertResponse(divisions_map) {
1496     $.each(divisions_map, function(key, value) {
1497         var content_div = '#'+value;
1498         var target_div = '#'+key;
1499         var content = $(content_div).html();
1501         //replace content of target_div with that from the response
1502         $(target_div).html(content);
1503     });
1507  * Show a message on the top of the page for an Ajax request
1509  * @param   var     message     string containing the message to be shown.
1510  *                              optional, defaults to 'Loading...'
1511  * @param   var     timeout     number of milliseconds for the message to be visible
1512  *                              optional, defaults to 5000
1513  */
1515 function PMA_ajaxShowMessage(message, timeout) {
1517     //Handle the case when a empty data.message is passed.  We don't want the empty message
1518     if(message == '') {
1519         return true;
1520     }
1522     /**
1523      * @var msg String containing the message that has to be displayed
1524      * @default PMA_messages['strLoading']
1525      */
1526     if(!message) {
1527         var msg = PMA_messages['strLoading'];
1528     }
1529     else {
1530         var msg = message;
1531     }
1533     /**
1534      * @var timeout Number of milliseconds for which {@link msg} will be visible
1535      * @default 5000 ms
1536      */
1537     if(!timeout) {
1538         var to = 5000;
1539     }
1540     else {
1541         var to = timeout;
1542     }
1544     if( !ajax_message_init) {
1545         //For the first time this function is called, append a new div
1546         $(function(){
1547             $('<div id="loading_parent"></div>')
1548             .insertBefore("#serverinfo");
1550             $('<span id="loading" class="ajax_notification"></span>')
1551             .appendTo("#loading_parent")
1552             .html(msg)
1553             .slideDown('medium')
1554             .delay(to)
1555             .slideUp('medium', function(){
1556                 $(this)
1557                 .html("") //Clear the message
1558                 .hide();
1559             });
1560         }, 'top.frame_content');
1561         ajax_message_init = true;
1562     }
1563     else {
1564         //Otherwise, just show the div again after inserting the message
1565         $("#loading")
1566         .clearQueue()
1567         .html(msg)
1568         .slideDown('medium')
1569         .delay(to)
1570         .slideUp('medium', function() {
1571             $(this)
1572             .html("")
1573             .hide();
1574         })
1575     }
1579  * Hides/shows the "Open in ENUM/SET editor" message, depending on the data type of the column currently selected
1580  */
1581 function toggle_enum_notice(selectElement) {
1582     var enum_notice_id = selectElement.attr("id").split("_")[1];
1583     enum_notice_id += "_" + (parseInt(selectElement.attr("id").split("_")[2]) + 1);
1584     var selectedType = selectElement.attr("value");
1585     if (selectedType == "ENUM" || selectedType == "SET") {
1586         $("p[id='enum_notice_" + enum_notice_id + "']").show();
1587     } else {
1588         $("p[id='enum_notice_" + enum_notice_id + "']").hide();
1589     }
1593  * jQuery function that uses jQueryUI's dialogs to confirm with user. Does not
1594  *  return a jQuery object yet and hence cannot be chained
1596  * @param   string      question
1597  * @param   string      url         URL to be passed to the callbackFn to make
1598  *                                  an Ajax call to
1599  * @param   function    callbackFn  callback to execute after user clicks on OK
1600  */
1602 jQuery.fn.PMA_confirm = function(question, url, callbackFn) {
1603     if (PMA_messages['strDoYouReally'] == '') {
1604         return true;
1605     }
1607     /**
1608      *  @var    button_options  Object that stores the options passed to jQueryUI
1609      *                          dialog
1610      */
1611     var button_options = {};
1612     button_options[PMA_messages['strOK']] = function(){
1613                                                 $(this).dialog("close").remove();
1615                                                 if($.isFunction(callbackFn)) {
1616                                                     callbackFn.call(this, url);
1617                                                 }
1618                                             };
1619     button_options[PMA_messages['strCancel']] = function() {$(this).dialog("close").remove();}
1621     $('<div id="confirm_dialog"></div>')
1622     .prepend(question)
1623     .dialog({buttons: button_options});
1627  * jQuery function to sort a table's body after a new row has been appended to it.
1628  * Also fixes the even/odd classes of the table rows at the end.
1630  * @param   string      text_selector   string to select the sortKey's text
1632  * @return  jQuery Object for chaining purposes
1633  */
1634 jQuery.fn.PMA_sort_table = function(text_selector) {
1635     return this.each(function() {
1637         /**
1638          * @var table_body  Object referring to the table's <tbody> element
1639          */
1640         var table_body = $(this);
1641         /**
1642          * @var rows    Object referring to the collection of rows in {@link table_body}
1643          */
1644         var rows = $(this).find('tr').get();
1646         //get the text of the field that we will sort by
1647         $.each(rows, function(index, row) {
1648             row.sortKey = $.trim($(row).find(text_selector).text().toLowerCase());
1649         })
1651         //get the sorted order
1652         rows.sort(function(a,b) {
1653             if(a.sortKey < b.sortKey) {
1654                 return -1;
1655             }
1656             if(a.sortKey > b.sortKey) {
1657                 return 1;
1658             }
1659             return 0;
1660         })
1662         //pull out each row from the table and then append it according to it's order
1663         $.each(rows, function(index, row) {
1664             $(table_body).append(row);
1665             row.sortKey = null;
1666         })
1668         //Re-check the classes of each row
1669         $(this).find('tr:odd')
1670         .removeClass('even').addClass('odd')
1671         .end()
1672         .find('tr:even')
1673         .removeClass('odd').addClass('even');
1674     })
1678  * jQuery coding for 'Create Table'.  Used on db_operations.php,
1679  * db_structure.php and db_tracking.php (i.e., wherever
1680  * libraries/display_create_table.lib.php is used)
1682  * Attach Ajax Event handlers for Create Table
1683  */
1684 $(document).ready(function() {
1686     /**
1687      * Attach event handler to the submit action of the create table minimal form
1688      * and retrieve the full table form and display it in a dialog
1689      *
1690      * @uses    PMA_ajaxShowMessage()
1691      */
1692     $("#create_table_form_minimal.ajax").live('submit', function(event) {
1693         event.preventDefault();
1694         $form = $(this);
1696         /* @todo Validate this form! */
1698         /**
1699          *  @var    button_options  Object that stores the options passed to jQueryUI
1700          *                          dialog
1701          */
1702         var button_options = {};
1703         // in the following function we need to use $(this)
1704         button_options[PMA_messages['strCancel']] = function() {$(this).dialog('close').remove();}
1706         var button_options_error = {};
1707         button_options_error[PMA_messages['strOK']] = function() {$(this).dialog('close').remove();}
1709         PMA_ajaxShowMessage();
1710         if (! $form.find('input:hidden').is('#ajax_request_hidden')) {
1711             $form.append('<input type="hidden" id="ajax_request_hidden" name="ajax_request" value="true" />');
1712         }
1714         $.get($form.attr('action'), $form.serialize(), function(data) {
1715             //in the case of an error, show the error message returned.
1716             if (data.success != undefined && data.success == false) {
1717                 $('<div id="create_table_dialog"></div>')
1718                 .append(data.error)
1719                 .dialog({
1720                     title: PMA_messages['strCreateTable'],
1721                     height: 230,
1722                     width: 900,
1723                     open: PMA_verifyTypeOfAllColumns,
1724                     buttons : button_options_error
1725                 })// end dialog options
1726                 //remove the redundant [Back] link in the error message.
1727                 .find('fieldset').remove();
1728             } else {
1729                 $('<div id="create_table_dialog"></div>')
1730                 .append(data)
1731                 .dialog({
1732                     title: PMA_messages['strCreateTable'],
1733                     height: 600,
1734                     width: 900,
1735                     open: PMA_verifyTypeOfAllColumns,
1736                     buttons : button_options
1737                 }); // end dialog options
1738             }
1739         }) // end $.get()
1741         // empty table name and number of columns from the minimal form
1742         $form.find('input[name=table],input[name=num_fields]').val('');
1743     });
1745     /**
1746      * Attach event handler for submission of create table form (save)
1747      *
1748      * @uses    PMA_ajaxShowMessage()
1749      * @uses    $.PMA_sort_table()
1750      *
1751      */
1752     // .live() must be called after a selector, see http://api.jquery.com/live
1753     $("#create_table_form.ajax input[name=do_save_data]").live('click', function(event) {
1754         event.preventDefault();
1756         /**
1757          *  @var    the_form    object referring to the create table form
1758          */
1759         var $form = $("#create_table_form");
1761         PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
1762         if (! $form.find('input:hidden').is('#ajax_request_hidden')) {
1763             $form.append('<input type="hidden" id="ajax_request_hidden" name="ajax_request" value="true" />');
1764         }
1765         //User wants to submit the form
1766         $.post($form.attr('action'), $form.serialize() + "&do_save_data=" + $(this).val(), function(data) {
1767             if(data.success == true) {
1768                 PMA_ajaxShowMessage(data.message);
1769                 $("#create_table_dialog").dialog("close").remove();
1771                 /**
1772                  * @var tables_table    Object referring to the <tbody> element that holds the list of tables
1773                  */
1774                 var tables_table = $("#tablesForm").find("tbody").not("#tbl_summary_row");
1775                 // this is the first table created in this db
1776                 if (tables_table.length == 0) {
1777                     if (window.parent && window.parent.frame_content) {
1778                         window.parent.frame_content.location.reload();
1779                     }
1780                 } else {
1781                     /**
1782                      * @var curr_last_row   Object referring to the last <tr> element in {@link tables_table}
1783                      */
1784                     var curr_last_row = $(tables_table).find('tr:last');
1785                     /**
1786                      * @var curr_last_row_index_string   String containing the index of {@link curr_last_row}
1787                      */
1788                     var curr_last_row_index_string = $(curr_last_row).find('input:checkbox').attr('id').match(/\d+/)[0];
1789                     /**
1790                      * @var curr_last_row_index Index of {@link curr_last_row}
1791                      */
1792                     var curr_last_row_index = parseFloat(curr_last_row_index_string);
1793                     /**
1794                      * @var new_last_row_index   Index of the new row to be appended to {@link tables_table}
1795                      */
1796                     var new_last_row_index = curr_last_row_index + 1;
1797                     /**
1798                      * @var new_last_row_id String containing the id of the row to be appended to {@link tables_table}
1799                      */
1800                     var new_last_row_id = 'checkbox_tbl_' + new_last_row_index;
1802                     //append to table
1803                     $(data.new_table_string)
1804                      .find('input:checkbox')
1805                      .val(new_last_row_id)
1806                      .end()
1807                      .appendTo(tables_table);
1809                     //Sort the table
1810                     $(tables_table).PMA_sort_table('th');
1811                 }
1813                 //Refresh navigation frame as a new table has been added
1814                 if (window.parent && window.parent.frame_navigation) {
1815                     window.parent.frame_navigation.location.reload();
1816                 }
1817             }
1818             else {
1819                 PMA_ajaxShowMessage(data.error);
1820             }
1821         }) // end $.post()
1822     }) // end create table form (save)
1824     /**
1825      * Attach event handler for create table form (add fields)
1826      *
1827      * @uses    PMA_ajaxShowMessage()
1828      * @uses    $.PMA_sort_table()
1829      * @uses    window.parent.refreshNavigation()
1830      *
1831      */
1832     // .live() must be called after a selector, see http://api.jquery.com/live
1833     $("#create_table_form.ajax input[name=submit_num_fields]").live('click', function(event) {
1834         event.preventDefault();
1836         /**
1837          *  @var    the_form    object referring to the create table form
1838          */
1839         var $form = $("#create_table_form");
1841         PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
1842         if (! $form.find('input:hidden').is('#ajax_request_hidden')) {
1843             $form.append('<input type="hidden" id="ajax_request_hidden" name="ajax_request" value="true" />');
1844         }
1846         //User wants to add more fields to the table
1847         $.post($form.attr('action'), $form.serialize() + "&submit_num_fields=" + $(this).val(), function(data) {
1848             // if 'create_table_dialog' exists
1849                 if ($("#create_table_dialog").length > 0) {
1850                 $("#create_table_dialog").html(data);
1851             }
1852                 // if 'create_table_div' exists
1853                 if ($("#create_table_div").length > 0) {
1854                         $("#create_table_div").html(data);
1855                 }            
1856         }) //end $.post()
1858     }) // end create table form (add fields)
1860 }, 'top.frame_content'); //end $(document).ready for 'Create Table'
1863  * Attach Ajax event handlers for Drop Trigger.  Used on tbl_structure.php
1864  * @see $cfg['AjaxEnable']
1865  */
1866 $(document).ready(function() {
1868     $(".drop_trigger_anchor").live('click', function(event) {
1869         event.preventDefault();
1871         $anchor = $(this);
1872         /**
1873          * @var curr_row    Object reference to the current trigger's <tr>
1874          */
1875         var $curr_row = $anchor.parents('tr');
1876         /**
1877          * @var question    String containing the question to be asked for confirmation
1878          */
1879         var question = 'DROP TRIGGER IF EXISTS `' + $curr_row.children('td:first').text() + '`';
1881         $anchor.PMA_confirm(question, $anchor.attr('href'), function(url) {
1883             PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
1884             $.get(url, {'is_js_confirmed': 1, 'ajax_request': true}, function(data) {
1885                 if(data.success == true) {
1886                     PMA_ajaxShowMessage(data.message);
1887                     $("#topmenucontainer")
1888                     .next('div')
1889                     .remove()
1890                     .end()
1891                     .after(data.sql_query);
1892                     $curr_row.hide("medium").remove();
1893                 }
1894                 else {
1895                     PMA_ajaxShowMessage(data.error);
1896                 }
1897             }) // end $.get()
1898         }) // end $.PMA_confirm()
1899     }) // end $().live()
1900 }, 'top.frame_content'); //end $(document).ready() for Drop Trigger
1903  * Attach Ajax event handlers for Drop Database. Moved here from db_structure.js
1904  * as it was also required on db_create.php
1906  * @uses    $.PMA_confirm()
1907  * @uses    PMA_ajaxShowMessage()
1908  * @uses    window.parent.refreshNavigation()
1909  * @uses    window.parent.refreshMain()
1910  * @see $cfg['AjaxEnable']
1911  */
1912 $(document).ready(function() {
1913     $("#drop_db_anchor").live('click', function(event) {
1914         event.preventDefault();
1916         //context is top.frame_content, so we need to use window.parent.db to access the db var
1917         /**
1918          * @var question    String containing the question to be asked for confirmation
1919          */
1920         var question = PMA_messages['strDropDatabaseStrongWarning'] + '\n' + PMA_messages['strDoYouReally'] + ' :\n' + 'DROP DATABASE ' + window.parent.db;
1922         $(this).PMA_confirm(question, $(this).attr('href') ,function(url) {
1924             PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
1925             $.get(url, {'is_js_confirmed': '1', 'ajax_request': true}, function(data) {
1926                 //Database deleted successfully, refresh both the frames
1927                 window.parent.refreshNavigation();
1928                 window.parent.refreshMain();
1929             }) // end $.get()
1930         }); // end $.PMA_confirm()
1931     }); //end of Drop Database Ajax action
1932 }) // end of $(document).ready() for Drop Database
1935  * Attach Ajax event handlers for 'Create Database'.  Used wherever libraries/
1936  * display_create_database.lib.php is used, ie main.php and server_databases.php
1938  * @uses    PMA_ajaxShowMessage()
1939  * @see $cfg['AjaxEnable']
1940  */
1941 $(document).ready(function() {
1943     $('#create_database_form.ajax').live('submit', function(event) {
1944         event.preventDefault();
1946         $form = $(this);
1948         PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
1950         if (! $form.find('input:hidden').is('#ajax_request_hidden')) {
1951             $form.append('<input type="hidden" id="ajax_request_hidden" name="ajax_request" value="true" />');
1952         }
1954         $.post($form.attr('action'), $form.serialize(), function(data) {
1955             if(data.success == true) {
1956                 PMA_ajaxShowMessage(data.message);
1958                 //Append database's row to table
1959                 $("#tabledatabases")
1960                 .find('tbody')
1961                 .append(data.new_db_string)
1962                 .PMA_sort_table('.name')
1963                 .find('#db_summary_row')
1964                 .appendTo('#tabledatabases tbody')
1965                 .removeClass('odd even');
1967                 var $databases_count_object = $('#databases_count');
1968                 var databases_count = parseInt($databases_count_object.text());
1969                 $databases_count_object.text(++databases_count);
1970                 //Refresh navigation frame as a new database has been added
1971                 if (window.parent && window.parent.frame_navigation) {
1972                     window.parent.frame_navigation.location.reload();
1973                 }
1974             }
1975             else {
1976                 PMA_ajaxShowMessage(data.error);
1977             }
1978         }) // end $.post()
1979     }) // end $().live()
1980 })  // end $(document).ready() for Create Database
1983  * Attach Ajax event handlers for 'Change Password' on main.php
1984  */
1985 $(document).ready(function() {
1987     /**
1988      * Attach Ajax event handler on the change password anchor
1989      * @see $cfg['AjaxEnable']
1990      */
1991     $('#change_password_anchor.ajax').live('click', function(event) {
1992         event.preventDefault();
1994         /**
1995          * @var button_options  Object containing options to be passed to jQueryUI's dialog
1996          */
1997         var button_options = {};
1999         button_options[PMA_messages['strCancel']] = function() {$(this).dialog('close').remove();}
2001         $.get($(this).attr('href'), {'ajax_request': true}, function(data) {
2002             $('<div id="change_password_dialog"></div>')
2003             .dialog({
2004                 title: PMA_messages['strChangePassword'],
2005                 width: 600,
2006                 buttons : button_options
2007             })
2008             .append(data);
2009             displayPasswordGenerateButton();
2010         }) // end $.get()
2011     }) // end handler for change password anchor
2013     /**
2014      * Attach Ajax event handler for Change Password form submission
2015      *
2016      * @uses    PMA_ajaxShowMessage()
2017      * @see $cfg['AjaxEnable']
2018      */
2019     $("#change_password_form.ajax").find('input[name=change_pw]').live('click', function(event) {
2020         event.preventDefault();
2022         /**
2023          * @var the_form    Object referring to the change password form
2024          */
2025         var the_form = $("#change_password_form");
2027         /**
2028          * @var this_value  String containing the value of the submit button.
2029          * Need to append this for the change password form on Server Privileges
2030          * page to work
2031          */
2032         var this_value = $(this).val();
2034         PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
2035         $(the_form).append('<input type="hidden" name="ajax_request" value="true" />');
2037         $.post($(the_form).attr('action'), $(the_form).serialize() + '&change_pw='+ this_value, function(data) {
2038             if(data.success == true) {
2040                 PMA_ajaxShowMessage(data.message);
2042                 $("#topmenucontainer").after(data.sql_query);
2044                 $("#change_password_dialog").hide().remove();
2045                 $("#edit_user_dialog").dialog("close").remove();
2046             }
2047             else {
2048                 PMA_ajaxShowMessage(data.error);
2049             }
2050         }) // end $.post()
2051     }) // end handler for Change Password form submission
2052 }) // end $(document).ready() for Change Password
2055  * Toggle the hiding/showing of the "Open in ENUM/SET editor" message when
2056  * the page loads and when the selected data type changes
2057  */
2058 $(document).ready(function() {
2059     // is called here for normal page loads and also when opening
2060     // the Create table dialog
2061     PMA_verifyTypeOfAllColumns();
2062     //
2063     // needs live() to work also in the Create Table dialog
2064     $("select[class='column_type']").live('change', function() {
2065         toggle_enum_notice($(this));
2066     });
2069 function PMA_verifyTypeOfAllColumns() {
2070     $("select[class='column_type']").each(function() {
2071         toggle_enum_notice($(this));
2072     });
2076  * Closes the ENUM/SET editor and removes the data in it
2077  */
2078 function disable_popup() {
2079     $("#popup_background").fadeOut("fast");
2080     $("#enum_editor").fadeOut("fast");
2081     // clear the data from the text boxes
2082     $("#enum_editor #values input").remove();
2083     $("#enum_editor input[type='hidden']").remove();
2087  * Opens the ENUM/SET editor and controls its functions
2088  */
2089 $(document).ready(function() {
2090     // Needs live() to work also in the Create table dialog
2091     $("a[class='open_enum_editor']").live('click', function() {
2092         // Center the popup
2093         var windowWidth = document.documentElement.clientWidth;
2094         var windowHeight = document.documentElement.clientHeight;
2095         var popupWidth = windowWidth/2;
2096         var popupHeight = windowHeight*0.8;
2097         var popupOffsetTop = windowHeight/2 - popupHeight/2;
2098         var popupOffsetLeft = windowWidth/2 - popupWidth/2;
2099         $("#enum_editor").css({"position":"absolute", "top": popupOffsetTop, "left": popupOffsetLeft, "width": popupWidth, "height": popupHeight});
2101         // Make it appear
2102         $("#popup_background").css({"opacity":"0.7"});
2103         $("#popup_background").fadeIn("fast");
2104         $("#enum_editor").fadeIn("fast");
2106         // Get the values
2107         var values = $(this).parent().prev("input").attr("value").split(",");
2108         $.each(values, function(index, val) {
2109             if(jQuery.trim(val) != "") {
2110                  // enclose the string in single quotes if it's not already
2111                  if(val.substr(0, 1) != "'") {
2112                       val = "'" + val;
2113                  }
2114                  if(val.substr(val.length-1, val.length) != "'") {
2115                       val = val + "'";
2116                  }
2117                 // escape the single quotes, except the mandatory ones enclosing the entire string
2118                 val = val.substr(1, val.length-2).replace(/''/g, "'").replace(/\\\\/g, '\\').replace(/\\'/g, "'").replace(/'/g, "&#039;");
2119                 // escape the greater-than symbol
2120                 val = val.replace(/>/g, "&gt;");
2121                 $("#enum_editor #values").append("<input type='text' value=" + val + " />");
2122             }
2123         });
2124         // So we know which column's data is being edited
2125         $("#enum_editor").append("<input type='hidden' value='" + $(this).parent().prev("input").attr("id") + "' />");
2126         return false;
2127     });
2129     // If the "close" link is clicked, close the enum editor
2130     // Needs live() to work also in the Create table dialog
2131     $("a[class='close_enum_editor']").live('click', function() {
2132         disable_popup();
2133     });
2135     // If the "cancel" link is clicked, close the enum editor
2136     // Needs live() to work also in the Create table dialog
2137     $("a[class='cancel_enum_editor']").live('click', function() {
2138         disable_popup();
2139     });
2141     // When "add a new value" is clicked, append an empty text field
2142     // Needs live() to work also in the Create table dialog
2143     $("a[class='add_value']").live('click', function() {
2144         $("#enum_editor #values").append("<input type='text' />");
2145     });
2147     // When the submit button is clicked, put the data back into the original form
2148     // Needs live() to work also in the Create table dialog
2149     $("#enum_editor input[type='submit']").live('click', function() {
2150         var value_array = new Array();
2151         $.each($("#enum_editor #values input"), function(index, input_element) {
2152             val = jQuery.trim(input_element.value);
2153             if(val != "") {
2154                 value_array.push("'" + val.replace(/\\/g, '\\\\').replace(/'/g, "''") + "'");
2155             }
2156         });
2157         // get the Length/Values text field where this value belongs
2158         var values_id = $("#enum_editor input[type='hidden']").attr("value");
2159         $("input[id='" + values_id + "']").attr("value", value_array.join(","));
2160         disable_popup();
2161      });
2163     /**
2164      * Hides certain table structure actions, replacing them with the word "More". They are displayed
2165      * in a dropdown menu when the user hovers over the word "More."
2166      */
2167     // Remove the actions from the table cells (they are available by default for JavaScript-disabled browsers)
2168     // if the table is not a view or information_schema (otherwise there is only one action to hide and there's no point)
2169     if($("input[type='hidden'][name='table_type']").val() == "table") {
2170             var $table = $("table[id='tablestructure']");
2171         $table.find("td[class='browse']").remove();
2172         $table.find("td[class='primary']").remove();
2173         $table.find("td[class='unique']").remove();
2174         $table.find("td[class='index']").remove();
2175         $table.find("td[class='fulltext']").remove();
2176         $table.find("th[class='action']").attr("colspan", 3);
2178         // Display the "more" text
2179         $table.find("td[class='more_opts']").show();
2181         // Position the dropdown
2182         $(".structure_actions_dropdown").each(function() {
2183             // Optimize DOM querying
2184             var $this_dropdown = $(this);
2185              // The top offset must be set for IE even if it didn't change
2186             var cell_right_edge_offset = $this_dropdown.parent().offset().left + $this_dropdown.parent().innerWidth();
2187             var left_offset = cell_right_edge_offset - $this_dropdown.innerWidth();
2188             var top_offset = $this_dropdown.parent().offset().top + $this_dropdown.parent().innerHeight();
2189             $this_dropdown.offset({ top: top_offset, left: left_offset });
2190         });
2192         // A hack for IE6 to prevent the after_field select element from being displayed on top of the dropdown by
2193         // positioning an iframe directly on top of it
2194         var $after_field = $("select[name='after_field']");
2195             $("iframe[class='IE_hack']")
2196                     .width($after_field.width())
2197             .height($after_field.height())
2198             .offset({
2199                 top: $after_field.offset().top,
2200                 left: $after_field.offset().left
2201             });
2203         // When "more" is hovered over, show the hidden actions
2204         $table.find("td[class='more_opts']")
2205                     .mouseenter(function() {
2206                 if($.browser.msie && $.browser.version == "6.0") {
2207                     $("iframe[class='IE_hack']")
2208                                 .show()
2209                         .width($after_field.width()+4)
2210                         .height($after_field.height()+4)
2211                         .offset({
2212                             top: $after_field.offset().top,
2213                             left: $after_field.offset().left
2214                         });
2215                 }
2216                 $(".structure_actions_dropdown").hide(); // Hide all the other ones that may be open
2217                 $(this).children(".structure_actions_dropdown").show();
2218                 // Need to do this again for IE otherwise the offset is wrong
2219                 if($.browser.msie) {
2220                     var left_offset_IE = $(this).offset().left + $(this).innerWidth() - $(this).children(".structure_actions_dropdown").innerWidth();
2221                     var top_offset_IE = $(this).offset().top + $(this).innerHeight();
2222                     $(this).children(".structure_actions_dropdown").offset({
2223                             top: top_offset_IE,
2224                             left: left_offset_IE });
2225                 }
2226             })
2227             .mouseleave(function() {
2228                 $(this).children(".structure_actions_dropdown").hide();
2229                 if($.browser.msie && $.browser.version == "6.0") {
2230                     $("iframe[class='IE_hack']").hide();
2231                 }
2232             });
2233     }
2236 /* Displays tooltips */
2237 $(document).ready(function() {
2238     // Hide the footnotes from the footer (which are displayed for
2239     // JavaScript-disabled browsers) since the tooltip is sufficient
2240     $(".footnotes").hide();
2241     $(".footnotes span").each(function() {
2242         $(this).children("sup").remove();
2243     });
2244     // The border and padding must be removed otherwise a thin yellow box remains visible
2245     $(".footnotes").css("border", "none");
2246     $(".footnotes").css("padding", "0px");
2248     // Replace the superscripts with the help icon
2249     $("sup[class='footnotemarker']").hide();
2250     $("img[class='footnotemarker']").show();
2252     $("img[class='footnotemarker']").each(function() {
2253         var span_id = $(this).attr("id");
2254         span_id = span_id.split("_")[1];
2255         var tooltip_text = $(".footnotes span[id='footnote_" + span_id + "']").html();
2256         $(this).qtip({
2257             content: tooltip_text,
2258             show: { delay: 0 },
2259             hide: { when: 'unfocus', delay: 0 },
2260             style: { background: '#ffffcc' }
2261         });
2262     });
2265 function menuResize()
2267     var cnt = $('#topmenu');
2268     var wmax = cnt.innerWidth() - 5; // 5 px margin for jumping menu in Chrome
2269     var submenu = cnt.find('.submenu');
2270     var submenu_w = submenu.outerWidth(true);
2271     var submenu_ul = submenu.find('ul');
2272     var li = cnt.find('> li');
2273     var li2 = submenu_ul.find('li');
2274     var more_shown = li2.length > 0;
2275     var w = more_shown ? submenu_w : 0;
2277     // hide menu items
2278     var hide_start = 0;
2279     for (var i = 0; i < li.length-1; i++) { // li.length-1: skip .submenu element
2280         var el = $(li[i]);
2281         var el_width = el.outerWidth(true);
2282         el.data('width', el_width);
2283         w += el_width;
2284         if (w > wmax) {
2285             w -= el_width;
2286             if (w + submenu_w < wmax) {
2287                 hide_start = i;
2288             } else {
2289                 hide_start = i-1;
2290                 w -= $(li[i-1]).data('width');
2291             }
2292             break;
2293         }
2294     }
2296     if (hide_start > 0) {
2297         for (var i = hide_start; i < li.length-1; i++) {
2298             $(li[i])[more_shown ? 'prependTo' : 'appendTo'](submenu_ul);
2299         }
2300         submenu.show();
2301     } else if (more_shown) {
2302         w -= submenu_w;
2303         // nothing hidden, maybe something can be restored
2304         for (var i = 0; i < li2.length; i++) {
2305             //console.log(li2[i], submenu_w);
2306             w += $(li2[i]).data('width');
2307             // item fits or (it is the last item and it would fit if More got removed)
2308             if (w+submenu_w < wmax || (i == li2.length-1 && w < wmax)) {
2309                 $(li2[i]).insertBefore(submenu);
2310                 if (i == li2.length-1) {
2311                     submenu.hide();
2312                 }
2313                 continue;
2314             }
2315             break;
2316         }
2317     }
2318     if (submenu.find('.tabactive').length) {
2319         submenu.addClass('active').find('> a').removeClass('tab').addClass('tabactive');
2320     } else {
2321         submenu.removeClass('active').find('> a').addClass('tab').removeClass('tabactive');
2322     }
2325 $(function() {
2326     var topmenu = $('#topmenu');
2327     if (topmenu.length == 0) {
2328         return;
2329     }
2330     // create submenu container
2331     var link = $('<a />', {href: '#', 'class': 'tab'})
2332         .text(PMA_messages['strMore'])
2333         .click(function(e) {
2334             e.preventDefault();
2335         });
2336     var img = topmenu.find('li:first-child img');
2337     if (img.length) {
2338         img.clone().attr('src', img.attr('src').replace(/\/[^\/]+$/, '/b_more.png')).prependTo(link);
2339     }
2340     var submenu = $('<li />', {'class': 'submenu'})
2341         .append(link)
2342         .append($('<ul />'))
2343         .mouseenter(function() {
2344             if ($(this).find('ul .tabactive').length == 0) {
2345                 $(this).addClass('submenuhover').find('> a').addClass('tabactive');
2346             }
2347         })
2348         .mouseleave(function() {
2349             if ($(this).find('ul .tabactive').length == 0) {
2350                 $(this).removeClass('submenuhover').find('> a').removeClass('tabactive');
2351             }
2352         })
2353         .hide();
2354     topmenu.append(submenu);
2356     // populate submenu and register resize event
2357     $(window).resize(menuResize);
2358     menuResize();
2362  * For the checkboxes in browse mode, handles the shift/click (only works
2363  * in horizontal mode) and propagates the click to the "companion" checkbox
2364  * (in both horizontal and vertical). Works also for pages reached via AJAX.
2365  */
2366 $(document).ready(function() {
2367     $('.multi_checkbox').live('click',function(e) {
2368         var current_checkbox_id = this.id;
2369         var left_checkbox_id = current_checkbox_id.replace('_right', '_left');
2370         var right_checkbox_id = current_checkbox_id.replace('_left', '_right');
2371         var other_checkbox_id = '';
2372         if (current_checkbox_id == left_checkbox_id) {
2373             other_checkbox_id = right_checkbox_id;
2374         } else {
2375             other_checkbox_id = left_checkbox_id;
2376         }
2378         var $current_checkbox = $('#' + current_checkbox_id);
2379         var $other_checkbox = $('#' + other_checkbox_id);
2381         if (e.shiftKey) {
2382             var index_of_current_checkbox = $('.multi_checkbox').index($current_checkbox);
2383             var $last_checkbox = $('.multi_checkbox').filter('.last_clicked');
2384             var index_of_last_click = $('.multi_checkbox').index($last_checkbox);
2385             $('.multi_checkbox')
2386                 .filter(function(index) {
2387                     // the first clicked row can be on a row above or below the
2388                     // shift-clicked row
2389                     return (index_of_current_checkbox > index_of_last_click && index > index_of_last_click && index < index_of_current_checkbox)
2390                      || (index_of_last_click > index_of_current_checkbox && index < index_of_last_click && index > index_of_current_checkbox);
2391                 })
2392                 .each(function(index) {
2393                     var $intermediate_checkbox = $(this);
2394                     if ($current_checkbox.is(':checked')) {
2395                         $intermediate_checkbox.attr('checked', true);
2396                     } else {
2397                         $intermediate_checkbox.attr('checked', false);
2398                     }
2399                 });
2400         }
2402         $('.multi_checkbox').removeClass('last_clicked');
2403         $current_checkbox.addClass('last_clicked');
2405         // When there is a checkbox on both ends of the row, propagate the
2406         // click on one of them to the other one.
2407         // (the default action has not been prevented so if we have
2408         // just clicked, this "if" is true)
2409         if ($current_checkbox.is(':checked')) {
2410             $other_checkbox.attr('checked', true);
2411         } else {
2412             $other_checkbox.attr('checked', false);
2413         }
2414     });
2415 }) // end of $(document).ready() for multi checkbox
2418  * Get the row number from the classlist (for example, row_1)
2419  */
2420 function PMA_getRowNumber(classlist) {
2421     return parseInt(classlist.split(/row_/)[1]);
2425  * Changes status of slider
2426  */
2427 function PMA_set_status_label(id) {
2428     if ($('#' + id).css('display') == 'none') {
2429         $('#anchor_status_' + id).text('+ ');
2430     } else {
2431         $('#anchor_status_' + id).text('- ');
2432     }
2436  * Vertical pointer
2437  */
2438 $(document).ready(function() {
2439     $('.vpointer').live('hover',
2440         //handlerInOut
2441         function(e) {
2442         var $this_td = $(this);
2443         var row_num = PMA_getRowNumber($this_td.attr('class'));
2444         // for all td of the same vertical row, toggle hover
2445         $('.vpointer').filter('.row_' + row_num).toggleClass('hover');
2446         }
2447         );
2448 }) // end of $(document).ready() for vertical pointer
2450 $(document).ready(function() {
2451     /**
2452      * Vertical marker
2453      */
2454     $('.vmarker').live('click', function(e) {
2455         var $this_td = $(this);
2456         var row_num = PMA_getRowNumber($this_td.attr('class'));
2457         // for all td of the same vertical row, toggle the marked class
2458         $('.vmarker').filter('.row_' + row_num).toggleClass('marked');
2459         });
2461     /**
2462      * Reveal visual builder anchor
2463      */
2465     $('#visual_builder_anchor').show();
2467     /**
2468      * Page selector in db Structure (non-AJAX)
2469      */
2470     $('#tableslistcontainer').find('#pageselector').live('change', function() {
2471         $(this).parent("form").submit();
2472     });
2474     /**
2475      * Page selector in navi panel (non-AJAX)
2476      */
2477     $('#navidbpageselector').find('#pageselector').live('change', function() {
2478         $(this).parent("form").submit();
2479     });
2481     /**
2482      * Page selector in browse_foreigners windows (non-AJAX)
2483      */
2484     $('#body_browse_foreigners').find('#pageselector').live('change', function() {
2485         $(this).closest("form").submit();
2486     });
2488     /**
2489      * Load version information asynchronously.
2490      */
2491     if ($('.jsversioncheck').length > 0) {
2492         (function() {
2493             var s = document.createElement('script');
2494             s.type = 'text/javascript';
2495             s.async = true;
2496             s.src = 'http://www.phpmyadmin.net/home_page/version.js';
2497             s.onload = PMA_current_version;
2498             var x = document.getElementsByTagName('script')[0];
2499             x.parentNode.insertBefore(s, x);
2500         })();
2501     }
2503     /**
2504      * Slider effect.
2505      */
2506     $('.pma_auto_slider').each(function(idx, e) {
2507         $('<span id="anchor_status_' + e.id + '"><span>')
2508             .insertBefore(e);
2509         PMA_set_status_label(e.id);
2511         $('<a href="#' + e.id + '" id="anchor_' + e.id + '">' + e.title + '</a>')
2512             .insertBefore(e)
2513             .click(function() {
2514                 $('#' + e.id).toggle('clip');
2515                 PMA_set_status_label(e.id);
2516                 return false;
2517             });
2518     });
2520 }) // end of $(document).ready()