Advisor: mark that 'Rate of reading fixed position' may be wrong, requires further...
[phpmyadmin/thilanka.git] / js / functions.js
blob022cb808c1bc68c141fcd01d075b1bff495171be
1 /* vim: set expandtab sw=4 ts=4 sts=4: */
2 /**
3 * general function, usally for data manipulation pages
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
15 var only_once_elements = new Array();
17 /**
18 * @var int ajax_message_count Number of AJAX messages shown since page load
20 var ajax_message_count = 0;
22 /**
23 * @var codemirror_editor object containing CodeMirror editor
25 var codemirror_editor = false;
27 /**
28 * @var chart_activeTimeouts object active timeouts that refresh the charts. When disabling a realtime chart, this can be used to stop the continuous ajax requests
30 var chart_activeTimeouts = new Object();
32 /**
33 * Add a hidden field to the form to indicate that this will be an
34 * Ajax request (only if this hidden field does not exist)
36 * @param object the form
38 function PMA_prepareForAjaxRequest($form)
40 if (! $form.find('input:hidden').is('#ajax_request_hidden')) {
41 $form.append('<input type="hidden" id="ajax_request_hidden" name="ajax_request" value="true" />');
45 /**
46 * Generate a new password and copy it to the password input areas
48 * @param object the form that holds the password fields
50 * @return boolean always true
52 function suggestPassword(passwd_form)
54 // restrict the password to just letters and numbers to avoid problems:
55 // "editors and viewers regard the password as multiple words and
56 // things like double click no longer work"
57 var pwchars = "abcdefhjmnpqrstuvwxyz23456789ABCDEFGHJKLMNPQRSTUVWYXZ";
58 var passwordlength = 16; // do we want that to be dynamic? no, keep it simple :)
59 var passwd = passwd_form.generated_pw;
60 passwd.value = '';
62 for ( i = 0; i < passwordlength; i++ ) {
63 passwd.value += pwchars.charAt( Math.floor( Math.random() * pwchars.length ) )
65 passwd_form.text_pma_pw.value = passwd.value;
66 passwd_form.text_pma_pw2.value = passwd.value;
67 return true;
70 /**
71 * Version string to integer conversion.
73 function parseVersionString (str)
75 if (typeof(str) != 'string') { return false; }
76 var add = 0;
77 // Parse possible alpha/beta/rc/
78 var state = str.split('-');
79 if (state.length >= 2) {
80 if (state[1].substr(0, 2) == 'rc') {
81 add = - 20 - parseInt(state[1].substr(2));
82 } else if (state[1].substr(0, 4) == 'beta') {
83 add = - 40 - parseInt(state[1].substr(4));
84 } else if (state[1].substr(0, 5) == 'alpha') {
85 add = - 60 - parseInt(state[1].substr(5));
86 } else if (state[1].substr(0, 3) == 'dev') {
87 /* We don't handle dev, it's git snapshot */
88 add = 0;
91 // Parse version
92 var x = str.split('.');
93 // Use 0 for non existing parts
94 var maj = parseInt(x[0]) || 0;
95 var min = parseInt(x[1]) || 0;
96 var pat = parseInt(x[2]) || 0;
97 var hotfix = parseInt(x[3]) || 0;
98 return maj * 100000000 + min * 1000000 + pat * 10000 + hotfix * 100 + add;
102 * Indicates current available version on main page.
104 function PMA_current_version()
106 var current = parseVersionString(pmaversion);
107 var latest = parseVersionString(PMA_latest_version);
108 var version_information_message = PMA_messages['strLatestAvailable'] + ' ' + PMA_latest_version;
109 if (latest > current) {
110 var message = $.sprintf(PMA_messages['strNewerVersion'], PMA_latest_version, PMA_latest_date);
111 if (Math.floor(latest / 10000) == Math.floor(current / 10000)) {
112 /* Security update */
113 klass = 'error';
114 } else {
115 klass = 'notice';
117 $('#maincontainer').after('<div class="' + klass + '">' + message + '</div>');
119 if (latest == current) {
120 version_information_message = ' (' + PMA_messages['strUpToDate'] + ')';
122 $('#li_pma_version').append(version_information_message);
126 * for libraries/display_change_password.lib.php
127 * libraries/user_password.php
131 function displayPasswordGenerateButton()
133 $('#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>');
134 $('#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>');
138 * Adds a date/time picker to an element
140 * @param object $this_element a jQuery object pointing to the element
142 function PMA_addDatepicker($this_element, options)
144 var showTimeOption = false;
145 if ($this_element.is('.datetimefield')) {
146 showTimeOption = true;
149 var defaultOptions = {
150 showOn: 'button',
151 buttonImage: themeCalendarImage, // defined in js/messages.php
152 buttonImageOnly: true,
153 stepMinutes: 1,
154 stepHours: 1,
155 showSecond: true,
156 showTimepicker: showTimeOption,
157 showButtonPanel: false,
158 dateFormat: 'yy-mm-dd', // yy means year with four digits
159 timeFormat: 'hh:mm:ss',
160 altFieldTimeOnly: false,
161 showAnim: '',
162 beforeShow: function(input, inst) {
163 // Remember that we came from the datepicker; this is used
164 // in tbl_change.js by verificationsAfterFieldChange()
165 $this_element.data('comes_from', 'datepicker');
167 // Fix wrong timepicker z-index, doesn't work without timeout
168 setTimeout(function() {
169 $('#ui-timepicker-div').css('z-index',$('#ui-datepicker-div').css('z-index'))
170 },0);
174 $this_element.datetimepicker($.extend(defaultOptions, options));
178 * selects the content of a given object, f.e. a textarea
180 * @param object element element of which the content will be selected
181 * @param var lock variable which holds the lock for this element
182 * or true, if no lock exists
183 * @param boolean only_once if true this is only done once
184 * f.e. only on first focus
186 function selectContent( element, lock, only_once )
188 if ( only_once && only_once_elements[element.name] ) {
189 return;
192 only_once_elements[element.name] = true;
194 if ( lock ) {
195 return;
198 element.select();
202 * Displays a confirmation box before to submit a "DROP/DELETE/ALTER" query.
203 * This function is called while clicking links
205 * @param object the link
206 * @param object the sql query to submit
208 * @return boolean whether to run the query or not
210 function confirmLink(theLink, theSqlQuery)
212 // Confirmation is not required in the configuration file
213 // or browser is Opera (crappy js implementation)
214 if (PMA_messages['strDoYouReally'] == '' || typeof(window.opera) != 'undefined') {
215 return true;
218 var is_confirmed = confirm(PMA_messages['strDoYouReally'] + ' :\n' + theSqlQuery);
219 if (is_confirmed) {
220 if ( $(theLink).hasClass('formLinkSubmit') ) {
221 var name = 'is_js_confirmed';
222 if ($(theLink).attr('href').indexOf('usesubform') != -1) {
223 name = 'subform[' + $(theLink).attr('href').substr('#').match(/usesubform\[(\d+)\]/i)[1] + '][is_js_confirmed]';
226 $(theLink).parents('form').append('<input type="hidden" name="' + name + '" value="1" />');
227 } else if ( typeof(theLink.href) != 'undefined' ) {
228 theLink.href += '&is_js_confirmed=1';
229 } else if ( typeof(theLink.form) != 'undefined' ) {
230 theLink.form.action += '?is_js_confirmed=1';
234 return is_confirmed;
235 } // end of the 'confirmLink()' function
239 * Displays a confirmation box before doing some action
241 * @param object the message to display
243 * @return boolean whether to run the query or not
245 * @todo used only by libraries/display_tbl.lib.php. figure out how it is used
246 * and replace with a jQuery equivalent
248 function confirmAction(theMessage)
250 // TODO: Confirmation is not required in the configuration file
251 // or browser is Opera (crappy js implementation)
252 if (typeof(window.opera) != 'undefined') {
253 return true;
256 var is_confirmed = confirm(theMessage);
258 return is_confirmed;
259 } // end of the 'confirmAction()' function
263 * Displays an error message if a "DROP DATABASE" statement is submitted
264 * while it isn't allowed, else confirms a "DROP/DELETE/ALTER" query before
265 * sumitting it if required.
266 * This function is called by the 'checkSqlQuery()' js function.
268 * @param object the form
269 * @param object the sql query textarea
271 * @return boolean whether to run the query or not
273 * @see checkSqlQuery()
275 function confirmQuery(theForm1, sqlQuery1)
277 // Confirmation is not required in the configuration file
278 if (PMA_messages['strDoYouReally'] == '') {
279 return true;
282 // "DROP DATABASE" statement isn't allowed
283 if (PMA_messages['strNoDropDatabases'] != '') {
284 var drop_re = new RegExp('(^|;)\\s*DROP\\s+(IF EXISTS\\s+)?DATABASE\\s', 'i');
285 if (drop_re.test(sqlQuery1.value)) {
286 alert(PMA_messages['strNoDropDatabases']);
287 theForm1.reset();
288 sqlQuery1.focus();
289 return false;
290 } // end if
291 } // end if
293 // Confirms a "DROP/DELETE/ALTER/TRUNCATE" statement
295 // TODO: find a way (if possible) to use the parser-analyser
296 // for this kind of verification
297 // For now, I just added a ^ to check for the statement at
298 // beginning of expression
300 var do_confirm_re_0 = new RegExp('^\\s*DROP\\s+(IF EXISTS\\s+)?(TABLE|DATABASE|PROCEDURE)\\s', 'i');
301 var do_confirm_re_1 = new RegExp('^\\s*ALTER\\s+TABLE\\s+((`[^`]+`)|([A-Za-z0-9_$]+))\\s+DROP\\s', 'i');
302 var do_confirm_re_2 = new RegExp('^\\s*DELETE\\s+FROM\\s', 'i');
303 var do_confirm_re_3 = new RegExp('^\\s*TRUNCATE\\s', 'i');
305 if (do_confirm_re_0.test(sqlQuery1.value)
306 || do_confirm_re_1.test(sqlQuery1.value)
307 || do_confirm_re_2.test(sqlQuery1.value)
308 || do_confirm_re_3.test(sqlQuery1.value)) {
309 var message = (sqlQuery1.value.length > 100)
310 ? sqlQuery1.value.substr(0, 100) + '\n ...'
311 : sqlQuery1.value;
312 var is_confirmed = confirm(PMA_messages['strDoYouReally'] + ' :\n' + message);
313 // statement is confirmed -> update the
314 // "is_js_confirmed" form field so the confirm test won't be
315 // run on the server side and allows to submit the form
316 if (is_confirmed) {
317 theForm1.elements['is_js_confirmed'].value = 1;
318 return true;
320 // statement is rejected -> do not submit the form
321 else {
322 window.focus();
323 sqlQuery1.focus();
324 return false;
325 } // end if (handle confirm box result)
326 } // end if (display confirm box)
328 return true;
329 } // end of the 'confirmQuery()' function
333 * Displays a confirmation box before disabling the BLOB repository for a given database.
334 * This function is called while clicking links
336 * @param object the database
338 * @return boolean whether to disable the repository or not
340 function confirmDisableRepository(theDB)
342 // Confirmation is not required in the configuration file
343 // or browser is Opera (crappy js implementation)
344 if (PMA_messages['strDoYouReally'] == '' || typeof(window.opera) != 'undefined') {
345 return true;
348 var is_confirmed = confirm(PMA_messages['strBLOBRepositoryDisableStrongWarning'] + '\n' + PMA_messages['strBLOBRepositoryDisableAreYouSure']);
350 return is_confirmed;
351 } // end of the 'confirmDisableBLOBRepository()' function
355 * Displays an error message if the user submitted the sql query form with no
356 * sql query, else checks for "DROP/DELETE/ALTER" statements
358 * @param object the form
360 * @return boolean always false
362 * @see confirmQuery()
364 function checkSqlQuery(theForm)
366 var sqlQuery = theForm.elements['sql_query'];
367 var isEmpty = 1;
369 var space_re = new RegExp('\\s+');
370 if (typeof(theForm.elements['sql_file']) != 'undefined' &&
371 theForm.elements['sql_file'].value.replace(space_re, '') != '') {
372 return true;
374 if (typeof(theForm.elements['sql_localfile']) != 'undefined' &&
375 theForm.elements['sql_localfile'].value.replace(space_re, '') != '') {
376 return true;
378 if (isEmpty && typeof(theForm.elements['id_bookmark']) != 'undefined' &&
379 (theForm.elements['id_bookmark'].value != null || theForm.elements['id_bookmark'].value != '') &&
380 theForm.elements['id_bookmark'].selectedIndex != 0
382 return true;
384 // Checks for "DROP/DELETE/ALTER" statements
385 if (sqlQuery.value.replace(space_re, '') != '') {
386 if (confirmQuery(theForm, sqlQuery)) {
387 return true;
388 } else {
389 return false;
392 theForm.reset();
393 isEmpty = 1;
395 if (isEmpty) {
396 sqlQuery.select();
397 alert(PMA_messages['strFormEmpty']);
398 sqlQuery.focus();
399 return false;
402 return true;
403 } // end of the 'checkSqlQuery()' function
406 * Check if a form's element is empty.
407 * An element containing only spaces is also considered empty
409 * @param object the form
410 * @param string the name of the form field to put the focus on
412 * @return boolean whether the form field is empty or not
414 function emptyCheckTheField(theForm, theFieldName)
416 var theField = theForm.elements[theFieldName];
417 var space_re = new RegExp('\\s+');
418 return (theField.value.replace(space_re, '') == '') ? 1 : 0;
419 } // end of the 'emptyCheckTheField()' function
423 * Check whether a form field is empty or not
425 * @param object the form
426 * @param string the name of the form field to put the focus on
428 * @return boolean whether the form field is empty or not
430 function emptyFormElements(theForm, theFieldName)
432 var theField = theForm.elements[theFieldName];
433 var isEmpty = emptyCheckTheField(theForm, theFieldName);
436 return isEmpty;
437 } // end of the 'emptyFormElements()' function
441 * Ensures a value submitted in a form is numeric and is in a range
443 * @param object the form
444 * @param string the name of the form field to check
445 * @param integer the minimum authorized value
446 * @param integer the maximum authorized value
448 * @return boolean whether a valid number has been submitted or not
450 function checkFormElementInRange(theForm, theFieldName, message, min, max)
452 var theField = theForm.elements[theFieldName];
453 var val = parseInt(theField.value);
455 if (typeof(min) == 'undefined') {
456 min = 0;
458 if (typeof(max) == 'undefined') {
459 max = Number.MAX_VALUE;
462 // It's not a number
463 if (isNaN(val)) {
464 theField.select();
465 alert(PMA_messages['strNotNumber']);
466 theField.focus();
467 return false;
469 // It's a number but it is not between min and max
470 else if (val < min || val > max) {
471 theField.select();
472 alert(message.replace('%d', val));
473 theField.focus();
474 return false;
476 // It's a valid number
477 else {
478 theField.value = val;
480 return true;
482 } // end of the 'checkFormElementInRange()' function
485 function checkTableEditForm(theForm, fieldsCnt)
487 // TODO: avoid sending a message if user just wants to add a line
488 // on the form but has not completed at least one field name
490 var atLeastOneField = 0;
491 var i, elm, elm2, elm3, val, id;
493 for (i=0; i<fieldsCnt; i++)
495 id = "#field_" + i + "_2";
496 elm = $(id);
497 val = elm.val()
498 if (val == 'VARCHAR' || val == 'CHAR' || val == 'BIT' || val == 'VARBINARY' || val == 'BINARY') {
499 elm2 = $("#field_" + i + "_3");
500 val = parseInt(elm2.val());
501 elm3 = $("#field_" + i + "_1");
502 if (isNaN(val) && elm3.val() != "") {
503 elm2.select();
504 alert(PMA_messages['strNotNumber']);
505 elm2.focus();
506 return false;
510 if (atLeastOneField == 0) {
511 id = "field_" + i + "_1";
512 if (!emptyCheckTheField(theForm, id)) {
513 atLeastOneField = 1;
517 if (atLeastOneField == 0) {
518 var theField = theForm.elements["field_0_1"];
519 alert(PMA_messages['strFormEmpty']);
520 theField.focus();
521 return false;
524 // at least this section is under jQuery
525 if ($("input.textfield[name='table']").val() == "") {
526 alert(PMA_messages['strFormEmpty']);
527 $("input.textfield[name='table']").focus();
528 return false;
532 return true;
533 } // enf of the 'checkTableEditForm()' function
537 * Ensures the choice between 'transmit', 'zipped', 'gzipped' and 'bzipped'
538 * checkboxes is consistant
540 * @param object the form
541 * @param string a code for the action that causes this function to be run
543 * @return boolean always true
545 function checkTransmitDump(theForm, theAction)
547 var formElts = theForm.elements;
549 // 'zipped' option has been checked
550 if (theAction == 'zip' && formElts['zip'].checked) {
551 if (!formElts['asfile'].checked) {
552 theForm.elements['asfile'].checked = true;
554 if (typeof(formElts['gzip']) != 'undefined' && formElts['gzip'].checked) {
555 theForm.elements['gzip'].checked = false;
557 if (typeof(formElts['bzip']) != 'undefined' && formElts['bzip'].checked) {
558 theForm.elements['bzip'].checked = false;
561 // 'gzipped' option has been checked
562 else if (theAction == 'gzip' && formElts['gzip'].checked) {
563 if (!formElts['asfile'].checked) {
564 theForm.elements['asfile'].checked = true;
566 if (typeof(formElts['zip']) != 'undefined' && formElts['zip'].checked) {
567 theForm.elements['zip'].checked = false;
569 if (typeof(formElts['bzip']) != 'undefined' && formElts['bzip'].checked) {
570 theForm.elements['bzip'].checked = false;
573 // 'bzipped' option has been checked
574 else if (theAction == 'bzip' && formElts['bzip'].checked) {
575 if (!formElts['asfile'].checked) {
576 theForm.elements['asfile'].checked = true;
578 if (typeof(formElts['zip']) != 'undefined' && formElts['zip'].checked) {
579 theForm.elements['zip'].checked = false;
581 if (typeof(formElts['gzip']) != 'undefined' && formElts['gzip'].checked) {
582 theForm.elements['gzip'].checked = false;
585 // 'transmit' option has been unchecked
586 else if (theAction == 'transmit' && !formElts['asfile'].checked) {
587 if (typeof(formElts['zip']) != 'undefined' && formElts['zip'].checked) {
588 theForm.elements['zip'].checked = false;
590 if ((typeof(formElts['gzip']) != 'undefined' && formElts['gzip'].checked)) {
591 theForm.elements['gzip'].checked = false;
593 if ((typeof(formElts['bzip']) != 'undefined' && formElts['bzip'].checked)) {
594 theForm.elements['bzip'].checked = false;
598 return true;
599 } // end of the 'checkTransmitDump()' function
601 $(document).ready(function() {
603 * Row marking in horizontal mode (use "live" so that it works also for
604 * next pages reached via AJAX); a tr may have the class noclick to remove
605 * this behavior.
607 $('table:not(.noclick) tr.odd:not(.noclick), table:not(.noclick) tr.even:not(.noclick)').live('click',function(e) {
608 // do not trigger when clicked on anchor
609 if ($(e.target).is('a, img, a *')) {
610 return;
612 var $tr = $(this);
614 // make the table unselectable (to prevent default highlighting when shift+click)
615 //$tr.parents('table').noSelect();
617 if (!e.shiftKey || last_clicked_row == -1) {
618 // usual click
620 // XXX: FF fires two click events for <label> (label and checkbox), so we need to handle this differently
621 var $checkbox = $tr.find(':checkbox');
622 if ($checkbox.length) {
623 // checkbox in a row, add or remove class depending on checkbox state
624 var checked = $checkbox.attr('checked');
625 if (!$(e.target).is(':checkbox, label')) {
626 checked = !checked;
627 $checkbox.attr('checked', checked);
629 if (checked) {
630 $tr.addClass('marked');
631 } else {
632 $tr.removeClass('marked');
634 last_click_checked = checked;
635 } else {
636 // normaln data table, just toggle class
637 $tr.toggleClass('marked');
638 last_click_checked = false;
641 // remember the last clicked row
642 last_clicked_row = last_click_checked ? $('tr.odd:not(.noclick), tr.even:not(.noclick)').index(this) : -1;
643 last_shift_clicked_row = -1;
644 } else {
645 // handle the shift click
646 PMA_clearSelection();
647 var start, end;
649 // clear last shift click result
650 if (last_shift_clicked_row >= 0) {
651 if (last_shift_clicked_row >= last_clicked_row) {
652 start = last_clicked_row;
653 end = last_shift_clicked_row;
654 } else {
655 start = last_shift_clicked_row;
656 end = last_clicked_row;
658 $tr.parent().find('tr.odd:not(.noclick), tr.even:not(.noclick)')
659 .slice(start, end + 1)
660 .removeClass('marked')
661 .find(':checkbox')
662 .attr('checked', false);
665 // handle new shift click
666 var curr_row = $('tr.odd:not(.noclick), tr.even:not(.noclick)').index(this);
667 if (curr_row >= last_clicked_row) {
668 start = last_clicked_row;
669 end = curr_row;
670 } else {
671 start = curr_row;
672 end = last_clicked_row;
674 $tr.parent().find('tr.odd:not(.noclick), tr.even:not(.noclick)')
675 .slice(start, end + 1)
676 .addClass('marked')
677 .find(':checkbox')
678 .attr('checked', true);
680 // remember the last shift clicked row
681 last_shift_clicked_row = curr_row;
686 * Add a date/time picker to each element that needs it
688 if ($.datetimepicker != undefined) {
689 $('.datefield, .datetimefield').each(function() {
690 PMA_addDatepicker($(this));
696 * True if last click is to check a row.
698 var last_click_checked = false;
701 * Zero-based index of last clicked row.
702 * Used to handle the shift + click event in the code above.
704 var last_clicked_row = -1;
707 * Zero-based index of last shift clicked row.
709 var last_shift_clicked_row = -1;
712 * Row highlighting in horizontal mode (use "live"
713 * so that it works also for pages reached via AJAX)
715 /*$(document).ready(function() {
716 $('tr.odd, tr.even').live('hover',function(event) {
717 var $tr = $(this);
718 $tr.toggleClass('hover',event.type=='mouseover');
719 $tr.children().toggleClass('hover',event.type=='mouseover');
721 })*/
724 * This array is used to remember mark status of rows in browse mode
726 var marked_row = new Array;
729 * marks all rows and selects its first checkbox inside the given element
730 * the given element is usaly a table or a div containing the table or tables
732 * @param container DOM element
734 function markAllRows( container_id )
737 $("#"+container_id).find("input:checkbox:enabled").attr('checked', 'checked')
738 .parents("tr").addClass("marked");
739 return true;
743 * marks all rows and selects its first checkbox inside the given element
744 * the given element is usaly a table or a div containing the table or tables
746 * @param container DOM element
748 function unMarkAllRows( container_id )
751 $("#"+container_id).find("input:checkbox:enabled").removeAttr('checked')
752 .parents("tr").removeClass("marked");
753 return true;
757 * Checks/unchecks all checkbox in given conainer (f.e. a form, fieldset or div)
759 * @param string container_id the container id
760 * @param boolean state new value for checkbox (true or false)
761 * @return boolean always true
763 function setCheckboxes( container_id, state )
766 if(state) {
767 $("#"+container_id).find("input:checkbox").attr('checked', 'checked');
769 else {
770 $("#"+container_id).find("input:checkbox").removeAttr('checked');
773 return true;
774 } // end of the 'setCheckboxes()' function
777 * Checks/unchecks all options of a <select> element
779 * @param string the form name
780 * @param string the element name
781 * @param boolean whether to check or to uncheck options
783 * @return boolean always true
785 function setSelectOptions(the_form, the_select, do_check)
787 $("form[name='"+ the_form +"'] select[name='"+the_select+"']").find("option").attr('selected', do_check);
788 return true;
789 } // end of the 'setSelectOptions()' function
792 * Sets current value for query box.
794 function setQuery(query)
796 if (codemirror_editor) {
797 codemirror_editor.setValue(query);
798 } else {
799 document.sqlform.sql_query.value = query;
805 * Create quick sql statements.
808 function insertQuery(queryType)
810 if (queryType == "clear") {
811 setQuery('');
812 return;
815 var myQuery = document.sqlform.sql_query;
816 var query = "";
817 var myListBox = document.sqlform.dummy;
818 var table = document.sqlform.table.value;
820 if (myListBox.options.length > 0) {
821 sql_box_locked = true;
822 var chaineAj = "";
823 var valDis = "";
824 var editDis = "";
825 var NbSelect = 0;
826 for (var i=0; i < myListBox.options.length; i++) {
827 NbSelect++;
828 if (NbSelect > 1) {
829 chaineAj += ", ";
830 valDis += ",";
831 editDis += ",";
833 chaineAj += myListBox.options[i].value;
834 valDis += "[value-" + NbSelect + "]";
835 editDis += myListBox.options[i].value + "=[value-" + NbSelect + "]";
837 if (queryType == "selectall") {
838 query = "SELECT * FROM `" + table + "` WHERE 1";
839 } else if (queryType == "select") {
840 query = "SELECT " + chaineAj + " FROM `" + table + "` WHERE 1";
841 } else if (queryType == "insert") {
842 query = "INSERT INTO `" + table + "`(" + chaineAj + ") VALUES (" + valDis + ")";
843 } else if (queryType == "update") {
844 query = "UPDATE `" + table + "` SET " + editDis + " WHERE 1";
845 } else if(queryType == "delete") {
846 query = "DELETE FROM `" + table + "` WHERE 1";
848 setQuery(query);
849 sql_box_locked = false;
855 * Inserts multiple fields.
858 function insertValueQuery()
860 var myQuery = document.sqlform.sql_query;
861 var myListBox = document.sqlform.dummy;
863 if(myListBox.options.length > 0) {
864 sql_box_locked = true;
865 var chaineAj = "";
866 var NbSelect = 0;
867 for(var i=0; i<myListBox.options.length; i++) {
868 if (myListBox.options[i].selected) {
869 NbSelect++;
870 if (NbSelect > 1) {
871 chaineAj += ", ";
873 chaineAj += myListBox.options[i].value;
877 /* CodeMirror support */
878 if (codemirror_editor) {
879 codemirror_editor.replaceSelection(chaineAj);
880 //IE support
881 } else if (document.selection) {
882 myQuery.focus();
883 sel = document.selection.createRange();
884 sel.text = chaineAj;
885 document.sqlform.insert.focus();
887 //MOZILLA/NETSCAPE support
888 else if (document.sqlform.sql_query.selectionStart || document.sqlform.sql_query.selectionStart == "0") {
889 var startPos = document.sqlform.sql_query.selectionStart;
890 var endPos = document.sqlform.sql_query.selectionEnd;
891 var chaineSql = document.sqlform.sql_query.value;
893 myQuery.value = chaineSql.substring(0, startPos) + chaineAj + chaineSql.substring(endPos, chaineSql.length);
894 } else {
895 myQuery.value += chaineAj;
897 sql_box_locked = false;
902 * listbox redirection
904 function goToUrl(selObj, goToLocation)
906 eval("document.location.href = '" + goToLocation + "pos=" + selObj.options[selObj.selectedIndex].value + "'");
910 * Refresh the WYSIWYG scratchboard after changes have been made
912 function refreshDragOption(e)
914 var elm = $('#' + e);
915 if (elm.css('visibility') == 'visible') {
916 refreshLayout();
917 TableDragInit();
922 * Refresh/resize the WYSIWYG scratchboard
924 function refreshLayout()
926 var elm = $('#pdflayout')
927 var orientation = $('#orientation_opt').val();
928 if($('#paper_opt').length==1){
929 var paper = $('#paper_opt').val();
930 }else{
931 var paper = 'A4';
933 if (orientation == 'P') {
934 posa = 'x';
935 posb = 'y';
936 } else {
937 posa = 'y';
938 posb = 'x';
940 elm.css('width', pdfPaperSize(paper, posa) + 'px');
941 elm.css('height', pdfPaperSize(paper, posb) + 'px');
945 * Show/hide the WYSIWYG scratchboard
947 function ToggleDragDrop(e)
949 var elm = $('#' + e);
950 if (elm.css('visibility') == 'hidden') {
951 PDFinit(); /* Defined in pdf_pages.php */
952 elm.css('visibility', 'visible');
953 elm.css('display', 'block');
954 $('#showwysiwyg').val('1')
955 } else {
956 elm.css('visibility', 'hidden');
957 elm.css('display', 'none');
958 $('#showwysiwyg').val('0')
963 * PDF scratchboard: When a position is entered manually, update
964 * the fields inside the scratchboard.
966 function dragPlace(no, axis, value)
968 var elm = $('#table_' + no);
969 if (axis == 'x') {
970 elm.css('left', value + 'px');
971 } else {
972 elm.css('top', value + 'px');
977 * Returns paper sizes for a given format
979 function pdfPaperSize(format, axis)
981 switch (format.toUpperCase()) {
982 case '4A0':
983 if (axis == 'x') return 4767.87; else return 6740.79;
984 break;
985 case '2A0':
986 if (axis == 'x') return 3370.39; else return 4767.87;
987 break;
988 case 'A0':
989 if (axis == 'x') return 2383.94; else return 3370.39;
990 break;
991 case 'A1':
992 if (axis == 'x') return 1683.78; else return 2383.94;
993 break;
994 case 'A2':
995 if (axis == 'x') return 1190.55; else return 1683.78;
996 break;
997 case 'A3':
998 if (axis == 'x') return 841.89; else return 1190.55;
999 break;
1000 case 'A4':
1001 if (axis == 'x') return 595.28; else return 841.89;
1002 break;
1003 case 'A5':
1004 if (axis == 'x') return 419.53; else return 595.28;
1005 break;
1006 case 'A6':
1007 if (axis == 'x') return 297.64; else return 419.53;
1008 break;
1009 case 'A7':
1010 if (axis == 'x') return 209.76; else return 297.64;
1011 break;
1012 case 'A8':
1013 if (axis == 'x') return 147.40; else return 209.76;
1014 break;
1015 case 'A9':
1016 if (axis == 'x') return 104.88; else return 147.40;
1017 break;
1018 case 'A10':
1019 if (axis == 'x') return 73.70; else return 104.88;
1020 break;
1021 case 'B0':
1022 if (axis == 'x') return 2834.65; else return 4008.19;
1023 break;
1024 case 'B1':
1025 if (axis == 'x') return 2004.09; else return 2834.65;
1026 break;
1027 case 'B2':
1028 if (axis == 'x') return 1417.32; else return 2004.09;
1029 break;
1030 case 'B3':
1031 if (axis == 'x') return 1000.63; else return 1417.32;
1032 break;
1033 case 'B4':
1034 if (axis == 'x') return 708.66; else return 1000.63;
1035 break;
1036 case 'B5':
1037 if (axis == 'x') return 498.90; else return 708.66;
1038 break;
1039 case 'B6':
1040 if (axis == 'x') return 354.33; else return 498.90;
1041 break;
1042 case 'B7':
1043 if (axis == 'x') return 249.45; else return 354.33;
1044 break;
1045 case 'B8':
1046 if (axis == 'x') return 175.75; else return 249.45;
1047 break;
1048 case 'B9':
1049 if (axis == 'x') return 124.72; else return 175.75;
1050 break;
1051 case 'B10':
1052 if (axis == 'x') return 87.87; else return 124.72;
1053 break;
1054 case 'C0':
1055 if (axis == 'x') return 2599.37; else return 3676.54;
1056 break;
1057 case 'C1':
1058 if (axis == 'x') return 1836.85; else return 2599.37;
1059 break;
1060 case 'C2':
1061 if (axis == 'x') return 1298.27; else return 1836.85;
1062 break;
1063 case 'C3':
1064 if (axis == 'x') return 918.43; else return 1298.27;
1065 break;
1066 case 'C4':
1067 if (axis == 'x') return 649.13; else return 918.43;
1068 break;
1069 case 'C5':
1070 if (axis == 'x') return 459.21; else return 649.13;
1071 break;
1072 case 'C6':
1073 if (axis == 'x') return 323.15; else return 459.21;
1074 break;
1075 case 'C7':
1076 if (axis == 'x') return 229.61; else return 323.15;
1077 break;
1078 case 'C8':
1079 if (axis == 'x') return 161.57; else return 229.61;
1080 break;
1081 case 'C9':
1082 if (axis == 'x') return 113.39; else return 161.57;
1083 break;
1084 case 'C10':
1085 if (axis == 'x') return 79.37; else return 113.39;
1086 break;
1087 case 'RA0':
1088 if (axis == 'x') return 2437.80; else return 3458.27;
1089 break;
1090 case 'RA1':
1091 if (axis == 'x') return 1729.13; else return 2437.80;
1092 break;
1093 case 'RA2':
1094 if (axis == 'x') return 1218.90; else return 1729.13;
1095 break;
1096 case 'RA3':
1097 if (axis == 'x') return 864.57; else return 1218.90;
1098 break;
1099 case 'RA4':
1100 if (axis == 'x') return 609.45; else return 864.57;
1101 break;
1102 case 'SRA0':
1103 if (axis == 'x') return 2551.18; else return 3628.35;
1104 break;
1105 case 'SRA1':
1106 if (axis == 'x') return 1814.17; else return 2551.18;
1107 break;
1108 case 'SRA2':
1109 if (axis == 'x') return 1275.59; else return 1814.17;
1110 break;
1111 case 'SRA3':
1112 if (axis == 'x') return 907.09; else return 1275.59;
1113 break;
1114 case 'SRA4':
1115 if (axis == 'x') return 637.80; else return 907.09;
1116 break;
1117 case 'LETTER':
1118 if (axis == 'x') return 612.00; else return 792.00;
1119 break;
1120 case 'LEGAL':
1121 if (axis == 'x') return 612.00; else return 1008.00;
1122 break;
1123 case 'EXECUTIVE':
1124 if (axis == 'x') return 521.86; else return 756.00;
1125 break;
1126 case 'FOLIO':
1127 if (axis == 'x') return 612.00; else return 936.00;
1128 break;
1129 } // end switch
1131 return 0;
1135 * for playing media from the BLOB repository
1137 * @param var
1138 * @param var url_params main purpose is to pass the token
1139 * @param var bs_ref BLOB repository reference
1140 * @param var m_type type of BLOB repository media
1141 * @param var w_width width of popup window
1142 * @param var w_height height of popup window
1144 function popupBSMedia(url_params, bs_ref, m_type, is_cust_type, w_width, w_height)
1146 // if width not specified, use default
1147 if (w_width == undefined) {
1148 w_width = 640;
1151 // if height not specified, use default
1152 if (w_height == undefined) {
1153 w_height = 480;
1156 // open popup window (for displaying video/playing audio)
1157 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');
1161 * popups a request for changing MIME types for files in the BLOB repository
1163 * @param var db database name
1164 * @param var table table name
1165 * @param var reference BLOB repository reference
1166 * @param var current_mime_type current MIME type associated with BLOB repository reference
1168 function requestMIMETypeChange(db, table, reference, current_mime_type)
1170 // no mime type specified, set to default (nothing)
1171 if (undefined == current_mime_type) {
1172 current_mime_type = "";
1175 // prompt user for new mime type
1176 var new_mime_type = prompt("Enter custom MIME type", current_mime_type);
1178 // if new mime_type is specified and is not the same as the previous type, request for mime type change
1179 if (new_mime_type && new_mime_type != current_mime_type) {
1180 changeMIMEType(db, table, reference, new_mime_type);
1185 * changes MIME types for files in the BLOB repository
1187 * @param var db database name
1188 * @param var table table name
1189 * @param var reference BLOB repository reference
1190 * @param var mime_type new MIME type to be associated with BLOB repository reference
1192 function changeMIMEType(db, table, reference, mime_type)
1194 // specify url and parameters for jQuery POST
1195 var mime_chg_url = 'bs_change_mime_type.php';
1196 var params = {bs_db: db, bs_table: table, bs_reference: reference, bs_new_mime_type: mime_type};
1198 // jQuery POST
1199 jQuery.post(mime_chg_url, params);
1203 * Jquery Coding for inline editing SQL_QUERY
1205 $(document).ready(function(){
1206 $(".inline_edit_sql").live('click', function(){
1207 var server = $(this).prev().find("input[name='server']").val();
1208 var db = $(this).prev().find("input[name='db']").val();
1209 var table = $(this).prev().find("input[name='table']").val();
1210 var token = $(this).prev().find("input[name='token']").val();
1211 var sql_query = $(this).prev().find("input[name='sql_query']").val();
1212 var $inner_sql = $(this).parent().prev().find('.inner_sql');
1213 var old_text = $inner_sql.html();
1215 var new_content = "<textarea name=\"sql_query_edit\" id=\"sql_query_edit\">" + sql_query + "</textarea>\n";
1216 new_content += "<input type=\"button\" class=\"btnSave\" value=\"" + PMA_messages['strGo'] + "\">\n";
1217 new_content += "<input type=\"button\" class=\"btnDiscard\" value=\"" + PMA_messages['strCancel'] + "\">\n";
1218 $inner_sql.replaceWith(new_content);
1219 $(".btnSave").each(function(){
1220 $(this).click(function(){
1221 sql_query = $(this).prev().val();
1222 window.location.replace("import.php"
1223 + "?server=" + encodeURIComponent(server)
1224 + "&db=" + encodeURIComponent(db)
1225 + "&table=" + encodeURIComponent(table)
1226 + "&sql_query=" + encodeURIComponent(sql_query)
1227 + "&show_query=1"
1228 + "&token=" + token);
1231 $(".btnDiscard").each(function(){
1232 $(this).click(function(){
1233 $(this).closest(".sql").html("<span class=\"syntax\"><span class=\"inner_sql\">" + old_text + "</span></span>");
1236 return false;
1239 $('.sqlbutton').click(function(evt){
1240 insertQuery(evt.target.id);
1241 return false;
1244 $("#export_type").change(function(){
1245 if($("#export_type").val()=='svg'){
1246 $("#show_grid_opt").attr("disabled","disabled");
1247 $("#orientation_opt").attr("disabled","disabled");
1248 $("#with_doc").attr("disabled","disabled");
1249 $("#show_table_dim_opt").removeAttr("disabled");
1250 $("#all_table_same_wide").removeAttr("disabled");
1251 $("#paper_opt").removeAttr("disabled","disabled");
1252 $("#show_color_opt").removeAttr("disabled","disabled");
1253 //$(this).css("background-color","yellow");
1254 }else if($("#export_type").val()=='dia'){
1255 $("#show_grid_opt").attr("disabled","disabled");
1256 $("#with_doc").attr("disabled","disabled");
1257 $("#show_table_dim_opt").attr("disabled","disabled");
1258 $("#all_table_same_wide").attr("disabled","disabled");
1259 $("#paper_opt").removeAttr("disabled","disabled");
1260 $("#show_color_opt").removeAttr("disabled","disabled");
1261 $("#orientation_opt").removeAttr("disabled","disabled");
1262 }else if($("#export_type").val()=='eps'){
1263 $("#show_grid_opt").attr("disabled","disabled");
1264 $("#orientation_opt").removeAttr("disabled");
1265 $("#with_doc").attr("disabled","disabled");
1266 $("#show_table_dim_opt").attr("disabled","disabled");
1267 $("#all_table_same_wide").attr("disabled","disabled");
1268 $("#paper_opt").attr("disabled","disabled");
1269 $("#show_color_opt").attr("disabled","disabled");
1271 }else if($("#export_type").val()=='pdf'){
1272 $("#show_grid_opt").removeAttr("disabled");
1273 $("#orientation_opt").removeAttr("disabled");
1274 $("#with_doc").removeAttr("disabled","disabled");
1275 $("#show_table_dim_opt").removeAttr("disabled","disabled");
1276 $("#all_table_same_wide").removeAttr("disabled","disabled");
1277 $("#paper_opt").removeAttr("disabled","disabled");
1278 $("#show_color_opt").removeAttr("disabled","disabled");
1279 }else{
1280 // nothing
1284 $('#sqlquery').focus().keydown(function (e) {
1285 if (e.ctrlKey && e.keyCode == 13) {
1286 $("#sqlqueryform").submit();
1290 if ($('#input_username')) {
1291 if ($('#input_username').val() == '') {
1292 $('#input_username').focus();
1293 } else {
1294 $('#input_password').focus();
1300 * Show a message on the top of the page for an Ajax request
1302 * @param var message string containing the message to be shown.
1303 * optional, defaults to 'Loading...'
1304 * @param var timeout number of milliseconds for the message to be visible
1305 * optional, defaults to 5000
1306 * @return jQuery object jQuery Element that holds the message div
1308 function PMA_ajaxShowMessage(message, timeout)
1311 //Handle the case when a empty data.message is passed. We don't want the empty message
1312 if (message == '') {
1313 return true;
1314 } else if (! message) {
1315 // If the message is undefined, show the default
1316 message = PMA_messages['strLoading'];
1320 * @var timeout Number of milliseconds for which the message will be visible
1321 * @default 5000 ms
1323 if (! timeout) {
1324 timeout = 5000;
1327 // Create a parent element for the AJAX messages, if necessary
1328 if ($('#loading_parent').length == 0) {
1329 $('<div id="loading_parent"></div>')
1330 .insertBefore("#serverinfo");
1333 // Update message count to create distinct message elements every time
1334 ajax_message_count++;
1336 // Remove all old messages, if any
1337 $(".ajax_notification[id^=ajax_message_num]").remove();
1340 * @var $retval a jQuery object containing the reference
1341 * to the created AJAX message
1343 var $retval = $('<span class="ajax_notification" id="ajax_message_num_' + ajax_message_count + '"></span>')
1344 .hide()
1345 .appendTo("#loading_parent")
1346 .html(message)
1347 .fadeIn('medium')
1348 .delay(timeout)
1349 .fadeOut('medium', function() {
1350 $(this).remove();
1353 return $retval;
1357 * Removes the message shown for an Ajax operation when it's completed
1359 function PMA_ajaxRemoveMessage($this_msgbox)
1361 if ($this_msgbox != undefined && $this_msgbox instanceof jQuery) {
1362 $this_msgbox
1363 .stop(true, true)
1364 .fadeOut('medium');
1369 * Hides/shows the "Open in ENUM/SET editor" message, depending on the data type of the column currently selected
1371 function PMA_showNoticeForEnum(selectElement)
1373 var enum_notice_id = selectElement.attr("id").split("_")[1];
1374 enum_notice_id += "_" + (parseInt(selectElement.attr("id").split("_")[2]) + 1);
1375 var selectedType = selectElement.attr("value");
1376 if (selectedType == "ENUM" || selectedType == "SET") {
1377 $("p[id='enum_notice_" + enum_notice_id + "']").show();
1378 } else {
1379 $("p[id='enum_notice_" + enum_notice_id + "']").hide();
1384 * Generates a dialog box to pop up the create_table form
1386 function PMA_createTableDialog( div, url , target)
1389 * @var button_options Object that stores the options passed to jQueryUI
1390 * dialog
1392 var button_options = {};
1393 // in the following function we need to use $(this)
1394 button_options[PMA_messages['strCancel']] = function() {$(this).parent().dialog('close').remove();}
1396 var button_options_error = {};
1397 button_options_error[PMA_messages['strOK']] = function() {$(this).parent().dialog('close').remove();}
1399 var $msgbox = PMA_ajaxShowMessage();
1401 $.get( target , url , function(data) {
1402 //in the case of an error, show the error message returned.
1403 if (data.success != undefined && data.success == false) {
1405 .append(data.error)
1406 .dialog({
1407 title: PMA_messages['strCreateTable'],
1408 height: 230,
1409 width: 900,
1410 open: PMA_verifyTypeOfAllColumns,
1411 buttons : button_options_error
1412 })// end dialog options
1413 //remove the redundant [Back] link in the error message.
1414 .find('fieldset').remove();
1415 } else {
1417 .append(data)
1418 .dialog({
1419 title: PMA_messages['strCreateTable'],
1420 height: 600,
1421 width: 900,
1422 open: PMA_verifyTypeOfAllColumns,
1423 buttons : button_options
1424 }); // end dialog options
1426 PMA_ajaxRemoveMessage($msgbox);
1427 }) // end $.get()
1432 * Creates a highcharts chart in the given container
1434 * @param var settings object with highcharts properties that should be applied. (See also http://www.highcharts.com/ref/)
1435 * requires at least settings.chart.renderTo and settings.series to be set.
1436 * In addition there may be an additional property object 'realtime' that allows for realtime charting:
1437 * realtime: {
1438 * url: adress to get the data from (will always add token, ajax_request=1 and chart_data=1 to the GET request)
1439 * type: the GET request will also add type=[value of the type property] to the request
1440 * callback: Callback function that should draw the point, it's called with 4 parameters in this order:
1441 * - the chart object
1442 * - the current response value of the GET request, JSON parsed
1443 * - the previous response value of the GET request, JSON parsed
1444 * - the number of added points
1445 * error: Callback function when the get request fails. TODO: Apply callback on timeouts aswell
1448 * @return object The created highcharts instance
1450 function PMA_createChart(passedSettings)
1452 var container = passedSettings.chart.renderTo;
1454 var settings = {
1455 chart: {
1456 type: 'spline',
1457 marginRight: 10,
1458 backgroundColor: 'none',
1459 events: {
1460 /* Live charting support */
1461 load: function() {
1462 var thisChart = this;
1463 var lastValue = null, curValue = null;
1464 var numLoadedPoints = 0, otherSum = 0;
1465 var diff;
1467 // No realtime updates for graphs that are being exported, and disabled when realtime is not set
1468 // Also don't do live charting if we don't have the server time
1469 if(thisChart.options.chart.forExport == true ||
1470 ! thisChart.options.realtime ||
1471 ! thisChart.options.realtime.callback ||
1472 ! server_time_diff) return;
1474 thisChart.options.realtime.timeoutCallBack = function() {
1475 thisChart.options.realtime.postRequest = $.post(
1476 thisChart.options.realtime.url,
1477 thisChart.options.realtime.postData,
1478 function(data) {
1479 try {
1480 curValue = jQuery.parseJSON(data);
1481 } catch (err) {
1482 if(thisChart.options.realtime.error)
1483 thisChart.options.realtime.error(err);
1484 return;
1487 if (lastValue==null) {
1488 diff = curValue.x - thisChart.xAxis[0].getExtremes().max;
1489 } else {
1490 diff = parseInt(curValue.x - lastValue.x);
1493 thisChart.xAxis[0].setExtremes(
1494 thisChart.xAxis[0].getExtremes().min+diff,
1495 thisChart.xAxis[0].getExtremes().max+diff,
1496 false
1499 thisChart.options.realtime.callback(thisChart,curValue,lastValue,numLoadedPoints);
1501 lastValue = curValue;
1502 numLoadedPoints++;
1504 // Timeout has been cleared => don't start a new timeout
1505 if (chart_activeTimeouts[container] == null) {
1506 return;
1509 chart_activeTimeouts[container] = setTimeout(
1510 thisChart.options.realtime.timeoutCallBack,
1511 thisChart.options.realtime.refreshRate
1516 chart_activeTimeouts[container] = setTimeout(thisChart.options.realtime.timeoutCallBack, 5);
1520 plotOptions: {
1521 series: {
1522 marker: {
1523 radius: 3
1527 credits: {
1528 enabled:false
1530 xAxis: {
1531 type: 'datetime'
1533 yAxis: {
1534 min: 0,
1535 title: {
1536 text: PMA_messages['strTotalCount']
1538 plotLines: [{
1539 value: 0,
1540 width: 1,
1541 color: '#808080'
1544 tooltip: {
1545 formatter: function() {
1546 return '<b>' + this.series.name +'</b><br/>' +
1547 Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '<br/>' +
1548 Highcharts.numberFormat(this.y, 2);
1551 exporting: {
1552 enabled: true
1554 series: []
1557 /* Set/Get realtime chart default values */
1558 if(passedSettings.realtime) {
1559 if(!passedSettings.realtime.refreshRate) {
1560 passedSettings.realtime.refreshRate = 5000;
1563 if(!passedSettings.realtime.numMaxPoints) {
1564 passedSettings.realtime.numMaxPoints = 30;
1567 // Allow custom POST vars to be added
1568 passedSettings.realtime.postData = $.extend(false,{ ajax_request: true, chart_data: 1, type: passedSettings.realtime.type },passedSettings.realtime.postData);
1570 if(server_time_diff) {
1571 settings.xAxis.min = new Date().getTime() - server_time_diff - passedSettings.realtime.numMaxPoints * passedSettings.realtime.refreshRate;
1572 settings.xAxis.max = new Date().getTime() - server_time_diff + passedSettings.realtime.refreshRate;
1576 // Overwrite/Merge default settings with passedsettings
1577 $.extend(true,settings,passedSettings);
1579 return new Highcharts.Chart(settings);
1584 * Creates a Profiling Chart. Used in sql.php and server_status.js
1586 function PMA_createProfilingChart(data, options)
1588 return PMA_createChart($.extend(true, {
1589 chart: {
1590 renderTo: 'profilingchart',
1591 type: 'pie'
1593 title: { text:'', margin:0 },
1594 series: [{
1595 type: 'pie',
1596 name: PMA_messages['strQueryExecutionTime'],
1597 data: data
1599 plotOptions: {
1600 pie: {
1601 allowPointSelect: true,
1602 cursor: 'pointer',
1603 dataLabels: {
1604 enabled: true,
1605 distance: 35,
1606 formatter: function() {
1607 return '<b>'+ this.point.name +'</b><br/>'+ Highcharts.numberFormat(this.percentage, 2) +' %';
1612 tooltip: {
1613 formatter: function() {
1614 return '<b>'+ this.point.name +'</b><br/>'+PMA_prettyProfilingNum(this.y)+'<br/>('+Highcharts.numberFormat(this.percentage, 2) +' %)';
1617 },options));
1621 * Formats a profiling duration nicely (in us and ms time). Used in PMA_createProfilingChart() and server_status.js
1623 * @param integer Number to be formatted, should be in the range of microsecond to second
1624 * @param integer Acuracy, how many numbers right to the comma should be
1625 * @return string The formatted number
1627 function PMA_prettyProfilingNum(num, acc)
1629 if (!acc) {
1630 acc = 2;
1632 acc = Math.pow(10,acc);
1633 if (num * 1000 < 0.1) {
1634 num = Math.round(acc * (num * 1000 * 1000)) / acc + 'µ';
1635 } else if (num < 0.1) {
1636 num = Math.round(acc * (num * 1000)) / acc + 'm';
1637 } else {
1638 num = Math.round(acc * num) / acc;
1641 return num + 's';
1646 * Formats a SQL Query nicely with newlines and indentation. Depends on Codemirror and MySQL Mode!
1648 * @param string Query to be formatted
1649 * @return string The formatted query
1651 function PMA_SQLPrettyPrint(string)
1653 var mode = CodeMirror.getMode({},"text/x-mysql");
1654 var stream = new CodeMirror.StringStream(string);
1655 var state = mode.startState();
1656 var token, tokens = [];
1657 var output = '';
1658 var tabs = function(cnt) {
1659 var ret = '';
1660 for (var i=0; i<4*cnt; i++)
1661 ret += " ";
1662 return ret;
1665 // "root-level" statements
1666 var statements = {
1667 'select': ['select', 'from','on','where','having','limit','order by','group by'],
1668 'update': ['update', 'set','where'],
1669 'insert into': ['insert into', 'values']
1671 // don't put spaces before these tokens
1672 var spaceExceptionsBefore = { ';':true, ',': true, '.': true, '(': true };
1673 // don't put spaces after these tokens
1674 var spaceExceptionsAfter = { '.': true };
1676 // Populate tokens array
1677 var str='';
1678 while (! stream.eol()) {
1679 stream.start = stream.pos;
1680 token = mode.token(stream, state);
1681 if(token != null) {
1682 tokens.push([token, stream.current().toLowerCase()]);
1686 var currentStatement = tokens[0][1];
1688 if(! statements[currentStatement]) {
1689 return string;
1691 // Holds all currently opened code blocks (statement, function or generic)
1692 var blockStack = [];
1693 // Holds the type of block from last iteration (the current is in blockStack[0])
1694 var previousBlock;
1695 // If a new code block is found, newBlock contains its type for one iteration and vice versa for endBlock
1696 var newBlock, endBlock;
1697 // How much to indent in the current line
1698 var indentLevel = 0;
1699 // Holds the "root-level" statements
1700 var statementPart, lastStatementPart = statements[currentStatement][0];
1702 blockStack.unshift('statement');
1704 // Iterate through every token and format accordingly
1705 for (var i = 0; i < tokens.length; i++) {
1706 previousBlock = blockStack[0];
1708 // New block => push to stack
1709 if (tokens[i][1] == '(') {
1710 if (i < tokens.length - 1 && tokens[i+1][0] == 'statement-verb') {
1711 blockStack.unshift(newBlock = 'statement');
1712 } else if (i > 0 && tokens[i-1][0] == 'builtin') {
1713 blockStack.unshift(newBlock = 'function');
1714 } else {
1715 blockStack.unshift(newBlock = 'generic');
1717 } else {
1718 newBlock = null;
1721 // Block end => pop from stack
1722 if (tokens[i][1] == ')') {
1723 endBlock = blockStack[0];
1724 blockStack.shift();
1725 } else {
1726 endBlock = null;
1729 // A subquery is starting
1730 if (i > 0 && newBlock == 'statement') {
1731 indentLevel++;
1732 output += "\n" + tabs(indentLevel) + tokens[i][1] + ' ' + tokens[i+1][1].toUpperCase() + "\n" + tabs(indentLevel + 1);
1733 currentStatement = tokens[i+1][1];
1734 i++;
1735 continue;
1738 // A subquery is ending
1739 if (endBlock == 'statement' && indentLevel > 0) {
1740 output += "\n" + tabs(indentLevel);
1741 indentLevel--;
1744 // One less indentation for statement parts (from, where, order by, etc.) and a newline
1745 statementPart = statements[currentStatement].indexOf(tokens[i][1]);
1746 if (statementPart != -1) {
1747 if (i > 0) output += "\n";
1748 output += tabs(indentLevel) + tokens[i][1].toUpperCase();
1749 output += "\n" + tabs(indentLevel + 1);
1750 lastStatementPart = tokens[i][1];
1752 // Normal indentatin and spaces for everything else
1753 else {
1754 if (! spaceExceptionsBefore[tokens[i][1]]
1755 && ! (i > 0 && spaceExceptionsAfter[tokens[i-1][1]])
1756 && output.charAt(output.length -1) != ' ' ) {
1757 output += " ";
1759 if (tokens[i][0] == 'keyword') {
1760 output += tokens[i][1].toUpperCase();
1761 } else {
1762 output += tokens[i][1];
1766 // split columns in select and 'update set' clauses, but only inside statements blocks
1767 if (( lastStatementPart == 'select' || lastStatementPart == 'where' || lastStatementPart == 'set')
1768 && tokens[i][1]==',' && blockStack[0] == 'statement') {
1770 output += "\n" + tabs(indentLevel + 1);
1773 // split conditions in where clauses, but only inside statements blocks
1774 if (lastStatementPart == 'where'
1775 && (tokens[i][1]=='and' || tokens[i][1]=='or' || tokens[i][1]=='xor')) {
1777 if (blockStack[0] == 'statement') {
1778 output += "\n" + tabs(indentLevel + 1);
1780 // Todo: Also split and or blocks in newlines & identation++
1781 //if(blockStack[0] == 'generic')
1782 // output += ...
1785 return output;
1789 * jQuery function that uses jQueryUI's dialogs to confirm with user. Does not
1790 * return a jQuery object yet and hence cannot be chained
1792 * @param string question
1793 * @param string url URL to be passed to the callbackFn to make
1794 * an Ajax call to
1795 * @param function callbackFn callback to execute after user clicks on OK
1798 jQuery.fn.PMA_confirm = function(question, url, callbackFn) {
1799 if (PMA_messages['strDoYouReally'] == '') {
1800 return true;
1804 * @var button_options Object that stores the options passed to jQueryUI
1805 * dialog
1807 var button_options = {};
1808 button_options[PMA_messages['strOK']] = function(){
1809 $(this).dialog("close").remove();
1811 if($.isFunction(callbackFn)) {
1812 callbackFn.call(this, url);
1815 button_options[PMA_messages['strCancel']] = function() {$(this).dialog("close").remove();}
1817 $('<div id="confirm_dialog"></div>')
1818 .prepend(question)
1819 .dialog({buttons: button_options});
1823 * jQuery function to sort a table's body after a new row has been appended to it.
1824 * Also fixes the even/odd classes of the table rows at the end.
1826 * @param string text_selector string to select the sortKey's text
1828 * @return jQuery Object for chaining purposes
1830 jQuery.fn.PMA_sort_table = function(text_selector) {
1831 return this.each(function() {
1834 * @var table_body Object referring to the table's <tbody> element
1836 var table_body = $(this);
1838 * @var rows Object referring to the collection of rows in {@link table_body}
1840 var rows = $(this).find('tr').get();
1842 //get the text of the field that we will sort by
1843 $.each(rows, function(index, row) {
1844 row.sortKey = $.trim($(row).find(text_selector).text().toLowerCase());
1847 //get the sorted order
1848 rows.sort(function(a,b) {
1849 if(a.sortKey < b.sortKey) {
1850 return -1;
1852 if(a.sortKey > b.sortKey) {
1853 return 1;
1855 return 0;
1858 //pull out each row from the table and then append it according to it's order
1859 $.each(rows, function(index, row) {
1860 $(table_body).append(row);
1861 row.sortKey = null;
1864 //Re-check the classes of each row
1865 $(this).find('tr:odd')
1866 .removeClass('even').addClass('odd')
1867 .end()
1868 .find('tr:even')
1869 .removeClass('odd').addClass('even');
1874 * jQuery coding for 'Create Table'. Used on db_operations.php,
1875 * db_structure.php and db_tracking.php (i.e., wherever
1876 * libraries/display_create_table.lib.php is used)
1878 * Attach Ajax Event handlers for Create Table
1880 $(document).ready(function() {
1883 * Attach event handler to the submit action of the create table minimal form
1884 * and retrieve the full table form and display it in a dialog
1886 * @uses PMA_ajaxShowMessage()
1888 $("#create_table_form_minimal.ajax").live('submit', function(event) {
1889 event.preventDefault();
1890 $form = $(this);
1891 PMA_prepareForAjaxRequest($form);
1893 /*variables which stores the common attributes*/
1894 var url = $form.serialize();
1895 var action = $form.attr('action');
1896 var div = $('<div id="create_table_dialog"></div>');
1898 /*Calling to the createTableDialog function*/
1899 PMA_createTableDialog(div, url, action);
1901 // empty table name and number of columns from the minimal form
1902 $form.find('input[name=table],input[name=num_fields]').val('');
1906 * Attach event handler for submission of create table form (save)
1908 * @uses PMA_ajaxShowMessage()
1909 * @uses $.PMA_sort_table()
1912 // .live() must be called after a selector, see http://api.jquery.com/live
1913 $("#create_table_form input[name=do_save_data]").live('click', function(event) {
1914 event.preventDefault();
1917 * @var the_form object referring to the create table form
1919 var $form = $("#create_table_form");
1922 * First validate the form; if there is a problem, avoid submitting it
1924 * checkTableEditForm() needs a pure element and not a jQuery object,
1925 * this is why we pass $form[0] as a parameter (the jQuery object
1926 * is actually an array of DOM elements)
1929 if (checkTableEditForm($form[0], $form.find('input[name=orig_num_fields]').val())) {
1930 // OK, form passed validation step
1931 if ($form.hasClass('ajax')) {
1932 PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
1933 PMA_prepareForAjaxRequest($form);
1934 //User wants to submit the form
1935 $.post($form.attr('action'), $form.serialize() + "&do_save_data=" + $(this).val(), function(data) {
1936 if(data.success == true) {
1937 $('#properties_message')
1938 .removeClass('error')
1939 .html('');
1940 PMA_ajaxShowMessage(data.message);
1941 // Only if the create table dialog (distinct panel) exists
1942 if ($("#create_table_dialog").length > 0) {
1943 $("#create_table_dialog").dialog("close").remove();
1947 * @var tables_table Object referring to the <tbody> element that holds the list of tables
1949 var tables_table = $("#tablesForm").find("tbody").not("#tbl_summary_row");
1950 // this is the first table created in this db
1951 if (tables_table.length == 0) {
1952 if (window.parent && window.parent.frame_content) {
1953 window.parent.frame_content.location.reload();
1955 } else {
1957 * @var curr_last_row Object referring to the last <tr> element in {@link tables_table}
1959 var curr_last_row = $(tables_table).find('tr:last');
1961 * @var curr_last_row_index_string String containing the index of {@link curr_last_row}
1963 var curr_last_row_index_string = $(curr_last_row).find('input:checkbox').attr('id').match(/\d+/)[0];
1965 * @var curr_last_row_index Index of {@link curr_last_row}
1967 var curr_last_row_index = parseFloat(curr_last_row_index_string);
1969 * @var new_last_row_index Index of the new row to be appended to {@link tables_table}
1971 var new_last_row_index = curr_last_row_index + 1;
1973 * @var new_last_row_id String containing the id of the row to be appended to {@link tables_table}
1975 var new_last_row_id = 'checkbox_tbl_' + new_last_row_index;
1977 data.new_table_string = data.new_table_string.replace(/checkbox_tbl_/, new_last_row_id);
1978 //append to table
1979 $(data.new_table_string)
1980 .appendTo(tables_table);
1982 //Sort the table
1983 $(tables_table).PMA_sort_table('th');
1986 //Refresh navigation frame as a new table has been added
1987 if (window.parent && window.parent.frame_navigation) {
1988 window.parent.frame_navigation.location.reload();
1990 } else {
1991 $('#properties_message')
1992 .addClass('error')
1993 .html(data.error);
1994 // scroll to the div containing the error message
1995 $('#properties_message')[0].scrollIntoView();
1997 }) // end $.post()
1998 } // end if ($form.hasClass('ajax')
1999 else {
2000 // non-Ajax submit
2001 $form.append('<input type="hidden" name="do_save_data" value="save" />');
2002 $form.submit();
2004 } // end if (checkTableEditForm() )
2005 }) // end create table form (save)
2008 * Attach event handler for create table form (add fields)
2010 * @uses PMA_ajaxShowMessage()
2011 * @uses $.PMA_sort_table()
2012 * @uses window.parent.refreshNavigation()
2015 // .live() must be called after a selector, see http://api.jquery.com/live
2016 $("#create_table_form.ajax input[name=submit_num_fields]").live('click', function(event) {
2017 event.preventDefault();
2020 * @var the_form object referring to the create table form
2022 var $form = $("#create_table_form");
2024 var $msgbox = PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
2025 PMA_prepareForAjaxRequest($form);
2027 //User wants to add more fields to the table
2028 $.post($form.attr('action'), $form.serialize() + "&submit_num_fields=" + $(this).val(), function(data) {
2029 // if 'create_table_dialog' exists
2030 if ($("#create_table_dialog").length > 0) {
2031 $("#create_table_dialog").html(data);
2033 // if 'create_table_div' exists
2034 if ($("#create_table_div").length > 0) {
2035 $("#create_table_div").html(data);
2037 PMA_verifyTypeOfAllColumns();
2038 PMA_ajaxRemoveMessage($msgbox);
2039 }) //end $.post()
2041 }) // end create table form (add fields)
2043 }, 'top.frame_content'); //end $(document).ready for 'Create Table'
2046 * jQuery coding for 'Change Table' and 'Add Column'. Used on tbl_structure.php *
2047 * Attach Ajax Event handlers for Change Table
2049 $(document).ready(function() {
2051 *Ajax action for submitting the "Column Change" and "Add Column" form
2053 $("#append_fields_form input[name=do_save_data]").live('click', function(event) {
2054 event.preventDefault();
2056 * @var the_form object referring to the export form
2058 var $form = $("#append_fields_form");
2061 * First validate the form; if there is a problem, avoid submitting it
2063 * checkTableEditForm() needs a pure element and not a jQuery object,
2064 * this is why we pass $form[0] as a parameter (the jQuery object
2065 * is actually an array of DOM elements)
2067 if (checkTableEditForm($form[0], $form.find('input[name=orig_num_fields]').val())) {
2068 // OK, form passed validation step
2069 if ($form.hasClass('ajax')) {
2070 PMA_prepareForAjaxRequest($form);
2071 //User wants to submit the form
2072 $.post($form.attr('action'), $form.serialize()+"&do_save_data=Save", function(data) {
2073 if ($("#sqlqueryresults").length != 0) {
2074 $("#sqlqueryresults").remove();
2075 } else if ($(".error").length != 0) {
2076 $(".error").remove();
2078 if (data.success == true) {
2079 PMA_ajaxShowMessage(data.message);
2080 $("<div id='sqlqueryresults'></div>").insertAfter("#topmenucontainer");
2081 $("#sqlqueryresults").html(data.sql_query);
2082 $("#result_query .notice").remove();
2083 $("#result_query").prepend((data.message));
2084 if ($("#change_column_dialog").length > 0) {
2085 $("#change_column_dialog").dialog("close").remove();
2086 } else if ($("#add_columns").length > 0) {
2087 $("#add_columns").dialog("close").remove();
2089 /*Reload the field form*/
2090 $.post($("#fieldsForm").attr('action'), $("#fieldsForm").serialize()+"&ajax_request=true", function(form_data) {
2091 $("#fieldsForm").remove();
2092 $("#addColumns").remove();
2093 var $temp_div = $("<div id='temp_div'><div>").append(form_data);
2094 if ($("#sqlqueryresults").length != 0) {
2095 $temp_div.find("#fieldsForm").insertAfter("#sqlqueryresults");
2096 } else {
2097 $temp_div.find("#fieldsForm").insertAfter(".error");
2099 $temp_div.find("#addColumns").insertBefore("iframe.IE_hack");
2100 /*Call the function to display the more options in table*/
2101 displayMoreTableOpts();
2103 } else {
2104 var $temp_div = $("<div id='temp_div'><div>").append(data);
2105 var $error = $temp_div.find(".error code").addClass("error");
2106 PMA_ajaxShowMessage($error);
2108 }) // end $.post()
2109 } else {
2110 // non-Ajax submit
2111 $form.append('<input type="hidden" name="do_save_data" value="Save" />');
2112 $form.submit();
2115 }) // end change table button "do_save_data"
2117 }, 'top.frame_content'); //end $(document).ready for 'Change Table'
2120 * jQuery coding for 'Table operations'. Used on tbl_operations.php
2121 * Attach Ajax Event handlers for Table operations
2123 $(document).ready(function() {
2125 *Ajax action for submitting the "Alter table order by"
2127 $("#alterTableOrderby.ajax").live('submit', function(event) {
2128 event.preventDefault();
2129 var $form = $(this);
2131 PMA_prepareForAjaxRequest($form);
2132 /*variables which stores the common attributes*/
2133 $.post($form.attr('action'), $form.serialize()+"&submitorderby=Go", function(data) {
2134 if ($("#sqlqueryresults").length != 0) {
2135 $("#sqlqueryresults").remove();
2137 if ($("#result_query").length != 0) {
2138 $("#result_query").remove();
2140 if (data.success == true) {
2141 PMA_ajaxShowMessage(data.message);
2142 $("<div id='sqlqueryresults'></div>").insertAfter("#topmenucontainer");
2143 $("#sqlqueryresults").html(data.sql_query);
2144 $("#result_query .notice").remove();
2145 $("#result_query").prepend((data.message));
2146 } else {
2147 var $temp_div = $("<div id='temp_div'></div>")
2148 $temp_div.html(data.error);
2149 var $error = $temp_div.find("code").addClass("error");
2150 PMA_ajaxShowMessage($error);
2152 }) // end $.post()
2153 });//end of alterTableOrderby ajax submit
2156 *Ajax action for submitting the "Copy table"
2158 $("#copyTable.ajax input[name='submit_copy']").live('click', function(event) {
2159 event.preventDefault();
2160 var $form = $("#copyTable");
2161 if($form.find("input[name='switch_to_new']").attr('checked')) {
2162 $form.append('<input type="hidden" name="submit_copy" value="Go" />');
2163 $form.removeClass('ajax');
2164 $form.find("#ajax_request_hidden").remove();
2165 $form.submit();
2166 } else {
2167 PMA_prepareForAjaxRequest($form);
2168 /*variables which stores the common attributes*/
2169 $.post($form.attr('action'), $form.serialize()+"&submit_copy=Go", function(data) {
2170 if ($("#sqlqueryresults").length != 0) {
2171 $("#sqlqueryresults").remove();
2173 if ($("#result_query").length != 0) {
2174 $("#result_query").remove();
2176 if (data.success == true) {
2177 PMA_ajaxShowMessage(data.message);
2178 $("<div id='sqlqueryresults'></div>").insertAfter("#topmenucontainer");
2179 $("#sqlqueryresults").html(data.sql_query);
2180 $("#result_query .notice").remove();
2181 $("#result_query").prepend((data.message));
2182 $("#copyTable").find("select[name='target_db'] option[value="+data.db+"]").attr('selected', 'selected');
2184 //Refresh navigation frame when the table is coppied
2185 if (window.parent && window.parent.frame_navigation) {
2186 window.parent.frame_navigation.location.reload();
2188 } else {
2189 var $temp_div = $("<div id='temp_div'></div>");
2190 $temp_div.html(data.error);
2191 var $error = $temp_div.find("code").addClass("error");
2192 PMA_ajaxShowMessage($error);
2194 }) // end $.post()
2196 });//end of copyTable ajax submit
2199 *Ajax events for actions in the "Table maintenance"
2201 $("#tbl_maintenance.ajax li a.maintain_action").live('click', function(event) {
2202 event.preventDefault();
2203 var $link = $(this);
2204 var href = $link.attr("href");
2205 href = href.split('?');
2206 if ($("#sqlqueryresults").length != 0) {
2207 $("#sqlqueryresults").remove();
2209 if ($("#result_query").length != 0) {
2210 $("#result_query").remove();
2212 //variables which stores the common attributes
2213 $.post(href[0], href[1]+"&ajax_request=true", function(data) {
2214 if (data.success == undefined) {
2215 var $temp_div = $("<div id='temp_div'></div>");
2216 $temp_div.html(data);
2217 var $success = $temp_div.find("#result_query .success");
2218 PMA_ajaxShowMessage($success);
2219 $("<div id='sqlqueryresults' class='ajax'></div>").insertAfter("#topmenucontainer");
2220 $("#sqlqueryresults").html(data);
2221 PMA_init_slider();
2222 $("#sqlqueryresults").children("fieldset").remove();
2223 } else if (data.success == true ) {
2224 PMA_ajaxShowMessage(data.message);
2225 $("<div id='sqlqueryresults' class='ajax'></div>").insertAfter("#topmenucontainer");
2226 $("#sqlqueryresults").html(data.sql_query);
2227 } else {
2228 var $temp_div = $("<div id='temp_div'></div>");
2229 $temp_div.html(data.error);
2230 var $error = $temp_div.find("code").addClass("error");
2231 PMA_ajaxShowMessage($error);
2233 }) // end $.post()
2234 });//end of table maintanance ajax click
2236 }, 'top.frame_content'); //end $(document).ready for 'Table operations'
2240 * Attach Ajax event handlers for Drop Database. Moved here from db_structure.js
2241 * as it was also required on db_create.php
2243 * @uses $.PMA_confirm()
2244 * @uses PMA_ajaxShowMessage()
2245 * @uses window.parent.refreshNavigation()
2246 * @uses window.parent.refreshMain()
2247 * @see $cfg['AjaxEnable']
2249 $(document).ready(function() {
2250 $("#drop_db_anchor").live('click', function(event) {
2251 event.preventDefault();
2253 //context is top.frame_content, so we need to use window.parent.db to access the db var
2255 * @var question String containing the question to be asked for confirmation
2257 var question = PMA_messages['strDropDatabaseStrongWarning'] + '\n' + PMA_messages['strDoYouReally'] + ' :\n' + 'DROP DATABASE ' + window.parent.db;
2259 $(this).PMA_confirm(question, $(this).attr('href') ,function(url) {
2261 PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
2262 $.get(url, {'is_js_confirmed': '1', 'ajax_request': true}, function(data) {
2263 //Database deleted successfully, refresh both the frames
2264 window.parent.refreshNavigation();
2265 window.parent.refreshMain();
2266 }) // end $.get()
2267 }); // end $.PMA_confirm()
2268 }); //end of Drop Database Ajax action
2269 }) // end of $(document).ready() for Drop Database
2272 * Attach Ajax event handlers for 'Create Database'. Used wherever libraries/
2273 * display_create_database.lib.php is used, ie main.php and server_databases.php
2275 * @uses PMA_ajaxShowMessage()
2276 * @see $cfg['AjaxEnable']
2278 $(document).ready(function() {
2280 $('#create_database_form.ajax').live('submit', function(event) {
2281 event.preventDefault();
2283 $form = $(this);
2285 PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
2286 PMA_prepareForAjaxRequest($form);
2288 $.post($form.attr('action'), $form.serialize(), function(data) {
2289 if(data.success == true) {
2290 PMA_ajaxShowMessage(data.message);
2292 //Append database's row to table
2293 $("#tabledatabases")
2294 .find('tbody')
2295 .append(data.new_db_string)
2296 .PMA_sort_table('.name')
2297 .find('#db_summary_row')
2298 .appendTo('#tabledatabases tbody')
2299 .removeClass('odd even');
2301 var $databases_count_object = $('#databases_count');
2302 var databases_count = parseInt($databases_count_object.text());
2303 $databases_count_object.text(++databases_count);
2304 //Refresh navigation frame as a new database has been added
2305 if (window.parent && window.parent.frame_navigation) {
2306 window.parent.frame_navigation.location.reload();
2309 else {
2310 PMA_ajaxShowMessage(data.error);
2312 }) // end $.post()
2313 }) // end $().live()
2314 }) // end $(document).ready() for Create Database
2317 * Attach Ajax event handlers for 'Change Password' on main.php
2319 $(document).ready(function() {
2322 * Attach Ajax event handler on the change password anchor
2323 * @see $cfg['AjaxEnable']
2325 $('#change_password_anchor.dialog_active').live('click',function(event) {
2326 event.preventDefault();
2327 return false;
2329 $('#change_password_anchor.ajax').live('click', function(event) {
2330 event.preventDefault();
2331 $(this).removeClass('ajax').addClass('dialog_active');
2333 * @var button_options Object containing options to be passed to jQueryUI's dialog
2335 var button_options = {};
2336 button_options[PMA_messages['strCancel']] = function() {$(this).dialog('close').remove();}
2337 $.get($(this).attr('href'), {'ajax_request': true}, function(data) {
2338 $('<div id="change_password_dialog"></div>')
2339 .dialog({
2340 title: PMA_messages['strChangePassword'],
2341 width: 600,
2342 close: function(ev,ui) {$(this).remove();},
2343 buttons : button_options,
2344 beforeClose: function(ev,ui){ $('#change_password_anchor.dialog_active').removeClass('dialog_active').addClass('ajax')}
2346 .append(data);
2347 displayPasswordGenerateButton();
2348 }) // end $.get()
2349 }) // end handler for change password anchor
2352 * Attach Ajax event handler for Change Password form submission
2354 * @uses PMA_ajaxShowMessage()
2355 * @see $cfg['AjaxEnable']
2357 $("#change_password_form.ajax").find('input[name=change_pw]').live('click', function(event) {
2358 event.preventDefault();
2361 * @var the_form Object referring to the change password form
2363 var the_form = $("#change_password_form");
2366 * @var this_value String containing the value of the submit button.
2367 * Need to append this for the change password form on Server Privileges
2368 * page to work
2370 var this_value = $(this).val();
2372 var $msgbox = PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
2373 $(the_form).append('<input type="hidden" name="ajax_request" value="true" />');
2375 $.post($(the_form).attr('action'), $(the_form).serialize() + '&change_pw='+ this_value, function(data) {
2376 if(data.success == true) {
2377 $("#topmenucontainer").after(data.sql_query);
2378 $("#change_password_dialog").hide().remove();
2379 $("#edit_user_dialog").dialog("close").remove();
2380 $('#change_password_anchor.dialog_active').removeClass('dialog_active').addClass('ajax');
2381 PMA_ajaxRemoveMessage($msgbox);
2383 else {
2384 PMA_ajaxShowMessage(data.error);
2386 }) // end $.post()
2387 }) // end handler for Change Password form submission
2388 }) // end $(document).ready() for Change Password
2391 * Toggle the hiding/showing of the "Open in ENUM/SET editor" message when
2392 * the page loads and when the selected data type changes
2394 $(document).ready(function() {
2395 // is called here for normal page loads and also when opening
2396 // the Create table dialog
2397 PMA_verifyTypeOfAllColumns();
2399 // needs live() to work also in the Create Table dialog
2400 $("select[class='column_type']").live('change', function() {
2401 PMA_showNoticeForEnum($(this));
2405 function PMA_verifyTypeOfAllColumns()
2407 $("select[class='column_type']").each(function() {
2408 PMA_showNoticeForEnum($(this));
2413 * Closes the ENUM/SET editor and removes the data in it
2415 function disable_popup()
2417 $("#popup_background").fadeOut("fast");
2418 $("#enum_editor").fadeOut("fast");
2419 // clear the data from the text boxes
2420 $("#enum_editor #values input").remove();
2421 $("#enum_editor input[type='hidden']").remove();
2425 * Opens the ENUM/SET editor and controls its functions
2427 $(document).ready(function() {
2428 // Needs live() to work also in the Create table dialog
2429 $("a[class='open_enum_editor']").live('click', function() {
2430 // Center the popup
2431 var windowWidth = document.documentElement.clientWidth;
2432 var windowHeight = document.documentElement.clientHeight;
2433 var popupWidth = windowWidth/2;
2434 var popupHeight = windowHeight*0.8;
2435 var popupOffsetTop = windowHeight/2 - popupHeight/2;
2436 var popupOffsetLeft = windowWidth/2 - popupWidth/2;
2437 $("#enum_editor").css({"position":"absolute", "top": popupOffsetTop, "left": popupOffsetLeft, "width": popupWidth, "height": popupHeight});
2439 // Make it appear
2440 $("#popup_background").css({"opacity":"0.7"});
2441 $("#popup_background").fadeIn("fast");
2442 $("#enum_editor").fadeIn("fast");
2443 /**Replacing the column name in the enum editor header*/
2444 var column_name = $("#append_fields_form").find("input[id=field_0_1]").attr("value");
2445 var h3_text = $("#enum_editor h3").html();
2446 $("#enum_editor h3").html(h3_text.split('"')[0]+'"'+column_name+'"');
2448 // Get the values
2449 var values = $(this).parent().prev("input").attr("value").split(",");
2450 $.each(values, function(index, val) {
2451 if(jQuery.trim(val) != "") {
2452 // enclose the string in single quotes if it's not already
2453 if(val.substr(0, 1) != "'") {
2454 val = "'" + val;
2456 if(val.substr(val.length-1, val.length) != "'") {
2457 val = val + "'";
2459 // escape the single quotes, except the mandatory ones enclosing the entire string
2460 val = val.substr(1, val.length-2).replace(/''/g, "'").replace(/\\\\/g, '\\').replace(/\\'/g, "'").replace(/'/g, "&#039;");
2461 // escape the greater-than symbol
2462 val = val.replace(/>/g, "&gt;");
2463 $("#enum_editor #values").append("<input type='text' value=" + val + " />");
2466 // So we know which column's data is being edited
2467 $("#enum_editor").append("<input type='hidden' value='" + $(this).parent().prev("input").attr("id") + "' />");
2468 return false;
2471 // If the "close" link is clicked, close the enum editor
2472 // Needs live() to work also in the Create table dialog
2473 $("a[class='close_enum_editor']").live('click', function() {
2474 disable_popup();
2477 // If the "cancel" link is clicked, close the enum editor
2478 // Needs live() to work also in the Create table dialog
2479 $("a[class='cancel_enum_editor']").live('click', function() {
2480 disable_popup();
2483 // When "add a new value" is clicked, append an empty text field
2484 // Needs live() to work also in the Create table dialog
2485 $("a[class='add_value']").live('click', function() {
2486 $("#enum_editor #values").append("<input type='text' />");
2489 // When the submit button is clicked, put the data back into the original form
2490 // Needs live() to work also in the Create table dialog
2491 $("#enum_editor input[type='submit']").live('click', function() {
2492 var value_array = new Array();
2493 $.each($("#enum_editor #values input"), function(index, input_element) {
2494 val = jQuery.trim(input_element.value);
2495 if(val != "") {
2496 value_array.push("'" + val.replace(/\\/g, '\\\\').replace(/'/g, "''") + "'");
2499 // get the Length/Values text field where this value belongs
2500 var values_id = $("#enum_editor input[type='hidden']").attr("value");
2501 $("input[id='" + values_id + "']").attr("value", value_array.join(","));
2502 disable_popup();
2506 * Hides certain table structure actions, replacing them with the word "More". They are displayed
2507 * in a dropdown menu when the user hovers over the word "More."
2509 displayMoreTableOpts();
2512 function displayMoreTableOpts()
2514 // Remove the actions from the table cells (they are available by default for JavaScript-disabled browsers)
2515 // if the table is not a view or information_schema (otherwise there is only one action to hide and there's no point)
2516 if($("input[type='hidden'][name='table_type']").val() == "table") {
2517 var $table = $("table[id='tablestructure']");
2518 $table.find("td[class='browse']").remove();
2519 $table.find("td[class='primary']").remove();
2520 $table.find("td[class='unique']").remove();
2521 $table.find("td[class='index']").remove();
2522 $table.find("td[class='fulltext']").remove();
2523 $table.find("td[class='spatial']").remove();
2524 $table.find("th[class='action']").attr("colspan", 3);
2526 // Display the "more" text
2527 $table.find("td[class='more_opts']").show();
2529 // Position the dropdown
2530 $(".structure_actions_dropdown").each(function() {
2531 // Optimize DOM querying
2532 var $this_dropdown = $(this);
2533 // The top offset must be set for IE even if it didn't change
2534 var cell_right_edge_offset = $this_dropdown.parent().position().left + $this_dropdown.parent().innerWidth();
2535 var left_offset = cell_right_edge_offset - $this_dropdown.innerWidth();
2536 var top_offset = $this_dropdown.parent().position().top + $this_dropdown.parent().innerHeight();
2537 $this_dropdown.offset({ top: top_offset, left: left_offset });
2540 // A hack for IE6 to prevent the after_field select element from being displayed on top of the dropdown by
2541 // positioning an iframe directly on top of it
2542 var $after_field = $("select[name='after_field']");
2543 $("iframe[class='IE_hack']")
2544 .width($after_field.width())
2545 .height($after_field.height())
2546 .offset({
2547 top: $after_field.offset().top,
2548 left: $after_field.offset().left
2551 // When "more" is hovered over, show the hidden actions
2552 $table.find("td[class='more_opts']")
2553 .mouseenter(function() {
2554 if($.browser.msie && $.browser.version == "6.0") {
2555 $("iframe[class='IE_hack']")
2556 .show()
2557 .width($after_field.width()+4)
2558 .height($after_field.height()+4)
2559 .offset({
2560 top: $after_field.offset().top,
2561 left: $after_field.offset().left
2564 $(".structure_actions_dropdown").hide(); // Hide all the other ones that may be open
2565 $(this).children(".structure_actions_dropdown").show();
2566 // Need to do this again for IE otherwise the offset is wrong
2567 if($.browser.msie) {
2568 var left_offset_IE = $(this).offset().left + $(this).innerWidth() - $(this).children(".structure_actions_dropdown").innerWidth();
2569 var top_offset_IE = $(this).offset().top + $(this).innerHeight();
2570 $(this).children(".structure_actions_dropdown").offset({
2571 top: top_offset_IE,
2572 left: left_offset_IE });
2575 .mouseleave(function() {
2576 $(this).children(".structure_actions_dropdown").hide();
2577 if($.browser.msie && $.browser.version == "6.0") {
2578 $("iframe[class='IE_hack']").hide();
2584 $(document).ready(function(){
2585 PMA_convertFootnotesToTooltips();
2589 * Ensures indexes names are valid according to their type and, for a primary
2590 * key, lock index name to 'PRIMARY'
2591 * @param string form_id Variable which parses the form name as
2592 * the input
2593 * @return boolean false if there is no index form, true else
2595 function checkIndexName(form_id)
2597 if ($("#"+form_id).length == 0) {
2598 return false;
2601 // Gets the elements pointers
2602 var $the_idx_name = $("#input_index_name");
2603 var $the_idx_type = $("#select_index_type");
2605 // Index is a primary key
2606 if ($the_idx_type.find("option:selected").attr("value") == 'PRIMARY') {
2607 $the_idx_name.attr("value", 'PRIMARY');
2608 $the_idx_name.attr("disabled", true);
2611 // Other cases
2612 else {
2613 if ($the_idx_name.attr("value") == 'PRIMARY') {
2614 $the_idx_name.attr("value", '');
2616 $the_idx_name.attr("disabled", false);
2619 return true;
2620 } // end of the 'checkIndexName()' function
2623 * function to convert the footnotes to tooltips
2625 * @param jquery-Object $div a div jquery object which specifies the
2626 * domain for searching footnootes. If we
2627 * ommit this parameter the function searches
2628 * the footnotes in the whole body
2630 function PMA_convertFootnotesToTooltips($div)
2632 // Hide the footnotes from the footer (which are displayed for
2633 // JavaScript-disabled browsers) since the tooltip is sufficient
2635 if ($div == undefined || ! $div instanceof jQuery || $div.length == 0) {
2636 $div = $("#serverinfo").parent();
2639 $footnotes = $div.find(".footnotes");
2641 $footnotes.hide();
2642 $footnotes.find('span').each(function() {
2643 $(this).children("sup").remove();
2645 // The border and padding must be removed otherwise a thin yellow box remains visible
2646 $footnotes.css("border", "none");
2647 $footnotes.css("padding", "0px");
2649 // Replace the superscripts with the help icon
2650 $div.find("sup.footnotemarker").hide();
2651 $div.find("img.footnotemarker").show();
2653 $div.find("img.footnotemarker").each(function() {
2654 var img_class = $(this).attr("class");
2655 /** img contains two classes, as example "footnotemarker footnote_1".
2656 * We split it by second class and take it for the id of span
2658 img_class = img_class.split(" ");
2659 for (i = 0; i < img_class.length; i++) {
2660 if (img_class[i].split("_")[0] == "footnote") {
2661 var span_id = img_class[i].split("_")[1];
2665 * Now we get the #id of the span with span_id variable. As an example if we
2666 * initially get the img class as "footnotemarker footnote_2", now we get
2667 * #2 as the span_id. Using that we can find footnote_2 in footnotes.
2668 * */
2669 var tooltip_text = $footnotes.find("span[id='footnote_" + span_id + "']").html();
2670 $(this).qtip({
2671 content: tooltip_text,
2672 show: { delay: 0 },
2673 hide: { delay: 1000 },
2674 style: { background: '#ffffcc' }
2679 function menuResize()
2681 var cnt = $('#topmenu');
2682 var wmax = cnt.innerWidth() - 5; // 5 px margin for jumping menu in Chrome
2683 var submenu = cnt.find('.submenu');
2684 var submenu_w = submenu.outerWidth(true);
2685 var submenu_ul = submenu.find('ul');
2686 var li = cnt.find('> li');
2687 var li2 = submenu_ul.find('li');
2688 var more_shown = li2.length > 0;
2689 var w = more_shown ? submenu_w : 0;
2691 // hide menu items
2692 var hide_start = 0;
2693 for (var i = 0; i < li.length-1; i++) { // li.length-1: skip .submenu element
2694 var el = $(li[i]);
2695 var el_width = el.outerWidth(true);
2696 el.data('width', el_width);
2697 w += el_width;
2698 if (w > wmax) {
2699 w -= el_width;
2700 if (w + submenu_w < wmax) {
2701 hide_start = i;
2702 } else {
2703 hide_start = i-1;
2704 w -= $(li[i-1]).data('width');
2706 break;
2710 if (hide_start > 0) {
2711 for (var i = hide_start; i < li.length-1; i++) {
2712 $(li[i])[more_shown ? 'prependTo' : 'appendTo'](submenu_ul);
2714 submenu.addClass('shown');
2715 } else if (more_shown) {
2716 w -= submenu_w;
2717 // nothing hidden, maybe something can be restored
2718 for (var i = 0; i < li2.length; i++) {
2719 //console.log(li2[i], submenu_w);
2720 w += $(li2[i]).data('width');
2721 // item fits or (it is the last item and it would fit if More got removed)
2722 if (w+submenu_w < wmax || (i == li2.length-1 && w < wmax)) {
2723 $(li2[i]).insertBefore(submenu);
2724 if (i == li2.length-1) {
2725 submenu.removeClass('shown');
2727 continue;
2729 break;
2732 if (submenu.find('.tabactive').length) {
2733 submenu.addClass('active').find('> a').removeClass('tab').addClass('tabactive');
2734 } else {
2735 submenu.removeClass('active').find('> a').addClass('tab').removeClass('tabactive');
2739 $(function() {
2740 var topmenu = $('#topmenu');
2741 if (topmenu.length == 0) {
2742 return;
2744 // create submenu container
2745 var link = $('<a />', {href: '#', 'class': 'tab'})
2746 .text(PMA_messages['strMore'])
2747 .click(function(e) {
2748 e.preventDefault();
2750 var img = topmenu.find('li:first-child img');
2751 if (img.length) {
2752 img.clone().attr('class', 'icon ic_b_more').prependTo(link);
2754 var submenu = $('<li />', {'class': 'submenu'})
2755 .append(link)
2756 .append($('<ul />'))
2757 .mouseenter(function() {
2758 if ($(this).find('ul .tabactive').length == 0) {
2759 $(this).addClass('submenuhover').find('> a').addClass('tabactive');
2762 .mouseleave(function() {
2763 if ($(this).find('ul .tabactive').length == 0) {
2764 $(this).removeClass('submenuhover').find('> a').removeClass('tabactive');
2767 topmenu.append(submenu);
2769 // populate submenu and register resize event
2770 $(window).resize(menuResize);
2771 menuResize();
2775 * Get the row number from the classlist (for example, row_1)
2777 function PMA_getRowNumber(classlist)
2779 return parseInt(classlist.split(/\s+row_/)[1]);
2783 * Changes status of slider
2785 function PMA_set_status_label(id)
2787 if ($('#' + id).css('display') == 'none') {
2788 $('#anchor_status_' + id).text('+ ');
2789 } else {
2790 $('#anchor_status_' + id).text('- ');
2795 * Initializes slider effect.
2797 function PMA_init_slider()
2799 $('.pma_auto_slider').each(function(idx, e) {
2800 if ($(e).hasClass('slider_init_done')) return;
2801 $(e).addClass('slider_init_done');
2802 $('<span id="anchor_status_' + e.id + '"></span>')
2803 .insertBefore(e);
2804 PMA_set_status_label(e.id);
2806 $('<a href="#' + e.id + '" id="anchor_' + e.id + '">' + e.title + '</a>')
2807 .insertBefore(e)
2808 .click(function() {
2809 $('#' + e.id).toggle('clip', function() {
2810 PMA_set_status_label(e.id);
2812 return false;
2818 * var toggleButton This is a function that creates a toggle
2819 * sliding button given a jQuery reference
2820 * to the correct DOM element
2822 var toggleButton = function ($obj) {
2823 // In rtl mode the toggle switch is flipped horizontally
2824 // so we need to take that into account
2825 if ($('.text_direction', $obj).text() == 'ltr') {
2826 var right = 'right';
2827 } else {
2828 var right = 'left';
2831 * var h Height of the button, used to scale the
2832 * background image and position the layers
2834 var h = $obj.height();
2835 $('img', $obj).height(h);
2836 $('table', $obj).css('bottom', h-1);
2838 * var on Width of the "ON" part of the toggle switch
2839 * var off Width of the "OFF" part of the toggle switch
2841 var on = $('.toggleOn', $obj).width();
2842 var off = $('.toggleOff', $obj).width();
2843 // Make the "ON" and "OFF" parts of the switch the same size
2844 $('.toggleOn > div', $obj).width(Math.max(on, off));
2845 $('.toggleOff > div', $obj).width(Math.max(on, off));
2847 * var w Width of the central part of the switch
2849 var w = parseInt(($('img', $obj).height() / 16) * 22, 10);
2850 // Resize the central part of the switch on the top
2851 // layer to match the background
2852 $('table td:nth-child(2) > div', $obj).width(w);
2854 * var imgw Width of the background image
2855 * var tblw Width of the foreground layer
2856 * var offset By how many pixels to move the background
2857 * image, so that it matches the top layer
2859 var imgw = $('img', $obj).width();
2860 var tblw = $('table', $obj).width();
2861 var offset = parseInt(((imgw - tblw) / 2), 10);
2862 // Move the background to match the layout of the top layer
2863 $obj.find('img').css(right, offset);
2865 * var offw Outer width of the "ON" part of the toggle switch
2866 * var btnw Outer width of the central part of the switch
2868 var offw = $('.toggleOff', $obj).outerWidth();
2869 var btnw = $('table td:nth-child(2)', $obj).outerWidth();
2870 // Resize the main div so that exactly one side of
2871 // the switch plus the central part fit into it.
2872 $obj.width(offw + btnw + 2);
2874 * var move How many pixels to move the
2875 * switch by when toggling
2877 var move = $('.toggleOff', $obj).outerWidth();
2878 // If the switch is initialized to the
2879 // OFF state we need to move it now.
2880 if ($('.container', $obj).hasClass('off')) {
2881 if (right == 'right') {
2882 $('table, img', $obj).animate({'left': '-=' + move + 'px'}, 0);
2883 } else {
2884 $('table, img', $obj).animate({'left': '+=' + move + 'px'}, 0);
2887 // Attach an 'onclick' event to the switch
2888 $('.container', $obj).click(function () {
2889 if ($(this).hasClass('isActive')) {
2890 return false;
2891 } else {
2892 $(this).addClass('isActive');
2894 var $msg = PMA_ajaxShowMessage(PMA_messages['strLoading']);
2895 var $container = $(this);
2896 var callback = $('.callback', this).text();
2897 // Perform the actual toggle
2898 if ($(this).hasClass('on')) {
2899 if (right == 'right') {
2900 var operator = '-=';
2901 } else {
2902 var operator = '+=';
2904 var url = $(this).find('.toggleOff > span').text();
2905 var removeClass = 'on';
2906 var addClass = 'off';
2907 } else {
2908 if (right == 'right') {
2909 var operator = '+=';
2910 } else {
2911 var operator = '-=';
2913 var url = $(this).find('.toggleOn > span').text();
2914 var removeClass = 'off';
2915 var addClass = 'on';
2917 $.post(url, {'ajax_request': true}, function(data) {
2918 if(data.success == true) {
2919 PMA_ajaxRemoveMessage($msg);
2920 $container
2921 .removeClass(removeClass)
2922 .addClass(addClass)
2923 .animate({'left': operator + move + 'px'}, function () {
2924 $container.removeClass('isActive');
2926 eval(callback);
2927 } else {
2928 PMA_ajaxShowMessage(data.error);
2929 $container.removeClass('isActive');
2936 * Initialise all toggle buttons
2938 $(window).load(function () {
2939 $('.toggleAjax').each(function () {
2940 $(this)
2941 .show()
2942 .find('.toggleButton')
2943 toggleButton($(this));
2948 * Vertical pointer
2950 $(document).ready(function() {
2951 $('.vpointer').live('hover',
2952 //handlerInOut
2953 function(e) {
2954 var $this_td = $(this);
2955 var row_num = PMA_getRowNumber($this_td.attr('class'));
2956 // for all td of the same vertical row, toggle hover
2957 $('.vpointer').filter('.row_' + row_num).toggleClass('hover');
2960 }) // end of $(document).ready() for vertical pointer
2962 $(document).ready(function() {
2964 * Vertical marker
2966 $('.vmarker').live('click', function(e) {
2967 // do not trigger when clicked on anchor
2968 if ($(e.target).is('a, img, a *')) {
2969 return;
2972 var $this_td = $(this);
2973 var row_num = PMA_getRowNumber($this_td.attr('class'));
2975 // XXX: FF fires two click events for <label> (label and checkbox), so we need to handle this differently
2976 var $tr = $(this);
2977 var $checkbox = $('.vmarker').filter('.row_' + row_num + ':first').find(':checkbox');
2978 if ($checkbox.length) {
2979 // checkbox in a row, add or remove class depending on checkbox state
2980 var checked = $checkbox.attr('checked');
2981 if (!$(e.target).is(':checkbox, label')) {
2982 checked = !checked;
2983 $checkbox.attr('checked', checked);
2985 // for all td of the same vertical row, toggle the marked class
2986 if (checked) {
2987 $('.vmarker').filter('.row_' + row_num).addClass('marked');
2988 } else {
2989 $('.vmarker').filter('.row_' + row_num).removeClass('marked');
2991 } else {
2992 // normaln data table, just toggle class
2993 $('.vmarker').filter('.row_' + row_num).toggleClass('marked');
2998 * Reveal visual builder anchor
3001 $('#visual_builder_anchor').show();
3004 * Page selector in db Structure (non-AJAX)
3006 $('#tableslistcontainer').find('#pageselector').live('change', function() {
3007 $(this).parent("form").submit();
3011 * Page selector in navi panel (non-AJAX)
3013 $('#navidbpageselector').find('#pageselector').live('change', function() {
3014 $(this).parent("form").submit();
3018 * Page selector in browse_foreigners windows (non-AJAX)
3020 $('#body_browse_foreigners').find('#pageselector').live('change', function() {
3021 $(this).closest("form").submit();
3025 * Load version information asynchronously.
3027 if ($('.jsversioncheck').length > 0) {
3028 (function() {
3029 var s = document.createElement('script');
3030 s.type = 'text/javascript';
3031 s.async = true;
3032 s.src = 'http://www.phpmyadmin.net/home_page/version.js';
3033 s.onload = PMA_current_version;
3034 var x = document.getElementsByTagName('script')[0];
3035 x.parentNode.insertBefore(s, x);
3036 })();
3040 * Slider effect.
3042 PMA_init_slider();
3045 * Enables the text generated by PMA_linkOrButton() to be clickable
3047 $('a[class~="formLinkSubmit"]').live('click',function(e) {
3049 if($(this).attr('href').indexOf('=') != -1) {
3050 var data = $(this).attr('href').substr($(this).attr('href').indexOf('#')+1).split('=',2);
3051 $(this).parents('form').append('<input type="hidden" name="' + data[0] + '" value="' + data[1] + '"/>');
3053 $(this).parents('form').submit();
3054 return false;
3057 $('#update_recent_tables').ready(function() {
3058 if (window.parent.frame_navigation != undefined
3059 && window.parent.frame_navigation.PMA_reloadRecentTable != undefined)
3061 window.parent.frame_navigation.PMA_reloadRecentTable();
3065 }) // end of $(document).ready()
3068 * Creates a message inside an object with a sliding effect
3070 * @param msg A string containing the text to display
3071 * @param $obj a jQuery object containing the reference
3072 * to the element where to put the message
3073 * This is optional, if no element is
3074 * provided, one will be created below the
3075 * navigation links at the top of the page
3077 * @return bool True on success, false on failure
3079 function PMA_slidingMessage(msg, $obj)
3081 if (msg == undefined || msg.length == 0) {
3082 // Don't show an empty message
3083 return false;
3085 if ($obj == undefined || ! $obj instanceof jQuery || $obj.length == 0) {
3086 // If the second argument was not supplied,
3087 // we might have to create a new DOM node.
3088 if ($('#PMA_slidingMessage').length == 0) {
3089 $('#topmenucontainer')
3090 .after('<span id="PMA_slidingMessage" '
3091 + 'style="display: inline-block;"></span>');
3093 $obj = $('#PMA_slidingMessage');
3095 if ($obj.has('div').length > 0) {
3096 // If there already is a message inside the
3097 // target object, we must get rid of it
3098 $obj
3099 .find('div')
3100 .first()
3101 .fadeOut(function () {
3102 $obj
3103 .children()
3104 .remove();
3105 $obj
3106 .append('<div style="display: none;">' + msg + '</div>')
3107 .animate({
3108 height: $obj.find('div').first().height()
3110 .find('div')
3111 .first()
3112 .fadeIn();
3114 } else {
3115 // Object does not already have a message
3116 // inside it, so we simply slide it down
3117 var h = $obj
3118 .width('100%')
3119 .html('<div style="display: none;">' + msg + '</div>')
3120 .find('div')
3121 .first()
3122 .height();
3123 $obj
3124 .find('div')
3125 .first()
3126 .css('height', 0)
3127 .show()
3128 .animate({
3129 height: h
3130 }, function() {
3131 // Set the height of the parent
3132 // to the height of the child
3133 $obj
3134 .height(
3135 $obj
3136 .find('div')
3137 .first()
3138 .height()
3142 return true;
3143 } // end PMA_slidingMessage()
3146 * Attach Ajax event handlers for Drop Table.
3148 * @uses $.PMA_confirm()
3149 * @uses PMA_ajaxShowMessage()
3150 * @uses window.parent.refreshNavigation()
3151 * @uses window.parent.refreshMain()
3152 * @see $cfg['AjaxEnable']
3154 $(document).ready(function() {
3155 $("#drop_tbl_anchor").live('click', function(event) {
3156 event.preventDefault();
3158 //context is top.frame_content, so we need to use window.parent.table to access the table var
3160 * @var question String containing the question to be asked for confirmation
3162 var question = PMA_messages['strDropTableStrongWarning'] + '\n' + PMA_messages['strDoYouReally'] + ' :\n' + 'DROP TABLE ' + window.parent.table;
3164 $(this).PMA_confirm(question, $(this).attr('href') ,function(url) {
3166 PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
3167 $.get(url, {'is_js_confirmed': '1', 'ajax_request': true}, function(data) {
3168 //Database deleted successfully, refresh both the frames
3169 window.parent.refreshNavigation();
3170 window.parent.refreshMain();
3171 }) // end $.get()
3172 }); // end $.PMA_confirm()
3173 }); //end of Drop Table Ajax action
3174 }) // end of $(document).ready() for Drop Table
3177 * Attach Ajax event handlers for Truncate Table.
3179 * @uses $.PMA_confirm()
3180 * @uses PMA_ajaxShowMessage()
3181 * @uses window.parent.refreshNavigation()
3182 * @uses window.parent.refreshMain()
3183 * @see $cfg['AjaxEnable']
3185 $(document).ready(function() {
3186 $("#truncate_tbl_anchor.ajax").live('click', function(event) {
3187 event.preventDefault();
3189 //context is top.frame_content, so we need to use window.parent.table to access the table var
3191 * @var question String containing the question to be asked for confirmation
3193 var question = PMA_messages['strTruncateTableStrongWarning'] + '\n' + PMA_messages['strDoYouReally'] + ' :\n' + 'TRUNCATE TABLE ' + window.parent.table;
3195 $(this).PMA_confirm(question, $(this).attr('href') ,function(url) {
3197 PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
3198 $.get(url, {'is_js_confirmed': '1', 'ajax_request': true}, function(data) {
3199 if ($("#sqlqueryresults").length != 0) {
3200 $("#sqlqueryresults").remove();
3202 if ($("#result_query").length != 0) {
3203 $("#result_query").remove();
3205 if (data.success == true) {
3206 PMA_ajaxShowMessage(data.message);
3207 $("<div id='sqlqueryresults'></div>").insertAfter("#topmenucontainer");
3208 $("#sqlqueryresults").html(data.sql_query);
3209 } else {
3210 var $temp_div = $("<div id='temp_div'></div>")
3211 $temp_div.html(data.error);
3212 var $error = $temp_div.find("code").addClass("error");
3213 PMA_ajaxShowMessage($error);
3215 }) // end $.get()
3216 }); // end $.PMA_confirm()
3217 }); //end of Truncate Table Ajax action
3218 }) // end of $(document).ready() for Truncate Table
3221 * Attach CodeMirror2 editor to SQL edit area.
3223 $(document).ready(function() {
3224 var elm = $('#sqlquery');
3225 if (elm.length > 0 && typeof CodeMirror != 'undefined') {
3226 codemirror_editor = CodeMirror.fromTextArea(elm[0], {lineNumbers: true, matchBrackets: true, indentUnit: 4, mode: "text/x-mysql"});
3231 * jQuery plugin to cancel selection in HTML code.
3233 (function ($) {
3234 $.fn.noSelect = function (p) { //no select plugin by Paulo P.Marinas
3235 var prevent = (p == null) ? true : p;
3236 if (prevent) {
3237 return this.each(function () {
3238 if ($.browser.msie || $.browser.safari) $(this).bind('selectstart', function () {
3239 return false;
3241 else if ($.browser.mozilla) {
3242 $(this).css('MozUserSelect', 'none');
3243 $('body').trigger('focus');
3244 } else if ($.browser.opera) $(this).bind('mousedown', function () {
3245 return false;
3247 else $(this).attr('unselectable', 'on');
3249 } else {
3250 return this.each(function () {
3251 if ($.browser.msie || $.browser.safari) $(this).unbind('selectstart');
3252 else if ($.browser.mozilla) $(this).css('MozUserSelect', 'inherit');
3253 else if ($.browser.opera) $(this).unbind('mousedown');
3254 else $(this).removeAttr('unselectable', 'on');
3257 }; //end noSelect
3258 })(jQuery);
3261 * Create default PMA tooltip for the element specified. The default appearance
3262 * can be overriden by specifying optional "options" parameter (see qTip options).
3264 function PMA_createqTip($elements, content, options)
3266 if ($('#no_hint').length > 0) {
3267 return;
3270 var o = {
3271 content: content,
3272 style: {
3273 classes: {
3274 tooltip: 'normalqTip',
3275 content: 'normalqTipContent'
3277 name: 'dark'
3279 position: {
3280 target: 'mouse',
3281 corner: { target: 'rightMiddle', tooltip: 'leftMiddle' },
3282 adjust: { x: 10, y: 20 }
3284 show: {
3285 delay: 0,
3286 effect: {
3287 type: 'grow',
3288 length: 150
3291 hide: {
3292 effect: {
3293 type: 'grow',
3294 length: 200
3299 $elements.qtip($.extend(true, o, options));
3303 * Return value of a cell in a table.
3305 function PMA_getCellValue(td) {
3306 if ($(td).is('.null')) {
3307 return '';
3308 } else if (! $(td).is('.to_be_saved') && $(td).data('original_data')) {
3309 return $(td).data('original_data');
3310 } else {
3311 return $(td).text();
3315 /* Loads a js file, an array may be passed as well */
3316 loadJavascript=function(file) {
3317 if($.isArray(file)) {
3318 for(var i=0; i<file.length; i++) {
3319 $('head').append('<script type="text/javascript" src="'+file[i]+'"></script>');
3321 } else {
3322 $('head').append('<script type="text/javascript" src="'+file+'"></script>');
3326 $(document).ready(function() {
3328 * Theme selector.
3330 $('a.themeselect').live('click', function(e) {
3331 window.open(
3332 e.target,
3333 'themes',
3334 'left=10,top=20,width=510,height=350,scrollbars=yes,status=yes,resizable=yes'
3336 return false;
3340 * Automatic form submission on change.
3342 $('.autosubmit').change(function(e) {
3343 e.target.form.submit();
3347 * Theme changer.
3349 $('.take_theme').click(function(e) {
3350 var what = this.name;
3351 if (window.opener && window.opener.document.forms['setTheme'].elements['set_theme']) {
3352 window.opener.document.forms['setTheme'].elements['set_theme'].value = what;
3353 window.opener.document.forms['setTheme'].submit();
3354 window.close();
3355 return false;
3357 return true;
3362 * Clear text selection
3364 function PMA_clearSelection() {
3365 if(document.selection && document.selection.empty) {
3366 document.selection.empty();
3367 } else if(window.getSelection) {
3368 var sel = window.getSelection();
3369 if(sel.empty) sel.empty();
3370 if(sel.removeAllRanges) sel.removeAllRanges();