- Avoid author names or initials in code
[phpmyadmin/crack.git] / js / functions.js
blobb86ffe33078333cc9f9fe879047261a501b665b1
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     // at least this section is under jQuery
835     if ($("input.textfield[name='table']").val() == "") {
836         alert(PMA_messages['strFormEmpty']);
837         $("input.textfield[name='table']").focus();
838         return false;
839     }
842     return true;
843 } // enf of the 'checkTableEditForm()' function
847  * Ensures the choice between 'transmit', 'zipped', 'gzipped' and 'bzipped'
848  * checkboxes is consistant
850  * @param   object   the form
851  * @param   string   a code for the action that causes this function to be run
853  * @return  boolean  always true
854  */
855 function checkTransmitDump(theForm, theAction)
857     var formElts = theForm.elements;
859     // 'zipped' option has been checked
860     if (theAction == 'zip' && formElts['zip'].checked) {
861         if (!formElts['asfile'].checked) {
862             theForm.elements['asfile'].checked = true;
863         }
864         if (typeof(formElts['gzip']) != 'undefined' && formElts['gzip'].checked) {
865             theForm.elements['gzip'].checked = false;
866         }
867         if (typeof(formElts['bzip']) != 'undefined' && formElts['bzip'].checked) {
868             theForm.elements['bzip'].checked = false;
869         }
870     }
871     // 'gzipped' option has been checked
872     else if (theAction == 'gzip' && formElts['gzip'].checked) {
873         if (!formElts['asfile'].checked) {
874             theForm.elements['asfile'].checked = true;
875         }
876         if (typeof(formElts['zip']) != 'undefined' && formElts['zip'].checked) {
877             theForm.elements['zip'].checked = false;
878         }
879         if (typeof(formElts['bzip']) != 'undefined' && formElts['bzip'].checked) {
880             theForm.elements['bzip'].checked = false;
881         }
882     }
883     // 'bzipped' option has been checked
884     else if (theAction == 'bzip' && formElts['bzip'].checked) {
885         if (!formElts['asfile'].checked) {
886             theForm.elements['asfile'].checked = true;
887         }
888         if (typeof(formElts['zip']) != 'undefined' && formElts['zip'].checked) {
889             theForm.elements['zip'].checked = false;
890         }
891         if (typeof(formElts['gzip']) != 'undefined' && formElts['gzip'].checked) {
892             theForm.elements['gzip'].checked = false;
893         }
894     }
895     // 'transmit' option has been unchecked
896     else if (theAction == 'transmit' && !formElts['asfile'].checked) {
897         if (typeof(formElts['zip']) != 'undefined' && formElts['zip'].checked) {
898             theForm.elements['zip'].checked = false;
899         }
900         if ((typeof(formElts['gzip']) != 'undefined' && formElts['gzip'].checked)) {
901             theForm.elements['gzip'].checked = false;
902         }
903         if ((typeof(formElts['bzip']) != 'undefined' && formElts['bzip'].checked)) {
904             theForm.elements['bzip'].checked = false;
905         }
906     }
908     return true;
909 } // end of the 'checkTransmitDump()' function
911 $(document).ready(function() {
912     /**
913      * Row marking in horizontal mode (use "live" so that it works also for
914      * next pages reached via AJAX); a tr may have the class noclick to remove
915      * this behavior.
916      */
917     $('tr.odd:not(.noclick), tr.even:not(.noclick)').live('click',function(e) {
918         //do not trigger when clicked on anchor or inside input element (in inline editing mode) with exception of the first checkbox
919         if (!jQuery(e.target).is('a, a *, :input:not([name^="rows_to_delete"])')) {
920             var $tr = $(this);
921             $tr.toggleClass('marked');
922             $tr.children().toggleClass('marked');
923         }
924     });
926     /**
927      * Add a date/time picker to each element that needs it
928      */
929     $('.datefield, .datetimefield').each(function() {
930         PMA_addDatepicker($(this));
931         });
935  * Row highlighting in horizontal mode (use "live"
936  * so that it works also for pages reached via AJAX)
937  */
938 $(document).ready(function() {
939     $('tr.odd, tr.even').live('hover',function() {
940         var $tr = $(this);
941         $tr.toggleClass('hover');
942         $tr.children().toggleClass('hover');
943     });
947  * This array is used to remember mark status of rows in browse mode
948  */
949 var marked_row = new Array;
952  * marks all rows and selects its first checkbox inside the given element
953  * the given element is usaly a table or a div containing the table or tables
955  * @param    container    DOM element
956  */
957 function markAllRows( container_id ) {
959     $("#"+container_id).find("input:checkbox:enabled").attr('checked', 'checked')
960     .parents("tr").addClass("marked");
961     return true;
965  * marks all rows and selects its first checkbox inside the given element
966  * the given element is usaly a table or a div containing the table or tables
968  * @param    container    DOM element
969  */
970 function unMarkAllRows( container_id ) {
972     $("#"+container_id).find("input:checkbox:enabled").removeAttr('checked')
973     .parents("tr").removeClass("marked");
974     return true;
978  * Checks/unchecks all checkbox in given conainer (f.e. a form, fieldset or div)
980  * @param   string   container_id  the container id
981  * @param   boolean  state         new value for checkbox (true or false)
982  * @return  boolean  always true
983  */
984 function setCheckboxes( container_id, state ) {
986     if(state) {
987         $("#"+container_id).find("input:checkbox").attr('checked', 'checked');
988     }
989     else {
990         $("#"+container_id).find("input:checkbox").removeAttr('checked');
991     }
993     return true;
994 } // end of the 'setCheckboxes()' function
997   * Checks/unchecks all options of a <select> element
998   *
999   * @param   string   the form name
1000   * @param   string   the element name
1001   * @param   boolean  whether to check or to uncheck the element
1002   *
1003   * @return  boolean  always true
1004   */
1005 function setSelectOptions(the_form, the_select, do_check)
1008     if( do_check ) {
1009         $("form[name='"+ the_form +"']").find("select[name='"+the_select+"']").find("option").attr('selected', 'selected');
1010     }
1011     else {
1012         $("form[name='"+ the_form +"']").find("select[name="+the_select+"]").find("option").removeAttr('selected');
1013     }
1014     return true;
1015 } // end of the 'setSelectOptions()' function
1019   * Create quick sql statements.
1020   *
1021   */
1022 function insertQuery(queryType) {
1023     var myQuery = document.sqlform.sql_query;
1024     var myListBox = document.sqlform.dummy;
1025     var query = "";
1026     var table = document.sqlform.table.value;
1028     if (myListBox.options.length > 0) {
1029         sql_box_locked = true;
1030         var chaineAj = "";
1031         var valDis = "";
1032         var editDis = "";
1033         var NbSelect = 0;
1034         for (var i=0; i < myListBox.options.length; i++) {
1035             NbSelect++;
1036             if (NbSelect > 1) {
1037                 chaineAj += ", ";
1038                 valDis += ",";
1039                 editDis += ",";
1040             }
1041             chaineAj += myListBox.options[i].value;
1042             valDis += "[value-" + NbSelect + "]";
1043             editDis += myListBox.options[i].value + "=[value-" + NbSelect + "]";
1044         }
1045     if (queryType == "selectall") {
1046         query = "SELECT * FROM `" + table + "` WHERE 1";
1047     } else if (queryType == "select") {
1048         query = "SELECT " + chaineAj + " FROM `" + table + "` WHERE 1";
1049     } else if (queryType == "insert") {
1050            query = "INSERT INTO `" + table + "`(" + chaineAj + ") VALUES (" + valDis + ")";
1051     } else if (queryType == "update") {
1052         query = "UPDATE `" + table + "` SET " + editDis + " WHERE 1";
1053     } else if(queryType == "delete") {
1054         query = "DELETE FROM `" + table + "` WHERE 1";
1055     } else if(queryType == "clear") {
1056         query = '';
1057     }
1058     document.sqlform.sql_query.value = query;
1059     sql_box_locked = false;
1060     }
1065   * Inserts multiple fields.
1066   *
1067   */
1068 function insertValueQuery() {
1069     var myQuery = document.sqlform.sql_query;
1070     var myListBox = document.sqlform.dummy;
1072     if(myListBox.options.length > 0) {
1073         sql_box_locked = true;
1074         var chaineAj = "";
1075         var NbSelect = 0;
1076         for(var i=0; i<myListBox.options.length; i++) {
1077             if (myListBox.options[i].selected){
1078                 NbSelect++;
1079                 if (NbSelect > 1)
1080                     chaineAj += ", ";
1081                 chaineAj += myListBox.options[i].value;
1082             }
1083         }
1085         //IE support
1086         if (document.selection) {
1087             myQuery.focus();
1088             sel = document.selection.createRange();
1089             sel.text = chaineAj;
1090             document.sqlform.insert.focus();
1091         }
1092         //MOZILLA/NETSCAPE support
1093         else if (document.sqlform.sql_query.selectionStart || document.sqlform.sql_query.selectionStart == "0") {
1094             var startPos = document.sqlform.sql_query.selectionStart;
1095             var endPos = document.sqlform.sql_query.selectionEnd;
1096             var chaineSql = document.sqlform.sql_query.value;
1098             myQuery.value = chaineSql.substring(0, startPos) + chaineAj + chaineSql.substring(endPos, chaineSql.length);
1099         } else {
1100             myQuery.value += chaineAj;
1101         }
1102         sql_box_locked = false;
1103     }
1107   * listbox redirection
1108   */
1109 function goToUrl(selObj, goToLocation) {
1110     eval("document.location.href = '" + goToLocation + "pos=" + selObj.options[selObj.selectedIndex].value + "'");
1114  * getElement
1115  */
1116 function getElement(e,f){
1117     if(document.layers){
1118         f=(f)?f:self;
1119         if(f.document.layers[e]) {
1120             return f.document.layers[e];
1121         }
1122         for(W=0;W<f.document.layers.length;W++) {
1123             return(getElement(e,f.document.layers[W]));
1124         }
1125     }
1126     if(document.all) {
1127         return document.all[e];
1128     }
1129     return document.getElementById(e);
1133   * Refresh the WYSIWYG scratchboard after changes have been made
1134   */
1135 function refreshDragOption(e) {
1136     var elm = $('#' + e);
1137     if (elm.css('visibility') == 'visible') {
1138         refreshLayout();
1139         TableDragInit();
1140     }
1144   * Refresh/resize the WYSIWYG scratchboard
1145   */
1146 function refreshLayout() {
1147     var elm = $('#pdflayout')
1148     var orientation = $('#orientation_opt').val();
1149     if($('#paper_opt').length==1){
1150         var paper = $('#paper_opt').val();
1151     }else{
1152         var paper = 'A4';
1153     }
1154     if (orientation == 'P') {
1155         posa = 'x';
1156         posb = 'y';
1157     } else {
1158         posa = 'y';
1159         posb = 'x';
1160     }
1161     elm.css('width', pdfPaperSize(paper, posa) + 'px');
1162     elm.css('height', pdfPaperSize(paper, posb) + 'px');
1166   * Show/hide the WYSIWYG scratchboard
1167   */
1168 function ToggleDragDrop(e) {
1169     var elm = $('#' + e);
1170     if (elm.css('visibility') == 'hidden') {
1171         PDFinit(); /* Defined in pdf_pages.php */
1172         elm.css('visibility', 'visible');
1173         elm.css('display', 'block');
1174         $('#showwysiwyg').val('1')
1175     } else {
1176         elm.css('visibility', 'hidden');
1177         elm.css('display', 'none');
1178         $('#showwysiwyg').val('0')
1179     }
1183   * PDF scratchboard: When a position is entered manually, update
1184   * the fields inside the scratchboard.
1185   */
1186 function dragPlace(no, axis, value) {
1187     var elm = $('#table_' + no);
1188     if (axis == 'x') {
1189         elm.css('left', value + 'px');
1190     } else {
1191         elm.css('top', value + 'px');
1192     }
1196  * Returns paper sizes for a given format
1197  */
1198 function pdfPaperSize(format, axis) {
1199     switch (format.toUpperCase()) {
1200         case '4A0':
1201             if (axis == 'x') return 4767.87; else return 6740.79;
1202             break;
1203         case '2A0':
1204             if (axis == 'x') return 3370.39; else return 4767.87;
1205             break;
1206         case 'A0':
1207             if (axis == 'x') return 2383.94; else return 3370.39;
1208             break;
1209         case 'A1':
1210             if (axis == 'x') return 1683.78; else return 2383.94;
1211             break;
1212         case 'A2':
1213             if (axis == 'x') return 1190.55; else return 1683.78;
1214             break;
1215         case 'A3':
1216             if (axis == 'x') return 841.89; else return 1190.55;
1217             break;
1218         case 'A4':
1219             if (axis == 'x') return 595.28; else return 841.89;
1220             break;
1221         case 'A5':
1222             if (axis == 'x') return 419.53; else return 595.28;
1223             break;
1224         case 'A6':
1225             if (axis == 'x') return 297.64; else return 419.53;
1226             break;
1227         case 'A7':
1228             if (axis == 'x') return 209.76; else return 297.64;
1229             break;
1230         case 'A8':
1231             if (axis == 'x') return 147.40; else return 209.76;
1232             break;
1233         case 'A9':
1234             if (axis == 'x') return 104.88; else return 147.40;
1235             break;
1236         case 'A10':
1237             if (axis == 'x') return 73.70; else return 104.88;
1238             break;
1239         case 'B0':
1240             if (axis == 'x') return 2834.65; else return 4008.19;
1241             break;
1242         case 'B1':
1243             if (axis == 'x') return 2004.09; else return 2834.65;
1244             break;
1245         case 'B2':
1246             if (axis == 'x') return 1417.32; else return 2004.09;
1247             break;
1248         case 'B3':
1249             if (axis == 'x') return 1000.63; else return 1417.32;
1250             break;
1251         case 'B4':
1252             if (axis == 'x') return 708.66; else return 1000.63;
1253             break;
1254         case 'B5':
1255             if (axis == 'x') return 498.90; else return 708.66;
1256             break;
1257         case 'B6':
1258             if (axis == 'x') return 354.33; else return 498.90;
1259             break;
1260         case 'B7':
1261             if (axis == 'x') return 249.45; else return 354.33;
1262             break;
1263         case 'B8':
1264             if (axis == 'x') return 175.75; else return 249.45;
1265             break;
1266         case 'B9':
1267             if (axis == 'x') return 124.72; else return 175.75;
1268             break;
1269         case 'B10':
1270             if (axis == 'x') return 87.87; else return 124.72;
1271             break;
1272         case 'C0':
1273             if (axis == 'x') return 2599.37; else return 3676.54;
1274             break;
1275         case 'C1':
1276             if (axis == 'x') return 1836.85; else return 2599.37;
1277             break;
1278         case 'C2':
1279             if (axis == 'x') return 1298.27; else return 1836.85;
1280             break;
1281         case 'C3':
1282             if (axis == 'x') return 918.43; else return 1298.27;
1283             break;
1284         case 'C4':
1285             if (axis == 'x') return 649.13; else return 918.43;
1286             break;
1287         case 'C5':
1288             if (axis == 'x') return 459.21; else return 649.13;
1289             break;
1290         case 'C6':
1291             if (axis == 'x') return 323.15; else return 459.21;
1292             break;
1293         case 'C7':
1294             if (axis == 'x') return 229.61; else return 323.15;
1295             break;
1296         case 'C8':
1297             if (axis == 'x') return 161.57; else return 229.61;
1298             break;
1299         case 'C9':
1300             if (axis == 'x') return 113.39; else return 161.57;
1301             break;
1302         case 'C10':
1303             if (axis == 'x') return 79.37; else return 113.39;
1304             break;
1305         case 'RA0':
1306             if (axis == 'x') return 2437.80; else return 3458.27;
1307             break;
1308         case 'RA1':
1309             if (axis == 'x') return 1729.13; else return 2437.80;
1310             break;
1311         case 'RA2':
1312             if (axis == 'x') return 1218.90; else return 1729.13;
1313             break;
1314         case 'RA3':
1315             if (axis == 'x') return 864.57; else return 1218.90;
1316             break;
1317         case 'RA4':
1318             if (axis == 'x') return 609.45; else return 864.57;
1319             break;
1320         case 'SRA0':
1321             if (axis == 'x') return 2551.18; else return 3628.35;
1322             break;
1323         case 'SRA1':
1324             if (axis == 'x') return 1814.17; else return 2551.18;
1325             break;
1326         case 'SRA2':
1327             if (axis == 'x') return 1275.59; else return 1814.17;
1328             break;
1329         case 'SRA3':
1330             if (axis == 'x') return 907.09; else return 1275.59;
1331             break;
1332         case 'SRA4':
1333             if (axis == 'x') return 637.80; else return 907.09;
1334             break;
1335         case 'LETTER':
1336             if (axis == 'x') return 612.00; else return 792.00;
1337             break;
1338         case 'LEGAL':
1339             if (axis == 'x') return 612.00; else return 1008.00;
1340             break;
1341         case 'EXECUTIVE':
1342             if (axis == 'x') return 521.86; else return 756.00;
1343             break;
1344         case 'FOLIO':
1345             if (axis == 'x') return 612.00; else return 936.00;
1346             break;
1347     } // end switch
1349     return 0;
1353  * for playing media from the BLOB repository
1355  * @param   var
1356  * @param   var     url_params  main purpose is to pass the token
1357  * @param   var     bs_ref      BLOB repository reference
1358  * @param   var     m_type      type of BLOB repository media
1359  * @param   var     w_width     width of popup window
1360  * @param   var     w_height    height of popup window
1361  */
1362 function popupBSMedia(url_params, bs_ref, m_type, is_cust_type, w_width, w_height)
1364     // if width not specified, use default
1365     if (w_width == undefined)
1366         w_width = 640;
1368     // if height not specified, use default
1369     if (w_height == undefined)
1370         w_height = 480;
1372     // open popup window (for displaying video/playing audio)
1373     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');
1377  * popups a request for changing MIME types for files in the BLOB repository
1379  * @param   var     db                      database name
1380  * @param   var     table                   table name
1381  * @param   var     reference               BLOB repository reference
1382  * @param   var     current_mime_type       current MIME type associated with BLOB repository reference
1383  */
1384 function requestMIMETypeChange(db, table, reference, current_mime_type)
1386     // no mime type specified, set to default (nothing)
1387     if (undefined == current_mime_type)
1388         current_mime_type = "";
1390     // prompt user for new mime type
1391     var new_mime_type = prompt("Enter custom MIME type", current_mime_type);
1393     // if new mime_type is specified and is not the same as the previous type, request for mime type change
1394     if (new_mime_type && new_mime_type != current_mime_type)
1395         changeMIMEType(db, table, reference, new_mime_type);
1399  * changes MIME types for files in the BLOB repository
1401  * @param   var     db              database name
1402  * @param   var     table           table name
1403  * @param   var     reference       BLOB repository reference
1404  * @param   var     mime_type       new MIME type to be associated with BLOB repository reference
1405  */
1406 function changeMIMEType(db, table, reference, mime_type)
1408     // specify url and parameters for jQuery POST
1409     var mime_chg_url = 'bs_change_mime_type.php';
1410     var params = {bs_db: db, bs_table: table, bs_reference: reference, bs_new_mime_type: mime_type};
1412     // jQuery POST
1413     jQuery.post(mime_chg_url, params);
1417  * Jquery Coding for inline editing SQL_QUERY
1418  */
1419 $(document).ready(function(){
1420     var oldText,db,table,token,sql_query;
1421     oldText=$(".inner_sql").html();
1422     $("#inline_edit").click(function(){
1423         db=$("input[name='db']").val();
1424         table=$("input[name='table']").val();
1425         token=$("input[name='token']").val();
1426         sql_query=$("input[name='sql_query']").val();
1427         $(".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'] + "\">");
1428         return false;
1429     });
1431     $("#btnSave").live("click",function(){
1432         window.location.replace("import.php?db=" + db +"&table=" + table + "&sql_query=" + $("#sql_query_edit").val()+"&show_query=1&token=" + token + "");
1433     });
1435     $("#btnDiscard").live("click",function(){
1436         $(".sql").html("<span class=\"syntax\"><span class=\"inner_sql\">" + oldText + "</span></span>");
1437     });
1439     $('.sqlbutton').click(function(evt){
1440         insertQuery(evt.target.id);
1441         return false;
1442     });
1444     $("#export_type").change(function(){
1445         if($("#export_type").val()=='svg'){
1446             $("#show_grid_opt").attr("disabled","disabled");
1447             $("#orientation_opt").attr("disabled","disabled");
1448             $("#with_doc").attr("disabled","disabled");
1449             $("#show_table_dim_opt").removeAttr("disabled");
1450             $("#all_table_same_wide").removeAttr("disabled");
1451             $("#paper_opt").removeAttr("disabled","disabled");
1452             $("#show_color_opt").removeAttr("disabled","disabled");
1453             //$(this).css("background-color","yellow");
1454         }else if($("#export_type").val()=='dia'){
1455             $("#show_grid_opt").attr("disabled","disabled");
1456             $("#with_doc").attr("disabled","disabled");
1457             $("#show_table_dim_opt").attr("disabled","disabled");
1458             $("#all_table_same_wide").attr("disabled","disabled");
1459             $("#paper_opt").removeAttr("disabled","disabled");
1460             $("#show_color_opt").removeAttr("disabled","disabled");
1461             $("#orientation_opt").removeAttr("disabled","disabled");
1462         }else if($("#export_type").val()=='eps'){
1463             $("#show_grid_opt").attr("disabled","disabled");
1464             $("#orientation_opt").removeAttr("disabled");
1465             $("#with_doc").attr("disabled","disabled");
1466             $("#show_table_dim_opt").attr("disabled","disabled");
1467             $("#all_table_same_wide").attr("disabled","disabled");
1468             $("#paper_opt").attr("disabled","disabled");
1469             $("#show_color_opt").attr("disabled","disabled");
1471         }else if($("#export_type").val()=='pdf'){
1472             $("#show_grid_opt").removeAttr("disabled");
1473             $("#orientation_opt").removeAttr("disabled");
1474             $("#with_doc").removeAttr("disabled","disabled");
1475             $("#show_table_dim_opt").removeAttr("disabled","disabled");
1476             $("#all_table_same_wide").removeAttr("disabled","disabled");
1477             $("#paper_opt").removeAttr("disabled","disabled");
1478             $("#show_color_opt").removeAttr("disabled","disabled");
1479         }else{
1480             // nothing
1481         }
1482     });
1484     $('#sqlquery').focus();
1485     if ($('#input_username')) {
1486         if ($('#input_username').val() == '') {
1487             $('#input_username').focus();
1488         } else {
1489             $('#input_password').focus();
1490         }
1491     }
1495  * Show a message on the top of the page for an Ajax request
1497  * @param   var     message     string containing the message to be shown.
1498  *                              optional, defaults to 'Loading...'
1499  * @param   var     timeout     number of milliseconds for the message to be visible
1500  *                              optional, defaults to 5000
1501  */
1503 function PMA_ajaxShowMessage(message, timeout) {
1505     //Handle the case when a empty data.message is passed.  We don't want the empty message
1506     if(message == '') {
1507         return true;
1508     }
1510     /**
1511      * @var msg String containing the message that has to be displayed
1512      * @default PMA_messages['strLoading']
1513      */
1514     if(!message) {
1515         var msg = PMA_messages['strLoading'];
1516     }
1517     else {
1518         var msg = message;
1519     }
1521     /**
1522      * @var timeout Number of milliseconds for which {@link msg} will be visible
1523      * @default 5000 ms
1524      */
1525     if(!timeout) {
1526         var to = 5000;
1527     }
1528     else {
1529         var to = timeout;
1530     }
1532     if( !ajax_message_init) {
1533         //For the first time this function is called, append a new div
1534         $(function(){
1535             $('<div id="loading_parent"></div>')
1536             .insertBefore("#serverinfo");
1538             $('<span id="loading" class="ajax_notification"></span>')
1539             .appendTo("#loading_parent")
1540             .html(msg)
1541             .slideDown('medium')
1542             .delay(to)
1543             .slideUp('medium', function(){
1544                 $(this)
1545                 .html("") //Clear the message
1546                 .hide();
1547             });
1548         }, 'top.frame_content');
1549         ajax_message_init = true;
1550     }
1551     else {
1552         //Otherwise, just show the div again after inserting the message
1553         $("#loading")
1554         .clearQueue()
1555         .html(msg)
1556         .slideDown('medium')
1557         .delay(to)
1558         .slideUp('medium', function() {
1559             $(this)
1560             .html("")
1561             .hide();
1562         })
1563     }
1567  * Hides/shows the "Open in ENUM/SET editor" message, depending on the data type of the column currently selected
1568  */
1569 function PMA_showNoticeForEnum(selectElement) {
1570     var enum_notice_id = selectElement.attr("id").split("_")[1];
1571     enum_notice_id += "_" + (parseInt(selectElement.attr("id").split("_")[2]) + 1);
1572     var selectedType = selectElement.attr("value");
1573     if (selectedType == "ENUM" || selectedType == "SET") {
1574         $("p[id='enum_notice_" + enum_notice_id + "']").show();
1575     } else {
1576         $("p[id='enum_notice_" + enum_notice_id + "']").hide();
1577     }
1581  * jQuery function that uses jQueryUI's dialogs to confirm with user. Does not
1582  *  return a jQuery object yet and hence cannot be chained
1584  * @param   string      question
1585  * @param   string      url         URL to be passed to the callbackFn to make
1586  *                                  an Ajax call to
1587  * @param   function    callbackFn  callback to execute after user clicks on OK
1588  */
1590 jQuery.fn.PMA_confirm = function(question, url, callbackFn) {
1591     if (PMA_messages['strDoYouReally'] == '') {
1592         return true;
1593     }
1595     /**
1596      *  @var    button_options  Object that stores the options passed to jQueryUI
1597      *                          dialog
1598      */
1599     var button_options = {};
1600     button_options[PMA_messages['strOK']] = function(){
1601                                                 $(this).dialog("close").remove();
1603                                                 if($.isFunction(callbackFn)) {
1604                                                     callbackFn.call(this, url);
1605                                                 }
1606                                             };
1607     button_options[PMA_messages['strCancel']] = function() {$(this).dialog("close").remove();}
1609     $('<div id="confirm_dialog"></div>')
1610     .prepend(question)
1611     .dialog({buttons: button_options});
1615  * jQuery function to sort a table's body after a new row has been appended to it.
1616  * Also fixes the even/odd classes of the table rows at the end.
1618  * @param   string      text_selector   string to select the sortKey's text
1620  * @return  jQuery Object for chaining purposes
1621  */
1622 jQuery.fn.PMA_sort_table = function(text_selector) {
1623     return this.each(function() {
1625         /**
1626          * @var table_body  Object referring to the table's <tbody> element
1627          */
1628         var table_body = $(this);
1629         /**
1630          * @var rows    Object referring to the collection of rows in {@link table_body}
1631          */
1632         var rows = $(this).find('tr').get();
1634         //get the text of the field that we will sort by
1635         $.each(rows, function(index, row) {
1636             row.sortKey = $.trim($(row).find(text_selector).text().toLowerCase());
1637         })
1639         //get the sorted order
1640         rows.sort(function(a,b) {
1641             if(a.sortKey < b.sortKey) {
1642                 return -1;
1643             }
1644             if(a.sortKey > b.sortKey) {
1645                 return 1;
1646             }
1647             return 0;
1648         })
1650         //pull out each row from the table and then append it according to it's order
1651         $.each(rows, function(index, row) {
1652             $(table_body).append(row);
1653             row.sortKey = null;
1654         })
1656         //Re-check the classes of each row
1657         $(this).find('tr:odd')
1658         .removeClass('even').addClass('odd')
1659         .end()
1660         .find('tr:even')
1661         .removeClass('odd').addClass('even');
1662     })
1666  * jQuery coding for 'Create Table'.  Used on db_operations.php,
1667  * db_structure.php and db_tracking.php (i.e., wherever
1668  * libraries/display_create_table.lib.php is used)
1670  * Attach Ajax Event handlers for Create Table
1671  */
1672 $(document).ready(function() {
1674     /**
1675      * Attach event handler to the submit action of the create table minimal form
1676      * and retrieve the full table form and display it in a dialog
1677      *
1678      * @uses    PMA_ajaxShowMessage()
1679      */
1680     $("#create_table_form_minimal.ajax").live('submit', function(event) {
1681         event.preventDefault();
1682         $form = $(this);
1684         /* @todo Validate this form! */
1686         /**
1687          *  @var    button_options  Object that stores the options passed to jQueryUI
1688          *                          dialog
1689          */
1690         var button_options = {};
1691         // in the following function we need to use $(this)
1692         button_options[PMA_messages['strCancel']] = function() {$(this).dialog('close').remove();}
1694         var button_options_error = {};
1695         button_options_error[PMA_messages['strOK']] = function() {$(this).dialog('close').remove();}
1697         PMA_ajaxShowMessage();
1698         if (! $form.find('input:hidden').is('#ajax_request_hidden')) {
1699             $form.append('<input type="hidden" id="ajax_request_hidden" name="ajax_request" value="true" />');
1700         }
1702         $.get($form.attr('action'), $form.serialize(), function(data) {
1703             //in the case of an error, show the error message returned.
1704             if (data.success != undefined && data.success == false) {
1705                 $('<div id="create_table_dialog"></div>')
1706                 .append(data.error)
1707                 .dialog({
1708                     title: PMA_messages['strCreateTable'],
1709                     height: 230,
1710                     width: 900,
1711                     open: PMA_verifyTypeOfAllColumns,
1712                     buttons : button_options_error
1713                 })// end dialog options
1714                 //remove the redundant [Back] link in the error message.
1715                 .find('fieldset').remove();
1716             } else {
1717                 $('<div id="create_table_dialog"></div>')
1718                 .append(data)
1719                 .dialog({
1720                     title: PMA_messages['strCreateTable'],
1721                     height: 600,
1722                     width: 900,
1723                     open: PMA_verifyTypeOfAllColumns,
1724                     buttons : button_options
1725                 }); // end dialog options
1726             }
1727         }) // end $.get()
1729         // empty table name and number of columns from the minimal form
1730         $form.find('input[name=table],input[name=num_fields]').val('');
1731     });
1733     /**
1734      * Attach event handler for submission of create table form (save)
1735      *
1736      * @uses    PMA_ajaxShowMessage()
1737      * @uses    $.PMA_sort_table()
1738      *
1739      */
1740     // .live() must be called after a selector, see http://api.jquery.com/live
1741     $("#create_table_form input[name=do_save_data]").live('click', function(event) {
1742         event.preventDefault();
1744         /**
1745          *  @var    the_form    object referring to the create table form
1746          */
1747         var $form = $("#create_table_form");
1749         /*
1750          * First validate the form; if there is a problem, avoid submitting it
1751          *
1752          * checkTableEditForm() needs a pure element and not a jQuery object,
1753          * this is why we pass $form[0] as a parameter (the jQuery object
1754          * is actually an array of DOM elements)
1755          */
1757         if (checkTableEditForm($form[0], $form.find('input[name=orig_num_fields]').val())) {
1758             // OK, form passed validation step
1759             if ($form.hasClass('ajax')) {
1760                 PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
1761                 if (! $form.find('input:hidden').is('#ajax_request_hidden')) {
1762                     $form.append('<input type="hidden" id="ajax_request_hidden" name="ajax_request" value="true" />');
1763                 }
1764                 //User wants to submit the form
1765                 $.post($form.attr('action'), $form.serialize() + "&do_save_data=" + $(this).val(), function(data) {
1766                     if(data.success == true) {
1767                         $('#properties_message')
1768                          .removeClass('error')
1769                          .html('');
1770                         PMA_ajaxShowMessage(data.message);
1771                         // Only if the create table dialog (distinct panel) exists
1772                         if ($("#create_table_dialog").length > 0) {
1773                             $("#create_table_dialog").dialog("close").remove();
1774                         }
1776                         /**
1777                          * @var tables_table    Object referring to the <tbody> element that holds the list of tables
1778                          */
1779                         var tables_table = $("#tablesForm").find("tbody").not("#tbl_summary_row");
1780                         // this is the first table created in this db
1781                         if (tables_table.length == 0) {
1782                             if (window.parent && window.parent.frame_content) {
1783                                 window.parent.frame_content.location.reload();
1784                             }
1785                         } else {
1786                             /**
1787                              * @var curr_last_row   Object referring to the last <tr> element in {@link tables_table}
1788                              */
1789                             var curr_last_row = $(tables_table).find('tr:last');
1790                             /**
1791                              * @var curr_last_row_index_string   String containing the index of {@link curr_last_row}
1792                              */
1793                             var curr_last_row_index_string = $(curr_last_row).find('input:checkbox').attr('id').match(/\d+/)[0];
1794                             /**
1795                              * @var curr_last_row_index Index of {@link curr_last_row}
1796                              */
1797                             var curr_last_row_index = parseFloat(curr_last_row_index_string);
1798                             /**
1799                              * @var new_last_row_index   Index of the new row to be appended to {@link tables_table}
1800                              */
1801                             var new_last_row_index = curr_last_row_index + 1;
1802                             /**
1803                              * @var new_last_row_id String containing the id of the row to be appended to {@link tables_table}
1804                              */
1805                             var new_last_row_id = 'checkbox_tbl_' + new_last_row_index;
1807                             data.new_table_string = data.new_table_string.replace(/checkbox_tbl_/, new_last_row_id);
1808                             //append to table
1809                             $(data.new_table_string)
1810                              .appendTo(tables_table);
1812                             //Sort the table
1813                             $(tables_table).PMA_sort_table('th');
1814                         }
1816                         //Refresh navigation frame as a new table has been added
1817                         if (window.parent && window.parent.frame_navigation) {
1818                             window.parent.frame_navigation.location.reload();
1819                         }
1820                     } else {
1821                         $('#properties_message')
1822                          .addClass('error')
1823                          .html(data.error);
1824                     }
1825                 }) // end $.post()
1826             } // end if ($form.hasClass('ajax')
1827             else {
1828                 // non-Ajax submit
1829                 $form.append('<input type="hidden" name="do_save_data" value="save" />');
1830                 $form.submit();
1831             }
1832         } // end if (checkTableEditForm() )
1833     }) // end create table form (save)
1835     /**
1836      * Attach event handler for create table form (add fields)
1837      *
1838      * @uses    PMA_ajaxShowMessage()
1839      * @uses    $.PMA_sort_table()
1840      * @uses    window.parent.refreshNavigation()
1841      *
1842      */
1843     // .live() must be called after a selector, see http://api.jquery.com/live
1844     $("#create_table_form.ajax input[name=submit_num_fields]").live('click', function(event) {
1845         event.preventDefault();
1847         /**
1848          *  @var    the_form    object referring to the create table form
1849          */
1850         var $form = $("#create_table_form");
1852         PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
1853         if (! $form.find('input:hidden').is('#ajax_request_hidden')) {
1854             $form.append('<input type="hidden" id="ajax_request_hidden" name="ajax_request" value="true" />');
1855         }
1857         //User wants to add more fields to the table
1858         $.post($form.attr('action'), $form.serialize() + "&submit_num_fields=" + $(this).val(), function(data) {
1859             // if 'create_table_dialog' exists
1860             if ($("#create_table_dialog").length > 0) {
1861                 $("#create_table_dialog").html(data);
1862             }
1863             // if 'create_table_div' exists
1864             if ($("#create_table_div").length > 0) {
1865                 $("#create_table_div").html(data);
1866             }
1867             PMA_verifyTypeOfAllColumns();
1868         }) //end $.post()
1870     }) // end create table form (add fields)
1872 }, 'top.frame_content'); //end $(document).ready for 'Create Table'
1875  * Attach Ajax event handlers for Drop Trigger.  Used on tbl_structure.php
1876  * @see $cfg['AjaxEnable']
1877  */
1878 $(document).ready(function() {
1880     $(".drop_trigger_anchor").live('click', function(event) {
1881         event.preventDefault();
1883         $anchor = $(this);
1884         /**
1885          * @var curr_row    Object reference to the current trigger's <tr>
1886          */
1887         var $curr_row = $anchor.parents('tr');
1888         /**
1889          * @var question    String containing the question to be asked for confirmation
1890          */
1891         var question = 'DROP TRIGGER IF EXISTS `' + $curr_row.children('td:first').text() + '`';
1893         $anchor.PMA_confirm(question, $anchor.attr('href'), function(url) {
1895             PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
1896             $.get(url, {'is_js_confirmed': 1, 'ajax_request': true}, function(data) {
1897                 if(data.success == true) {
1898                     PMA_ajaxShowMessage(data.message);
1899                     $("#topmenucontainer")
1900                     .next('div')
1901                     .remove()
1902                     .end()
1903                     .after(data.sql_query);
1904                     $curr_row.hide("medium").remove();
1905                 }
1906                 else {
1907                     PMA_ajaxShowMessage(data.error);
1908                 }
1909             }) // end $.get()
1910         }) // end $.PMA_confirm()
1911     }) // end $().live()
1912 }, 'top.frame_content'); //end $(document).ready() for Drop Trigger
1915  * Attach Ajax event handlers for Drop Database. Moved here from db_structure.js
1916  * as it was also required on db_create.php
1918  * @uses    $.PMA_confirm()
1919  * @uses    PMA_ajaxShowMessage()
1920  * @uses    window.parent.refreshNavigation()
1921  * @uses    window.parent.refreshMain()
1922  * @see $cfg['AjaxEnable']
1923  */
1924 $(document).ready(function() {
1925     $("#drop_db_anchor").live('click', function(event) {
1926         event.preventDefault();
1928         //context is top.frame_content, so we need to use window.parent.db to access the db var
1929         /**
1930          * @var question    String containing the question to be asked for confirmation
1931          */
1932         var question = PMA_messages['strDropDatabaseStrongWarning'] + '\n' + PMA_messages['strDoYouReally'] + ' :\n' + 'DROP DATABASE ' + window.parent.db;
1934         $(this).PMA_confirm(question, $(this).attr('href') ,function(url) {
1936             PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
1937             $.get(url, {'is_js_confirmed': '1', 'ajax_request': true}, function(data) {
1938                 //Database deleted successfully, refresh both the frames
1939                 window.parent.refreshNavigation();
1940                 window.parent.refreshMain();
1941             }) // end $.get()
1942         }); // end $.PMA_confirm()
1943     }); //end of Drop Database Ajax action
1944 }) // end of $(document).ready() for Drop Database
1947  * Attach Ajax event handlers for 'Create Database'.  Used wherever libraries/
1948  * display_create_database.lib.php is used, ie main.php and server_databases.php
1950  * @uses    PMA_ajaxShowMessage()
1951  * @see $cfg['AjaxEnable']
1952  */
1953 $(document).ready(function() {
1955     $('#create_database_form.ajax').live('submit', function(event) {
1956         event.preventDefault();
1958         $form = $(this);
1960         PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
1962         if (! $form.find('input:hidden').is('#ajax_request_hidden')) {
1963             $form.append('<input type="hidden" id="ajax_request_hidden" name="ajax_request" value="true" />');
1964         }
1966         $.post($form.attr('action'), $form.serialize(), function(data) {
1967             if(data.success == true) {
1968                 PMA_ajaxShowMessage(data.message);
1970                 //Append database's row to table
1971                 $("#tabledatabases")
1972                 .find('tbody')
1973                 .append(data.new_db_string)
1974                 .PMA_sort_table('.name')
1975                 .find('#db_summary_row')
1976                 .appendTo('#tabledatabases tbody')
1977                 .removeClass('odd even');
1979                 var $databases_count_object = $('#databases_count');
1980                 var databases_count = parseInt($databases_count_object.text());
1981                 $databases_count_object.text(++databases_count);
1982                 //Refresh navigation frame as a new database has been added
1983                 if (window.parent && window.parent.frame_navigation) {
1984                     window.parent.frame_navigation.location.reload();
1985                 }
1986             }
1987             else {
1988                 PMA_ajaxShowMessage(data.error);
1989             }
1990         }) // end $.post()
1991     }) // end $().live()
1992 })  // end $(document).ready() for Create Database
1995  * Attach Ajax event handlers for 'Change Password' on main.php
1996  */
1997 $(document).ready(function() {
1999     /**
2000      * Attach Ajax event handler on the change password anchor
2001      * @see $cfg['AjaxEnable']
2002      */
2003     $('#change_password_anchor.dialog_active').live('click',function(event) {
2004         event.preventDefault();
2005         return false;
2006         });
2007     $('#change_password_anchor.ajax').live('click', function(event) {
2008         event.preventDefault();
2009         $(this).removeClass('ajax').addClass('dialog_active');
2010         /**
2011          * @var button_options  Object containing options to be passed to jQueryUI's dialog
2012          */
2013         var button_options = {};
2014         button_options[PMA_messages['strCancel']] = function() {$(this).dialog('close').remove();}
2015         $.get($(this).attr('href'), {'ajax_request': true}, function(data) {
2016             $('<div id="change_password_dialog"></div>')
2017             .dialog({
2018                 title: PMA_messages['strChangePassword'],
2019                 width: 600,
2020                 close: function(ev,ui) {$(this).remove();}, 
2021                 buttons : button_options,
2022                 beforeClose: function(ev,ui){ $('#change_password_anchor.dialog_active').removeClass('dialog_active').addClass('ajax')}
2023             })
2024             .append(data);
2025             displayPasswordGenerateButton();
2026         }) // end $.get()
2027     }) // end handler for change password anchor
2029     /**
2030      * Attach Ajax event handler for Change Password form submission
2031      *
2032      * @uses    PMA_ajaxShowMessage()
2033      * @see $cfg['AjaxEnable']
2034      */
2035     $("#change_password_form.ajax").find('input[name=change_pw]').live('click', function(event) {
2036         event.preventDefault();
2038         /**
2039          * @var the_form    Object referring to the change password form
2040          */
2041         var the_form = $("#change_password_form");
2043         /**
2044          * @var this_value  String containing the value of the submit button.
2045          * Need to append this for the change password form on Server Privileges
2046          * page to work
2047          */
2048         var this_value = $(this).val();
2050         PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
2051         $(the_form).append('<input type="hidden" name="ajax_request" value="true" />');
2053         $.post($(the_form).attr('action'), $(the_form).serialize() + '&change_pw='+ this_value, function(data) {
2054             if(data.success == true) {
2055                 $("#topmenucontainer").after(data.sql_query);
2056                 $("#change_password_dialog").hide().remove();
2057                 $("#edit_user_dialog").dialog("close").remove();
2058                 $('#change_password_anchor.dialog_active').removeClass('dialog_active').addClass('ajax');
2059             }
2060             else {
2061                 PMA_ajaxShowMessage(data.error);
2062             }
2063         }) // end $.post()
2064     }) // end handler for Change Password form submission
2065 }) // end $(document).ready() for Change Password
2068  * Toggle the hiding/showing of the "Open in ENUM/SET editor" message when
2069  * the page loads and when the selected data type changes
2070  */
2071 $(document).ready(function() {
2072     // is called here for normal page loads and also when opening
2073     // the Create table dialog
2074     PMA_verifyTypeOfAllColumns();
2075     //
2076     // needs live() to work also in the Create Table dialog
2077     $("select[class='column_type']").live('change', function() {
2078         PMA_showNoticeForEnum($(this));
2079     });
2082 function PMA_verifyTypeOfAllColumns() {
2083     $("select[class='column_type']").each(function() {
2084         PMA_showNoticeForEnum($(this));
2085     });
2089  * Closes the ENUM/SET editor and removes the data in it
2090  */
2091 function disable_popup() {
2092     $("#popup_background").fadeOut("fast");
2093     $("#enum_editor").fadeOut("fast");
2094     // clear the data from the text boxes
2095     $("#enum_editor #values input").remove();
2096     $("#enum_editor input[type='hidden']").remove();
2100  * Opens the ENUM/SET editor and controls its functions
2101  */
2102 $(document).ready(function() {
2103     // Needs live() to work also in the Create table dialog
2104     $("a[class='open_enum_editor']").live('click', function() {
2105         // Center the popup
2106         var windowWidth = document.documentElement.clientWidth;
2107         var windowHeight = document.documentElement.clientHeight;
2108         var popupWidth = windowWidth/2;
2109         var popupHeight = windowHeight*0.8;
2110         var popupOffsetTop = windowHeight/2 - popupHeight/2;
2111         var popupOffsetLeft = windowWidth/2 - popupWidth/2;
2112         $("#enum_editor").css({"position":"absolute", "top": popupOffsetTop, "left": popupOffsetLeft, "width": popupWidth, "height": popupHeight});
2114         // Make it appear
2115         $("#popup_background").css({"opacity":"0.7"});
2116         $("#popup_background").fadeIn("fast");
2117         $("#enum_editor").fadeIn("fast");
2119         // Get the values
2120         var values = $(this).parent().prev("input").attr("value").split(",");
2121         $.each(values, function(index, val) {
2122             if(jQuery.trim(val) != "") {
2123                  // enclose the string in single quotes if it's not already
2124                  if(val.substr(0, 1) != "'") {
2125                       val = "'" + val;
2126                  }
2127                  if(val.substr(val.length-1, val.length) != "'") {
2128                       val = val + "'";
2129                  }
2130                 // escape the single quotes, except the mandatory ones enclosing the entire string
2131                 val = val.substr(1, val.length-2).replace(/''/g, "'").replace(/\\\\/g, '\\').replace(/\\'/g, "'").replace(/'/g, "&#039;");
2132                 // escape the greater-than symbol
2133                 val = val.replace(/>/g, "&gt;");
2134                 $("#enum_editor #values").append("<input type='text' value=" + val + " />");
2135             }
2136         });
2137         // So we know which column's data is being edited
2138         $("#enum_editor").append("<input type='hidden' value='" + $(this).parent().prev("input").attr("id") + "' />");
2139         return false;
2140     });
2142     // If the "close" link is clicked, close the enum editor
2143     // Needs live() to work also in the Create table dialog
2144     $("a[class='close_enum_editor']").live('click', function() {
2145         disable_popup();
2146     });
2148     // If the "cancel" link is clicked, close the enum editor
2149     // Needs live() to work also in the Create table dialog
2150     $("a[class='cancel_enum_editor']").live('click', function() {
2151         disable_popup();
2152     });
2154     // When "add a new value" is clicked, append an empty text field
2155     // Needs live() to work also in the Create table dialog
2156     $("a[class='add_value']").live('click', function() {
2157         $("#enum_editor #values").append("<input type='text' />");
2158     });
2160     // When the submit button is clicked, put the data back into the original form
2161     // Needs live() to work also in the Create table dialog
2162     $("#enum_editor input[type='submit']").live('click', function() {
2163         var value_array = new Array();
2164         $.each($("#enum_editor #values input"), function(index, input_element) {
2165             val = jQuery.trim(input_element.value);
2166             if(val != "") {
2167                 value_array.push("'" + val.replace(/\\/g, '\\\\').replace(/'/g, "''") + "'");
2168             }
2169         });
2170         // get the Length/Values text field where this value belongs
2171         var values_id = $("#enum_editor input[type='hidden']").attr("value");
2172         $("input[id='" + values_id + "']").attr("value", value_array.join(","));
2173         disable_popup();
2174      });
2176     /**
2177      * Hides certain table structure actions, replacing them with the word "More". They are displayed
2178      * in a dropdown menu when the user hovers over the word "More."
2179      */
2180     // Remove the actions from the table cells (they are available by default for JavaScript-disabled browsers)
2181     // if the table is not a view or information_schema (otherwise there is only one action to hide and there's no point)
2182     if($("input[type='hidden'][name='table_type']").val() == "table") {
2183         var $table = $("table[id='tablestructure']");
2184         $table.find("td[class='browse']").remove();
2185         $table.find("td[class='primary']").remove();
2186         $table.find("td[class='unique']").remove();
2187         $table.find("td[class='index']").remove();
2188         $table.find("td[class='fulltext']").remove();
2189         $table.find("th[class='action']").attr("colspan", 3);
2191         // Display the "more" text
2192         $table.find("td[class='more_opts']").show();
2194         // Position the dropdown
2195         $(".structure_actions_dropdown").each(function() {
2196             // Optimize DOM querying
2197             var $this_dropdown = $(this);
2198              // The top offset must be set for IE even if it didn't change
2199             var cell_right_edge_offset = $this_dropdown.parent().offset().left + $this_dropdown.parent().innerWidth();
2200             var left_offset = cell_right_edge_offset - $this_dropdown.innerWidth();
2201             var top_offset = $this_dropdown.parent().offset().top + $this_dropdown.parent().innerHeight();
2202             $this_dropdown.offset({ top: top_offset, left: left_offset });
2203         });
2205         // A hack for IE6 to prevent the after_field select element from being displayed on top of the dropdown by
2206         // positioning an iframe directly on top of it
2207         var $after_field = $("select[name='after_field']");
2208         $("iframe[class='IE_hack']")
2209             .width($after_field.width())
2210             .height($after_field.height())
2211             .offset({
2212                 top: $after_field.offset().top,
2213                 left: $after_field.offset().left
2214             });
2216         // When "more" is hovered over, show the hidden actions
2217         $table.find("td[class='more_opts']")
2218             .mouseenter(function() {
2219                 if($.browser.msie && $.browser.version == "6.0") {
2220                     $("iframe[class='IE_hack']")
2221                         .show()
2222                         .width($after_field.width()+4)
2223                         .height($after_field.height()+4)
2224                         .offset({
2225                             top: $after_field.offset().top,
2226                             left: $after_field.offset().left
2227                         });
2228                 }
2229                 $(".structure_actions_dropdown").hide(); // Hide all the other ones that may be open
2230                 $(this).children(".structure_actions_dropdown").show();
2231                 // Need to do this again for IE otherwise the offset is wrong
2232                 if($.browser.msie) {
2233                     var left_offset_IE = $(this).offset().left + $(this).innerWidth() - $(this).children(".structure_actions_dropdown").innerWidth();
2234                     var top_offset_IE = $(this).offset().top + $(this).innerHeight();
2235                     $(this).children(".structure_actions_dropdown").offset({
2236                         top: top_offset_IE,
2237                         left: left_offset_IE });
2238                 }
2239             })
2240             .mouseleave(function() {
2241                 $(this).children(".structure_actions_dropdown").hide();
2242                 if($.browser.msie && $.browser.version == "6.0") {
2243                     $("iframe[class='IE_hack']").hide();
2244                 }
2245             });
2246     }
2249 /* Displays tooltips */
2250 $(document).ready(function() {
2251     // Hide the footnotes from the footer (which are displayed for
2252     // JavaScript-disabled browsers) since the tooltip is sufficient
2253     $(".footnotes").hide();
2254     $(".footnotes span").each(function() {
2255         $(this).children("sup").remove();
2256     });
2257     // The border and padding must be removed otherwise a thin yellow box remains visible
2258     $(".footnotes").css("border", "none");
2259     $(".footnotes").css("padding", "0px");
2261     // Replace the superscripts with the help icon
2262     $("sup[class='footnotemarker']").hide();
2263     $("img[class='footnotemarker']").show();
2265     $("img[class='footnotemarker']").each(function() {
2266         var span_id = $(this).attr("id");
2267         span_id = span_id.split("_")[1];
2268         var tooltip_text = $(".footnotes span[id='footnote_" + span_id + "']").html();
2269         $(this).qtip({
2270             content: tooltip_text,
2271             show: { delay: 0 },
2272             hide: { when: 'unfocus', delay: 0 },
2273             style: { background: '#ffffcc' }
2274         });
2275     });
2278 function menuResize()
2280     var cnt = $('#topmenu');
2281     var wmax = cnt.innerWidth() - 5; // 5 px margin for jumping menu in Chrome
2282     var submenu = cnt.find('.submenu');
2283     var submenu_w = submenu.outerWidth(true);
2284     var submenu_ul = submenu.find('ul');
2285     var li = cnt.find('> li');
2286     var li2 = submenu_ul.find('li');
2287     var more_shown = li2.length > 0;
2288     var w = more_shown ? submenu_w : 0;
2290     // hide menu items
2291     var hide_start = 0;
2292     for (var i = 0; i < li.length-1; i++) { // li.length-1: skip .submenu element
2293         var el = $(li[i]);
2294         var el_width = el.outerWidth(true);
2295         el.data('width', el_width);
2296         w += el_width;
2297         if (w > wmax) {
2298             w -= el_width;
2299             if (w + submenu_w < wmax) {
2300                 hide_start = i;
2301             } else {
2302                 hide_start = i-1;
2303                 w -= $(li[i-1]).data('width');
2304             }
2305             break;
2306         }
2307     }
2309     if (hide_start > 0) {
2310         for (var i = hide_start; i < li.length-1; i++) {
2311             $(li[i])[more_shown ? 'prependTo' : 'appendTo'](submenu_ul);
2312         }
2313         submenu.addClass('shown');
2314     } else if (more_shown) {
2315         w -= submenu_w;
2316         // nothing hidden, maybe something can be restored
2317         for (var i = 0; i < li2.length; i++) {
2318             //console.log(li2[i], submenu_w);
2319             w += $(li2[i]).data('width');
2320             // item fits or (it is the last item and it would fit if More got removed)
2321             if (w+submenu_w < wmax || (i == li2.length-1 && w < wmax)) {
2322                 $(li2[i]).insertBefore(submenu);
2323                 if (i == li2.length-1) {
2324                     submenu.removeClass('shown');
2325                 }
2326                 continue;
2327             }
2328             break;
2329         }
2330     }
2331     if (submenu.find('.tabactive').length) {
2332         submenu.addClass('active').find('> a').removeClass('tab').addClass('tabactive');
2333     } else {
2334         submenu.removeClass('active').find('> a').addClass('tab').removeClass('tabactive');
2335     }
2338 $(function() {
2339     var topmenu = $('#topmenu');
2340     if (topmenu.length == 0) {
2341         return;
2342     }
2343     // create submenu container
2344     var link = $('<a />', {href: '#', 'class': 'tab'})
2345         .text(PMA_messages['strMore'])
2346         .click(function(e) {
2347             e.preventDefault();
2348         });
2349     var img = topmenu.find('li:first-child img');
2350     if (img.length) {
2351         img.clone().attr('src', img.attr('src').replace(/\/[^\/]+$/, '/b_more.png')).prependTo(link);
2352     }
2353     var submenu = $('<li />', {'class': 'submenu'})
2354         .append(link)
2355         .append($('<ul />'))
2356         .mouseenter(function() {
2357             if ($(this).find('ul .tabactive').length == 0) {
2358                 $(this).addClass('submenuhover').find('> a').addClass('tabactive');
2359             }
2360         })
2361         .mouseleave(function() {
2362             if ($(this).find('ul .tabactive').length == 0) {
2363                 $(this).removeClass('submenuhover').find('> a').removeClass('tabactive');
2364             }
2365         });
2366     topmenu.append(submenu);
2368     // populate submenu and register resize event
2369     $(window).resize(menuResize);
2370     menuResize();
2374  * For the checkboxes in browse mode, handles the shift/click (only works
2375  * in horizontal mode) and propagates the click to the "companion" checkbox
2376  * (in both horizontal and vertical). Works also for pages reached via AJAX.
2377  */
2378 $(document).ready(function() {
2379     $('.multi_checkbox').live('click',function(e) {
2380         var current_checkbox_id = this.id;
2381         var left_checkbox_id = current_checkbox_id.replace('_right', '_left');
2382         var right_checkbox_id = current_checkbox_id.replace('_left', '_right');
2383         var other_checkbox_id = '';
2384         if (current_checkbox_id == left_checkbox_id) {
2385             other_checkbox_id = right_checkbox_id;
2386         } else {
2387             other_checkbox_id = left_checkbox_id;
2388         }
2390         var $current_checkbox = $('#' + current_checkbox_id);
2391         var $other_checkbox = $('#' + other_checkbox_id);
2393         if (e.shiftKey) {
2394             var index_of_current_checkbox = $('.multi_checkbox').index($current_checkbox);
2395             var $last_checkbox = $('.multi_checkbox').filter('.last_clicked');
2396             var index_of_last_click = $('.multi_checkbox').index($last_checkbox);
2397             $('.multi_checkbox')
2398                 .filter(function(index) {
2399                     // the first clicked row can be on a row above or below the
2400                     // shift-clicked row
2401                     return (index_of_current_checkbox > index_of_last_click && index > index_of_last_click && index < index_of_current_checkbox)
2402                      || (index_of_last_click > index_of_current_checkbox && index < index_of_last_click && index > index_of_current_checkbox);
2403                 })
2404                 .each(function(index) {
2405                     var $intermediate_checkbox = $(this);
2406                     if ($current_checkbox.is(':checked')) {
2407                         $intermediate_checkbox.attr('checked', true);
2408                     } else {
2409                         $intermediate_checkbox.attr('checked', false);
2410                     }
2411                 });
2412         }
2414         $('.multi_checkbox').removeClass('last_clicked');
2415         $current_checkbox.addClass('last_clicked');
2417         // When there is a checkbox on both ends of the row, propagate the
2418         // click on one of them to the other one.
2419         // (the default action has not been prevented so if we have
2420         // just clicked, this "if" is true)
2421         if ($current_checkbox.is(':checked')) {
2422             $other_checkbox.attr('checked', true);
2423         } else {
2424             $other_checkbox.attr('checked', false);
2425         }
2426     });
2427 }) // end of $(document).ready() for multi checkbox
2430  * Get the row number from the classlist (for example, row_1)
2431  */
2432 function PMA_getRowNumber(classlist) {
2433     return parseInt(classlist.split(/row_/)[1]);
2437  * Changes status of slider
2438  */
2439 function PMA_set_status_label(id) {
2440     if ($('#' + id).css('display') == 'none') {
2441         $('#anchor_status_' + id).text('+ ');
2442     } else {
2443         $('#anchor_status_' + id).text('- ');
2444     }
2448  * Initializes slider effect.
2449  */
2450 function PMA_init_slider() {
2451     $('.pma_auto_slider').each(function(idx, e) {
2452         if ($(e).hasClass('slider_init_done')) return;
2453         $(e).addClass('slider_init_done');
2454         $('<span id="anchor_status_' + e.id + '"><span>')
2455             .insertBefore(e);
2456         PMA_set_status_label(e.id);
2458         $('<a href="#' + e.id + '" id="anchor_' + e.id + '">' + e.title + '</a>')
2459             .insertBefore(e)
2460             .click(function() {
2461                 $('#' + e.id).toggle('clip');
2462                 PMA_set_status_label(e.id);
2463                 return false;
2464             });
2465     });
2469  * Vertical pointer
2470  */
2471 $(document).ready(function() {
2472     $('.vpointer').live('hover',
2473         //handlerInOut
2474         function(e) {
2475         var $this_td = $(this);
2476         var row_num = PMA_getRowNumber($this_td.attr('class'));
2477         // for all td of the same vertical row, toggle hover
2478         $('.vpointer').filter('.row_' + row_num).toggleClass('hover');
2479         }
2480         );
2481 }) // end of $(document).ready() for vertical pointer
2483 $(document).ready(function() {
2484     /**
2485      * Vertical marker
2486      */
2487     $('.vmarker').live('click', function(e) {
2488         var $this_td = $(this);
2489         var row_num = PMA_getRowNumber($this_td.attr('class'));
2490         // for all td of the same vertical row, toggle the marked class
2491         $('.vmarker').filter('.row_' + row_num).toggleClass('marked');
2492         });
2494     /**
2495      * Reveal visual builder anchor
2496      */
2498     $('#visual_builder_anchor').show();
2500     /**
2501      * Page selector in db Structure (non-AJAX)
2502      */
2503     $('#tableslistcontainer').find('#pageselector').live('change', function() {
2504         $(this).parent("form").submit();
2505     });
2507     /**
2508      * Page selector in navi panel (non-AJAX)
2509      */
2510     $('#navidbpageselector').find('#pageselector').live('change', function() {
2511         $(this).parent("form").submit();
2512     });
2514     /**
2515      * Page selector in browse_foreigners windows (non-AJAX)
2516      */
2517     $('#body_browse_foreigners').find('#pageselector').live('change', function() {
2518         $(this).closest("form").submit();
2519     });
2521     /**
2522      * Load version information asynchronously.
2523      */
2524     if ($('.jsversioncheck').length > 0) {
2525         (function() {
2526             var s = document.createElement('script');
2527             s.type = 'text/javascript';
2528             s.async = true;
2529             s.src = 'http://www.phpmyadmin.net/home_page/version.js';
2530             s.onload = PMA_current_version;
2531             var x = document.getElementsByTagName('script')[0];
2532             x.parentNode.insertBefore(s, x);
2533         })();
2534     }
2536     /**
2537      * Slider effect.
2538      */
2539     PMA_init_slider();
2541     /**
2542      * Enables the text generated by PMA_linkOrButton() to be clickable
2543      */
2544     $('.clickprevimage')
2545         .css('color', function(index) {
2546             return $('a').css('color');
2547         })
2548         .css('cursor', function(index) {
2549             return $('a').css('cursor');
2550         }) //todo: hover effect
2551         .live('click',function(e) {
2552             $this_span = $(this);
2553             if ($this_span.closest('td').is('.inline_edit_anchor')) {
2554             // this would bind a second click event to the inline edit
2555             // anchor and would disturb its behavior
2556             } else {
2557                 $this_span.parent().find('input:image').click();
2558             }
2559         });
2561 }) // end of $(document).ready()