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