1 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 * general function, usually for data manipulation pages
8 * @var sql_box_locked lock for the sqlbox textarea in the querybox/querywindow
10 var sql_box_locked = false;
13 * @var array holds elements which content should only selected once
15 var only_once_elements = new Array();
18 * @var int ajax_message_count Number of AJAX messages shown since page load
20 var ajax_message_count = 0;
23 * @var codemirror_editor object containing CodeMirror editor
25 var codemirror_editor = false;
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();
33 * Returns browser's viewport size, without accounting for scrollbars
37 function getWindowSize(wnd) {
38 var vp = wnd || window;
40 // most browsers || IE6-8 strict || failsafe
41 width: vp.innerWidth || (vp.documentElement !== undefined ? vp.documentElement.clientWidth : false) || $(vp).width(),
42 height: vp.innerHeight || (vp.documentElement !== undefined ? vp.documentElement.clientHeight : false) || $(vp).height()
47 * Make sure that ajax requests will not be cached
48 * by appending a random variable to their parameters
50 $.ajaxPrefilter(function (options, originalOptions, jqXHR) {
51 var nocache = new Date().getTime() + "" + Math.floor(Math.random() * 1000000);
52 if (typeof options.data == "string") {
53 options.data += "&_nocache=" + nocache;
54 } else if (typeof options.data == "object") {
55 options.data = $.extend(originalOptions.data, {'_nocache':nocache});
60 * Add a hidden field to the form to indicate that this will be an
61 * Ajax request (only if this hidden field does not exist)
63 * @param object the form
65 function PMA_prepareForAjaxRequest($form)
67 if (! $form.find('input:hidden').is('#ajax_request_hidden')) {
68 $form.append('<input type="hidden" id="ajax_request_hidden" name="ajax_request" value="true" />');
73 * Generate a new password and copy it to the password input areas
75 * @param object the form that holds the password fields
77 * @return boolean always true
79 function suggestPassword(passwd_form)
81 // restrict the password to just letters and numbers to avoid problems:
82 // "editors and viewers regard the password as multiple words and
83 // things like double click no longer work"
84 var pwchars = "abcdefhjmnpqrstuvwxyz23456789ABCDEFGHJKLMNPQRSTUVWYXZ";
85 var passwordlength = 16; // do we want that to be dynamic? no, keep it simple :)
86 var passwd = passwd_form.generated_pw;
89 for ( i = 0; i < passwordlength; i++ ) {
90 passwd.value += pwchars.charAt( Math.floor( Math.random() * pwchars.length ) )
92 passwd_form.text_pma_pw.value = passwd.value;
93 passwd_form.text_pma_pw2.value = passwd.value;
98 * Version string to integer conversion.
100 function parseVersionString (str)
102 if (typeof(str) != 'string') { return false; }
104 // Parse possible alpha/beta/rc/
105 var state = str.split('-');
106 if (state.length >= 2) {
107 if (state[1].substr(0, 2) == 'rc') {
108 add = - 20 - parseInt(state[1].substr(2));
109 } else if (state[1].substr(0, 4) == 'beta') {
110 add = - 40 - parseInt(state[1].substr(4));
111 } else if (state[1].substr(0, 5) == 'alpha') {
112 add = - 60 - parseInt(state[1].substr(5));
113 } else if (state[1].substr(0, 3) == 'dev') {
114 /* We don't handle dev, it's git snapshot */
119 var x = str.split('.');
120 // Use 0 for non existing parts
121 var maj = parseInt(x[0]) || 0;
122 var min = parseInt(x[1]) || 0;
123 var pat = parseInt(x[2]) || 0;
124 var hotfix = parseInt(x[3]) || 0;
125 return maj * 100000000 + min * 1000000 + pat * 10000 + hotfix * 100 + add;
129 * Indicates current available version on main page.
131 function PMA_current_version()
133 var current = parseVersionString(pmaversion);
134 var latest = parseVersionString(PMA_latest_version);
135 var version_information_message = PMA_messages['strLatestAvailable'] + ' ' + PMA_latest_version;
136 if (latest > current) {
137 var message = $.sprintf(PMA_messages['strNewerVersion'], PMA_latest_version, PMA_latest_date);
138 if (Math.floor(latest / 10000) == Math.floor(current / 10000)) {
139 /* Security update */
144 $('#maincontainer').after('<div class="' + klass + '">' + message + '</div>');
146 if (latest == current) {
147 version_information_message = ' (' + PMA_messages['strUpToDate'] + ')';
149 $('#li_pma_version').append(version_information_message);
153 * for libraries/display_change_password.lib.php
154 * libraries/user_password.php
158 function displayPasswordGenerateButton()
160 $('#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>');
161 $('#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>');
165 * Adds a date/time picker to an element
167 * @param object $this_element a jQuery object pointing to the element
169 function PMA_addDatepicker($this_element, options)
171 var showTimeOption = false;
172 if ($this_element.is('.datetimefield')) {
173 showTimeOption = true;
176 var defaultOptions = {
178 buttonImage: themeCalendarImage, // defined in js/messages.php
179 buttonImageOnly: true,
183 showTimepicker: showTimeOption,
184 showButtonPanel: false,
185 dateFormat: 'yy-mm-dd', // yy means year with four digits
186 timeFormat: 'hh:mm:ss',
187 altFieldTimeOnly: false,
189 beforeShow: function(input, inst) {
190 // Remember that we came from the datepicker; this is used
191 // in tbl_change.js by verificationsAfterFieldChange()
192 $this_element.data('comes_from', 'datepicker');
194 // Fix wrong timepicker z-index, doesn't work without timeout
195 setTimeout(function() {
196 $('#ui-timepicker-div').css('z-index',$('#ui-datepicker-div').css('z-index'))
201 $this_element.datetimepicker($.extend(defaultOptions, options));
205 * selects the content of a given object, f.e. a textarea
207 * @param object element element of which the content will be selected
208 * @param var lock variable which holds the lock for this element
209 * or true, if no lock exists
210 * @param boolean only_once if true this is only done once
211 * f.e. only on first focus
213 function selectContent( element, lock, only_once )
215 if ( only_once && only_once_elements[element.name] ) {
219 only_once_elements[element.name] = true;
229 * Displays a confirmation box before submitting a "DROP/DELETE/ALTER" query.
230 * This function is called while clicking links
232 * @param object the link
233 * @param object the sql query to submit
235 * @return boolean whether to run the query or not
237 function confirmLink(theLink, theSqlQuery)
239 // Confirmation is not required in the configuration file
240 // or browser is Opera (crappy js implementation)
241 if (PMA_messages['strDoYouReally'] == '' || typeof(window.opera) != 'undefined') {
245 var is_confirmed = confirm(PMA_messages['strDoYouReally'] + ' :\n' + theSqlQuery);
247 if ( $(theLink).hasClass('formLinkSubmit') ) {
248 var name = 'is_js_confirmed';
249 if ($(theLink).attr('href').indexOf('usesubform') != -1) {
250 name = 'subform[' + $(theLink).attr('href').substr('#').match(/usesubform\[(\d+)\]/i)[1] + '][is_js_confirmed]';
253 $(theLink).parents('form').append('<input type="hidden" name="' + name + '" value="1" />');
254 } else if ( typeof(theLink.href) != 'undefined' ) {
255 theLink.href += '&is_js_confirmed=1';
256 } else if ( typeof(theLink.form) != 'undefined' ) {
257 theLink.form.action += '?is_js_confirmed=1';
262 } // end of the 'confirmLink()' function
265 * Displays an error message if a "DROP DATABASE" statement is submitted
266 * while it isn't allowed, else confirms a "DROP/DELETE/ALTER" query before
267 * sumitting it if required.
268 * This function is called by the 'checkSqlQuery()' js function.
270 * @param object the form
271 * @param object the sql query textarea
273 * @return boolean whether to run the query or not
275 * @see checkSqlQuery()
277 function confirmQuery(theForm1, sqlQuery1)
279 // Confirmation is not required in the configuration file
280 if (PMA_messages['strDoYouReally'] == '') {
284 // "DROP DATABASE" statement isn't allowed
285 if (PMA_messages['strNoDropDatabases'] != '') {
286 var drop_re = new RegExp('(^|;)\\s*DROP\\s+(IF EXISTS\\s+)?DATABASE\\s', 'i');
287 if (drop_re.test(sqlQuery1.value)) {
288 alert(PMA_messages['strNoDropDatabases']);
295 // Confirms a "DROP/DELETE/ALTER/TRUNCATE" statement
297 // TODO: find a way (if possible) to use the parser-analyser
298 // for this kind of verification
299 // For now, I just added a ^ to check for the statement at
300 // beginning of expression
302 var do_confirm_re_0 = new RegExp('^\\s*DROP\\s+(IF EXISTS\\s+)?(TABLE|DATABASE|PROCEDURE)\\s', 'i');
303 var do_confirm_re_1 = new RegExp('^\\s*ALTER\\s+TABLE\\s+((`[^`]+`)|([A-Za-z0-9_$]+))\\s+DROP\\s', 'i');
304 var do_confirm_re_2 = new RegExp('^\\s*DELETE\\s+FROM\\s', 'i');
305 var do_confirm_re_3 = new RegExp('^\\s*TRUNCATE\\s', 'i');
307 if (do_confirm_re_0.test(sqlQuery1.value)
308 || do_confirm_re_1.test(sqlQuery1.value)
309 || do_confirm_re_2.test(sqlQuery1.value)
310 || do_confirm_re_3.test(sqlQuery1.value)) {
311 var message = (sqlQuery1.value.length > 100)
312 ? sqlQuery1.value.substr(0, 100) + '\n ...'
314 var is_confirmed = confirm(PMA_messages['strDoYouReally'] + ' :\n' + message);
315 // statement is confirmed -> update the
316 // "is_js_confirmed" form field so the confirm test won't be
317 // run on the server side and allows to submit the form
319 theForm1.elements['is_js_confirmed'].value = 1;
322 // statement is rejected -> do not submit the form
327 } // end if (handle confirm box result)
328 } // end if (display confirm box)
331 } // end of the 'confirmQuery()' function
335 * Displays a confirmation box before disabling the BLOB repository for a given database.
336 * This function is called while clicking links
338 * @param object the database
340 * @return boolean whether to disable the repository or not
342 function confirmDisableRepository(theDB)
344 // Confirmation is not required in the configuration file
345 // or browser is Opera (crappy js implementation)
346 if (PMA_messages['strDoYouReally'] == '' || typeof(window.opera) != 'undefined') {
350 var is_confirmed = confirm(PMA_messages['strBLOBRepositoryDisableStrongWarning'] + '\n' + PMA_messages['strBLOBRepositoryDisableAreYouSure']);
353 } // end of the 'confirmDisableBLOBRepository()' function
357 * Displays an error message if the user submitted the sql query form with no
358 * sql query, else checks for "DROP/DELETE/ALTER" statements
360 * @param object the form
362 * @return boolean always false
364 * @see confirmQuery()
366 function checkSqlQuery(theForm)
368 var sqlQuery = theForm.elements['sql_query'];
371 var space_re = new RegExp('\\s+');
372 if (typeof(theForm.elements['sql_file']) != 'undefined' &&
373 theForm.elements['sql_file'].value.replace(space_re, '') != '') {
376 if (typeof(theForm.elements['sql_localfile']) != 'undefined' &&
377 theForm.elements['sql_localfile'].value.replace(space_re, '') != '') {
380 if (isEmpty && typeof(theForm.elements['id_bookmark']) != 'undefined' &&
381 (theForm.elements['id_bookmark'].value != null || theForm.elements['id_bookmark'].value != '') &&
382 theForm.elements['id_bookmark'].selectedIndex != 0
386 // Checks for "DROP/DELETE/ALTER" statements
387 if (sqlQuery.value.replace(space_re, '') != '') {
388 if (confirmQuery(theForm, sqlQuery)) {
399 alert(PMA_messages['strFormEmpty']);
405 } // end of the 'checkSqlQuery()' function
408 * Check if a form's element is empty.
409 * An element containing only spaces is also considered empty
411 * @param object the form
412 * @param string the name of the form field to put the focus on
414 * @return boolean whether the form field is empty or not
416 function emptyCheckTheField(theForm, theFieldName)
418 var theField = theForm.elements[theFieldName];
419 var space_re = new RegExp('\\s+');
420 return (theField.value.replace(space_re, '') == '') ? 1 : 0;
421 } // end of the 'emptyCheckTheField()' function
425 * Check whether a form field is empty or not
427 * @param object the form
428 * @param string the name of the form field to put the focus on
430 * @return boolean whether the form field is empty or not
432 function emptyFormElements(theForm, theFieldName)
434 var theField = theForm.elements[theFieldName];
435 var isEmpty = emptyCheckTheField(theForm, theFieldName);
439 } // end of the 'emptyFormElements()' function
443 * Ensures a value submitted in a form is numeric and is in a range
445 * @param object the form
446 * @param string the name of the form field to check
447 * @param integer the minimum authorized value
448 * @param integer the maximum authorized value
450 * @return boolean whether a valid number has been submitted or not
452 function checkFormElementInRange(theForm, theFieldName, message, min, max)
454 var theField = theForm.elements[theFieldName];
455 var val = parseInt(theField.value);
457 if (typeof(min) == 'undefined') {
460 if (typeof(max) == 'undefined') {
461 max = Number.MAX_VALUE;
467 alert(PMA_messages['strNotNumber']);
471 // It's a number but it is not between min and max
472 else if (val < min || val > max) {
474 alert(message.replace('%d', val));
478 // It's a valid number
480 theField.value = val;
484 } // end of the 'checkFormElementInRange()' function
487 function checkTableEditForm(theForm, fieldsCnt)
489 // TODO: avoid sending a message if user just wants to add a line
490 // on the form but has not completed at least one field name
492 var atLeastOneField = 0;
493 var i, elm, elm2, elm3, val, id;
495 for (i=0; i<fieldsCnt; i++)
497 id = "#field_" + i + "_2";
500 if (val == 'VARCHAR' || val == 'CHAR' || val == 'BIT' || val == 'VARBINARY' || val == 'BINARY') {
501 elm2 = $("#field_" + i + "_3");
502 val = parseInt(elm2.val());
503 elm3 = $("#field_" + i + "_1");
504 if (isNaN(val) && elm3.val() != "") {
506 alert(PMA_messages['strNotNumber']);
512 if (atLeastOneField == 0) {
513 id = "field_" + i + "_1";
514 if (!emptyCheckTheField(theForm, id)) {
519 if (atLeastOneField == 0) {
520 var theField = theForm.elements["field_0_1"];
521 alert(PMA_messages['strFormEmpty']);
526 // at least this section is under jQuery
527 if ($("input.textfield[name='table']").val() == "") {
528 alert(PMA_messages['strFormEmpty']);
529 $("input.textfield[name='table']").focus();
535 } // enf of the 'checkTableEditForm()' function
537 $(document).ready(function() {
539 * Row marking in horizontal mode (use "live" so that it works also for
540 * next pages reached via AJAX); a tr may have the class noclick to remove
543 $('table:not(.noclick) tr.odd:not(.noclick), table:not(.noclick) tr.even:not(.noclick)').live('click',function(e) {
544 // do not trigger when clicked on anchor
545 if ($(e.target).is('a, img, a *')) {
550 // make the table unselectable (to prevent default highlighting when shift+click)
551 //$tr.parents('table').noSelect();
553 if (!e.shiftKey || last_clicked_row == -1) {
556 // XXX: FF fires two click events for <label> (label and checkbox), so we need to handle this differently
557 var $checkbox = $tr.find(':checkbox');
558 if ($checkbox.length) {
559 // checkbox in a row, add or remove class depending on checkbox state
560 var checked = $checkbox.attr('checked');
561 if (!$(e.target).is(':checkbox, label')) {
563 $checkbox.attr('checked', checked);
566 $tr.addClass('marked');
568 $tr.removeClass('marked');
570 last_click_checked = checked;
572 // normaln data table, just toggle class
573 $tr.toggleClass('marked');
574 last_click_checked = false;
577 // remember the last clicked row
578 last_clicked_row = last_click_checked ? $('tr.odd:not(.noclick), tr.even:not(.noclick)').index(this) : -1;
579 last_shift_clicked_row = -1;
581 // handle the shift click
582 PMA_clearSelection();
585 // clear last shift click result
586 if (last_shift_clicked_row >= 0) {
587 if (last_shift_clicked_row >= last_clicked_row) {
588 start = last_clicked_row;
589 end = last_shift_clicked_row;
591 start = last_shift_clicked_row;
592 end = last_clicked_row;
594 $tr.parent().find('tr.odd:not(.noclick), tr.even:not(.noclick)')
595 .slice(start, end + 1)
596 .removeClass('marked')
598 .attr('checked', false);
601 // handle new shift click
602 var curr_row = $('tr.odd:not(.noclick), tr.even:not(.noclick)').index(this);
603 if (curr_row >= last_clicked_row) {
604 start = last_clicked_row;
608 end = last_clicked_row;
610 $tr.parent().find('tr.odd:not(.noclick), tr.even:not(.noclick)')
611 .slice(start, end + 1)
614 .attr('checked', true);
616 // remember the last shift clicked row
617 last_shift_clicked_row = curr_row;
622 * Add a date/time picker to each element that needs it
623 * (only when timepicker.js is loaded)
625 if ($.timepicker != undefined) {
626 $('.datefield, .datetimefield').each(function() {
627 PMA_addDatepicker($(this));
633 * True if last click is to check a row.
635 var last_click_checked = false;
638 * Zero-based index of last clicked row.
639 * Used to handle the shift + click event in the code above.
641 var last_clicked_row = -1;
644 * Zero-based index of last shift clicked row.
646 var last_shift_clicked_row = -1;
649 * Row highlighting in horizontal mode (use "live"
650 * so that it works also for pages reached via AJAX)
652 /*$(document).ready(function() {
653 $('tr.odd, tr.even').live('hover',function(event) {
655 $tr.toggleClass('hover',event.type=='mouseover');
656 $tr.children().toggleClass('hover',event.type=='mouseover');
661 * This array is used to remember mark status of rows in browse mode
663 var marked_row = new Array;
666 * marks all rows and selects its first checkbox inside the given element
667 * the given element is usaly a table or a div containing the table or tables
669 * @param container DOM element
671 function markAllRows( container_id )
674 $("#"+container_id).find("input:checkbox:enabled").attr('checked', 'checked')
675 .parents("tr").addClass("marked");
680 * marks all rows and selects its first checkbox inside the given element
681 * the given element is usaly a table or a div containing the table or tables
683 * @param container DOM element
685 function unMarkAllRows( container_id )
688 $("#"+container_id).find("input:checkbox:enabled").removeAttr('checked')
689 .parents("tr").removeClass("marked");
694 * Checks/unchecks all checkbox in given conainer (f.e. a form, fieldset or div)
696 * @param string container_id the container id
697 * @param boolean state new value for checkbox (true or false)
698 * @return boolean always true
700 function setCheckboxes( container_id, state )
704 $("#"+container_id).find("input:checkbox").attr('checked', 'checked');
707 $("#"+container_id).find("input:checkbox").removeAttr('checked');
711 } // end of the 'setCheckboxes()' function
714 * Checks/unchecks all options of a <select> element
716 * @param string the form name
717 * @param string the element name
718 * @param boolean whether to check or to uncheck options
720 * @return boolean always true
722 function setSelectOptions(the_form, the_select, do_check)
724 $("form[name='"+ the_form +"'] select[name='"+the_select+"']").find("option").attr('selected', do_check);
726 } // end of the 'setSelectOptions()' function
729 * Sets current value for query box.
731 function setQuery(query)
733 if (codemirror_editor) {
734 codemirror_editor.setValue(query);
736 document.sqlform.sql_query.value = query;
742 * Create quick sql statements.
745 function insertQuery(queryType)
747 if (queryType == "clear") {
752 var myQuery = document.sqlform.sql_query;
754 var myListBox = document.sqlform.dummy;
755 var table = document.sqlform.table.value;
757 if (myListBox.options.length > 0) {
758 sql_box_locked = true;
763 for (var i=0; i < myListBox.options.length; i++) {
770 chaineAj += myListBox.options[i].value;
771 valDis += "[value-" + NbSelect + "]";
772 editDis += myListBox.options[i].value + "=[value-" + NbSelect + "]";
774 if (queryType == "selectall") {
775 query = "SELECT * FROM `" + table + "` WHERE 1";
776 } else if (queryType == "select") {
777 query = "SELECT " + chaineAj + " FROM `" + table + "` WHERE 1";
778 } else if (queryType == "insert") {
779 query = "INSERT INTO `" + table + "`(" + chaineAj + ") VALUES (" + valDis + ")";
780 } else if (queryType == "update") {
781 query = "UPDATE `" + table + "` SET " + editDis + " WHERE 1";
782 } else if(queryType == "delete") {
783 query = "DELETE FROM `" + table + "` WHERE 1";
786 sql_box_locked = false;
792 * Inserts multiple fields.
795 function insertValueQuery()
797 var myQuery = document.sqlform.sql_query;
798 var myListBox = document.sqlform.dummy;
800 if(myListBox.options.length > 0) {
801 sql_box_locked = true;
804 for(var i=0; i<myListBox.options.length; i++) {
805 if (myListBox.options[i].selected) {
810 chaineAj += myListBox.options[i].value;
814 /* CodeMirror support */
815 if (codemirror_editor) {
816 codemirror_editor.replaceSelection(chaineAj);
818 } else if (document.selection) {
820 sel = document.selection.createRange();
822 document.sqlform.insert.focus();
824 //MOZILLA/NETSCAPE support
825 else if (document.sqlform.sql_query.selectionStart || document.sqlform.sql_query.selectionStart == "0") {
826 var startPos = document.sqlform.sql_query.selectionStart;
827 var endPos = document.sqlform.sql_query.selectionEnd;
828 var chaineSql = document.sqlform.sql_query.value;
830 myQuery.value = chaineSql.substring(0, startPos) + chaineAj + chaineSql.substring(endPos, chaineSql.length);
832 myQuery.value += chaineAj;
834 sql_box_locked = false;
839 * listbox redirection
841 function goToUrl(selObj, goToLocation)
843 eval("document.location.href = '" + goToLocation + "pos=" + selObj.options[selObj.selectedIndex].value + "'");
847 * Refresh the WYSIWYG scratchboard after changes have been made
849 function refreshDragOption(e)
851 var elm = $('#' + e);
852 if (elm.css('visibility') == 'visible') {
859 * Refresh/resize the WYSIWYG scratchboard
861 function refreshLayout()
863 var elm = $('#pdflayout')
864 var orientation = $('#orientation_opt').val();
865 if($('#paper_opt').length==1){
866 var paper = $('#paper_opt').val();
870 if (orientation == 'P') {
877 elm.css('width', pdfPaperSize(paper, posa) + 'px');
878 elm.css('height', pdfPaperSize(paper, posb) + 'px');
882 * Show/hide the WYSIWYG scratchboard
884 function ToggleDragDrop(e)
886 var elm = $('#' + e);
887 if (elm.css('visibility') == 'hidden') {
888 PDFinit(); /* Defined in pdf_pages.php */
889 elm.css('visibility', 'visible');
890 elm.css('display', 'block');
891 $('#showwysiwyg').val('1')
893 elm.css('visibility', 'hidden');
894 elm.css('display', 'none');
895 $('#showwysiwyg').val('0')
900 * PDF scratchboard: When a position is entered manually, update
901 * the fields inside the scratchboard.
903 function dragPlace(no, axis, value)
905 var elm = $('#table_' + no);
907 elm.css('left', value + 'px');
909 elm.css('top', value + 'px');
914 * Returns paper sizes for a given format
916 function pdfPaperSize(format, axis)
918 switch (format.toUpperCase()) {
920 if (axis == 'x') return 4767.87; else return 6740.79;
923 if (axis == 'x') return 3370.39; else return 4767.87;
926 if (axis == 'x') return 2383.94; else return 3370.39;
929 if (axis == 'x') return 1683.78; else return 2383.94;
932 if (axis == 'x') return 1190.55; else return 1683.78;
935 if (axis == 'x') return 841.89; else return 1190.55;
938 if (axis == 'x') return 595.28; else return 841.89;
941 if (axis == 'x') return 419.53; else return 595.28;
944 if (axis == 'x') return 297.64; else return 419.53;
947 if (axis == 'x') return 209.76; else return 297.64;
950 if (axis == 'x') return 147.40; else return 209.76;
953 if (axis == 'x') return 104.88; else return 147.40;
956 if (axis == 'x') return 73.70; else return 104.88;
959 if (axis == 'x') return 2834.65; else return 4008.19;
962 if (axis == 'x') return 2004.09; else return 2834.65;
965 if (axis == 'x') return 1417.32; else return 2004.09;
968 if (axis == 'x') return 1000.63; else return 1417.32;
971 if (axis == 'x') return 708.66; else return 1000.63;
974 if (axis == 'x') return 498.90; else return 708.66;
977 if (axis == 'x') return 354.33; else return 498.90;
980 if (axis == 'x') return 249.45; else return 354.33;
983 if (axis == 'x') return 175.75; else return 249.45;
986 if (axis == 'x') return 124.72; else return 175.75;
989 if (axis == 'x') return 87.87; else return 124.72;
992 if (axis == 'x') return 2599.37; else return 3676.54;
995 if (axis == 'x') return 1836.85; else return 2599.37;
998 if (axis == 'x') return 1298.27; else return 1836.85;
1001 if (axis == 'x') return 918.43; else return 1298.27;
1004 if (axis == 'x') return 649.13; else return 918.43;
1007 if (axis == 'x') return 459.21; else return 649.13;
1010 if (axis == 'x') return 323.15; else return 459.21;
1013 if (axis == 'x') return 229.61; else return 323.15;
1016 if (axis == 'x') return 161.57; else return 229.61;
1019 if (axis == 'x') return 113.39; else return 161.57;
1022 if (axis == 'x') return 79.37; else return 113.39;
1025 if (axis == 'x') return 2437.80; else return 3458.27;
1028 if (axis == 'x') return 1729.13; else return 2437.80;
1031 if (axis == 'x') return 1218.90; else return 1729.13;
1034 if (axis == 'x') return 864.57; else return 1218.90;
1037 if (axis == 'x') return 609.45; else return 864.57;
1040 if (axis == 'x') return 2551.18; else return 3628.35;
1043 if (axis == 'x') return 1814.17; else return 2551.18;
1046 if (axis == 'x') return 1275.59; else return 1814.17;
1049 if (axis == 'x') return 907.09; else return 1275.59;
1052 if (axis == 'x') return 637.80; else return 907.09;
1055 if (axis == 'x') return 612.00; else return 792.00;
1058 if (axis == 'x') return 612.00; else return 1008.00;
1061 if (axis == 'x') return 521.86; else return 756.00;
1064 if (axis == 'x') return 612.00; else return 936.00;
1072 * for playing media from the BLOB repository
1075 * @param var url_params main purpose is to pass the token
1076 * @param var bs_ref BLOB repository reference
1077 * @param var m_type type of BLOB repository media
1078 * @param var w_width width of popup window
1079 * @param var w_height height of popup window
1081 function popupBSMedia(url_params, bs_ref, m_type, is_cust_type, w_width, w_height)
1083 // if width not specified, use default
1084 if (w_width == undefined) {
1088 // if height not specified, use default
1089 if (w_height == undefined) {
1093 // open popup window (for displaying video/playing audio)
1094 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');
1098 * popups a request for changing MIME types for files in the BLOB repository
1100 * @param var db database name
1101 * @param var table table name
1102 * @param var reference BLOB repository reference
1103 * @param var current_mime_type current MIME type associated with BLOB repository reference
1105 function requestMIMETypeChange(db, table, reference, current_mime_type)
1107 // no mime type specified, set to default (nothing)
1108 if (undefined == current_mime_type) {
1109 current_mime_type = "";
1112 // prompt user for new mime type
1113 var new_mime_type = prompt("Enter custom MIME type", current_mime_type);
1115 // if new mime_type is specified and is not the same as the previous type, request for mime type change
1116 if (new_mime_type && new_mime_type != current_mime_type) {
1117 changeMIMEType(db, table, reference, new_mime_type);
1122 * changes MIME types for files in the BLOB repository
1124 * @param var db database name
1125 * @param var table table name
1126 * @param var reference BLOB repository reference
1127 * @param var mime_type new MIME type to be associated with BLOB repository reference
1129 function changeMIMEType(db, table, reference, mime_type)
1131 // specify url and parameters for jQuery POST
1132 var mime_chg_url = 'bs_change_mime_type.php';
1133 var params = {bs_db: db, bs_table: table, bs_reference: reference, bs_new_mime_type: mime_type};
1136 jQuery.post(mime_chg_url, params);
1140 * Jquery Coding for inline editing SQL_QUERY
1142 $(document).ready(function(){
1143 $(".inline_edit_sql").live('click', function(){
1144 var $form = $(this).prev();
1145 var sql_query = $form.find("input[name='sql_query']").val();
1146 var $inner_sql = $(this).parent().prev().find('.inner_sql');
1147 var old_text = $inner_sql.html();
1149 var new_content = "<textarea name=\"sql_query_edit\" id=\"sql_query_edit\">" + sql_query + "</textarea>\n";
1150 new_content += "<input type=\"button\" class=\"btnSave\" value=\"" + PMA_messages['strGo'] + "\">\n";
1151 new_content += "<input type=\"button\" class=\"btnDiscard\" value=\"" + PMA_messages['strCancel'] + "\">\n";
1152 $inner_sql.replaceWith(new_content);
1153 $(".btnSave").click(function(){
1154 var sql_query = $(this).prev().val();
1155 var $fake_form = $('<form>', {action: 'import.php', method: 'post'})
1156 .append($form.find("input[name=server], input[name=db], input[name=table], input[name=token]").clone())
1157 .append($('<input>', {type: 'hidden', name: 'show_query', value: 1}))
1158 .append($('<input>', {type: 'hidden', name: 'sql_query', value: sql_query}));
1159 $fake_form.appendTo($('body')).submit();
1161 $(".btnDiscard").click(function(){
1162 $(this).closest(".sql").html("<span class=\"syntax\"><span class=\"inner_sql\">" + old_text + "</span></span>");
1167 $('.sqlbutton').click(function(evt){
1168 insertQuery(evt.target.id);
1172 $("#export_type").change(function(){
1173 if($("#export_type").val()=='svg'){
1174 $("#show_grid_opt").attr("disabled","disabled");
1175 $("#orientation_opt").attr("disabled","disabled");
1176 $("#with_doc").attr("disabled","disabled");
1177 $("#show_table_dim_opt").removeAttr("disabled");
1178 $("#all_table_same_wide").removeAttr("disabled");
1179 $("#paper_opt").removeAttr("disabled","disabled");
1180 $("#show_color_opt").removeAttr("disabled","disabled");
1181 //$(this).css("background-color","yellow");
1182 }else if($("#export_type").val()=='dia'){
1183 $("#show_grid_opt").attr("disabled","disabled");
1184 $("#with_doc").attr("disabled","disabled");
1185 $("#show_table_dim_opt").attr("disabled","disabled");
1186 $("#all_table_same_wide").attr("disabled","disabled");
1187 $("#paper_opt").removeAttr("disabled","disabled");
1188 $("#show_color_opt").removeAttr("disabled","disabled");
1189 $("#orientation_opt").removeAttr("disabled","disabled");
1190 }else if($("#export_type").val()=='eps'){
1191 $("#show_grid_opt").attr("disabled","disabled");
1192 $("#orientation_opt").removeAttr("disabled");
1193 $("#with_doc").attr("disabled","disabled");
1194 $("#show_table_dim_opt").attr("disabled","disabled");
1195 $("#all_table_same_wide").attr("disabled","disabled");
1196 $("#paper_opt").attr("disabled","disabled");
1197 $("#show_color_opt").attr("disabled","disabled");
1199 }else if($("#export_type").val()=='pdf'){
1200 $("#show_grid_opt").removeAttr("disabled");
1201 $("#orientation_opt").removeAttr("disabled");
1202 $("#with_doc").removeAttr("disabled","disabled");
1203 $("#show_table_dim_opt").removeAttr("disabled","disabled");
1204 $("#all_table_same_wide").removeAttr("disabled","disabled");
1205 $("#paper_opt").removeAttr("disabled","disabled");
1206 $("#show_color_opt").removeAttr("disabled","disabled");
1212 $('#sqlquery').focus().keydown(function (e) {
1213 if (e.ctrlKey && e.keyCode == 13) {
1214 $("#sqlqueryform").submit();
1218 if ($('#input_username')) {
1219 if ($('#input_username').val() == '') {
1220 $('#input_username').focus();
1222 $('#input_password').focus();
1228 * Show a message on the top of the page for an Ajax request
1232 * 1) var $msg = PMA_ajaxShowMessage();
1233 * This will show a message that reads "Loading...". Such a message will not
1234 * disappear automatically and cannot be dismissed by the user. To remove this
1235 * message either the PMA_ajaxRemoveMessage($msg) function must be called or
1236 * another message must be show with PMA_ajaxShowMessage() function.
1238 * 2) var $msg = PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
1239 * This is a special case. The behaviour is same as above,
1240 * just with a different message
1242 * 3) var $msg = PMA_ajaxShowMessage('The operation was successful');
1243 * This will show a message that will disappear automatically and it can also
1244 * be dismissed by the user.
1246 * 4) var $msg = PMA_ajaxShowMessage('Some error', false);
1247 * This will show a message that will not disappear automatically, but it
1248 * can be dismissed by the user after he has finished reading it.
1250 * @param string message string containing the message to be shown.
1251 * optional, defaults to 'Loading...'
1252 * @param mixed timeout number of milliseconds for the message to be visible
1253 * optional, defaults to 5000. If set to 'false', the
1254 * notification will never disappear
1255 * @return jQuery object jQuery Element that holds the message div
1256 * this object can be passed to PMA_ajaxRemoveMessage()
1257 * to remove the notification
1259 function PMA_ajaxShowMessage(message, timeout)
1262 * @var self_closing Whether the notification will automatically disappear
1264 var self_closing = true;
1266 * @var dismissable Whether the user will be able to remove
1267 * the notification by clicking on it
1269 var dismissable = true;
1270 // Handle the case when a empty data.message is passed.
1271 // We don't want the empty message
1272 if (message == '') {
1274 } else if (! message) {
1275 // If the message is undefined, show the default
1276 message = PMA_messages['strLoading'];
1277 dismissable = false;
1278 self_closing = false;
1279 } else if (message == PMA_messages['strProcessingRequest']) {
1280 // This is another case where the message should not disappear
1281 dismissable = false;
1282 self_closing = false;
1284 // Figure out whether (or after how long) to remove the notification
1285 if (timeout == undefined) {
1287 } else if (timeout === false) {
1288 self_closing = false;
1290 // Create a parent element for the AJAX messages, if necessary
1291 if ($('#loading_parent').length == 0) {
1292 $('<div id="loading_parent"></div>')
1295 // Update message count to create distinct message elements every time
1296 ajax_message_count++;
1297 // Remove all old messages, if any
1298 $(".ajax_notification[id^=ajax_message_num]").remove();
1300 * @var $retval a jQuery object containing the reference
1301 * to the created AJAX message
1304 '<span class="ajax_notification" id="ajax_message_num_'
1305 + ajax_message_count +
1309 .appendTo("#loading_parent")
1312 // If the notification is self-closing we should create a callback to remove it
1316 .fadeOut('medium', function() {
1317 if ($(this).is('.dismissable')) {
1318 // Here we should destroy the qtip instance, but
1319 // due to a bug in qtip's implementation we can
1320 // only hide it without throwing JS errors.
1321 $(this).qtip('hide');
1323 // Remove the notification
1327 // If the notification is dismissable we need to add the relevant class to it
1328 // and add a tooltip so that the users know that it can be removed
1330 $retval.addClass('dismissable').css('cursor', 'pointer');
1332 * @var qOpts Options for "Dismiss notification" tooltip
1336 effect: { length: 0 },
1340 effect: { length: 0 },
1345 * Add a tooltip to the notification to let the user know that (s)he
1346 * can dismiss the ajax notification by clicking on it.
1348 PMA_createqTip($retval, PMA_messages['strDismiss'], qOpts);
1355 * Removes the message shown for an Ajax operation when it's completed
1357 * @param jQuery object jQuery Element that holds the notification
1361 function PMA_ajaxRemoveMessage($this_msgbox)
1363 if ($this_msgbox != undefined && $this_msgbox instanceof jQuery) {
1367 if ($this_msgbox.is('.dismissable')) {
1368 // Here we should destroy the qtip instance, but
1369 // due to a bug in qtip's implementation we can
1370 // only hide it without throwing JS errors.
1371 $this_msgbox.qtip('hide');
1373 $this_msgbox.remove();
1378 $(document).ready(function() {
1380 * Allows the user to dismiss a notification
1381 * created with PMA_ajaxShowMessage()
1383 $('.ajax_notification.dismissable').live('click', function () {
1384 PMA_ajaxRemoveMessage($(this));
1387 * The below two functions hide the "Dismiss notification" tooltip when a user
1388 * is hovering a link or button that is inside an ajax message
1390 $('.ajax_notification a, .ajax_notification button, .ajax_notification input')
1391 .live('mouseover', function () {
1392 $(this).parents('.ajax_notification').qtip('hide');
1394 $('.ajax_notification a, .ajax_notification button, .ajax_notification input')
1395 .live('mouseout', function () {
1396 $(this).parents('.ajax_notification').qtip('show');
1401 * Hides/shows the "Open in ENUM/SET editor" message, depending on the data type of the column currently selected
1403 function PMA_showNoticeForEnum(selectElement)
1405 var enum_notice_id = selectElement.attr("id").split("_")[1];
1406 enum_notice_id += "_" + (parseInt(selectElement.attr("id").split("_")[2]) + 1);
1407 var selectedType = selectElement.val();
1408 if (selectedType == "ENUM" || selectedType == "SET") {
1409 $("p[id='enum_notice_" + enum_notice_id + "']").show();
1411 $("p[id='enum_notice_" + enum_notice_id + "']").hide();
1416 * Generates a dialog box to pop up the create_table form
1418 function PMA_createTableDialog( $div, url , target)
1421 * @var button_options Object that stores the options passed to jQueryUI
1424 var button_options = {};
1425 // in the following function we need to use $(this)
1426 button_options[PMA_messages['strCancel']] = function() {$(this).closest('.ui-dialog-content').dialog('close').remove();}
1428 var button_options_error = {};
1429 button_options_error[PMA_messages['strOK']] = function() {$(this).closest('.ui-dialog-content').dialog('close').remove();}
1431 var $msgbox = PMA_ajaxShowMessage();
1433 $.get( target , url , function(data) {
1434 //in the case of an error, show the error message returned.
1435 if (data.success != undefined && data.success == false) {
1441 open: PMA_verifyColumnsProperties,
1442 buttons : button_options_error
1443 })// end dialog options
1444 //remove the redundant [Back] link in the error message.
1445 .find('fieldset').remove();
1447 var size = getWindowSize();
1452 dialogClass: 'create-table',
1457 position: ['left','top'],
1458 width: size.width-10,
1459 height: size.height-10,
1461 var dialog_id = $(this).attr('id');
1462 $(window).bind('resize.dialog-resizer', function() {
1463 clearTimeout(timeout);
1464 timeout = setTimeout(function() {
1465 var size = getWindowSize();
1466 $('#'+dialog_id).dialog('option', {
1467 width: size.width-10,
1468 height: size.height-10
1473 var $wrapper = $('<div>', {'id': 'content-hide'}).hide();
1474 $('body > *:not(.ui-dialog)').wrapAll($wrapper);
1477 .scrollTop(0) // for Chrome
1478 .closest('.ui-dialog').css({
1483 PMA_verifyColumnsProperties();
1485 // move the Cancel button next to the Save button
1486 var $button_pane = $('.ui-dialog-buttonpane');
1487 var $cancel_button = $button_pane.find('.ui-button');
1488 var $save_button = $('#create_table_form').find("input[name='do_save_data']");
1489 $cancel_button.insertAfter($save_button);
1490 $button_pane.hide();
1493 $(window).unbind('resize.dialog-resizer');
1494 $('#content-hide > *').unwrap();
1496 buttons: button_options
1497 }); // end dialog options
1499 PMA_convertFootnotesToTooltips($div);
1500 PMA_ajaxRemoveMessage($msgbox);
1506 * Creates a highcharts chart in the given container
1508 * @param var settings object with highcharts properties that should be applied. (See also http://www.highcharts.com/ref/)
1509 * requires at least settings.chart.renderTo and settings.series to be set.
1510 * In addition there may be an additional property object 'realtime' that allows for realtime charting:
1512 * url: adress to get the data from (will always add token, ajax_request=1 and chart_data=1 to the GET request)
1513 * type: the GET request will also add type=[value of the type property] to the request
1514 * callback: Callback function that should draw the point, it's called with 4 parameters in this order:
1515 * - the chart object
1516 * - the current response value of the GET request, JSON parsed
1517 * - the previous response value of the GET request, JSON parsed
1518 * - the number of added points
1519 * error: Callback function when the get request fails. TODO: Apply callback on timeouts aswell
1522 * @return object The created highcharts instance
1524 function PMA_createChart(passedSettings)
1526 var container = passedSettings.chart.renderTo;
1532 backgroundColor: 'none',
1534 /* Live charting support */
1536 var thisChart = this;
1537 var lastValue = null, curValue = null;
1538 var numLoadedPoints = 0, otherSum = 0;
1541 // No realtime updates for graphs that are being exported, and disabled when realtime is not set
1542 // Also don't do live charting if we don't have the server time
1543 if(thisChart.options.chart.forExport == true ||
1544 ! thisChart.options.realtime ||
1545 ! thisChart.options.realtime.callback ||
1546 ! server_time_diff) return;
1548 thisChart.options.realtime.timeoutCallBack = function() {
1549 thisChart.options.realtime.postRequest = $.post(
1550 thisChart.options.realtime.url,
1551 thisChart.options.realtime.postData,
1554 curValue = jQuery.parseJSON(data);
1556 if(thisChart.options.realtime.error)
1557 thisChart.options.realtime.error(err);
1561 if (lastValue==null) {
1562 diff = curValue.x - thisChart.xAxis[0].getExtremes().max;
1564 diff = parseInt(curValue.x - lastValue.x);
1567 thisChart.xAxis[0].setExtremes(
1568 thisChart.xAxis[0].getExtremes().min+diff,
1569 thisChart.xAxis[0].getExtremes().max+diff,
1573 thisChart.options.realtime.callback(thisChart,curValue,lastValue,numLoadedPoints);
1575 lastValue = curValue;
1578 // Timeout has been cleared => don't start a new timeout
1579 if (chart_activeTimeouts[container] == null) {
1583 chart_activeTimeouts[container] = setTimeout(
1584 thisChart.options.realtime.timeoutCallBack,
1585 thisChart.options.realtime.refreshRate
1590 chart_activeTimeouts[container] = setTimeout(thisChart.options.realtime.timeoutCallBack, 5);
1610 text: PMA_messages['strTotalCount']
1619 formatter: function() {
1620 return '<b>' + this.series.name +'</b><br/>' +
1621 Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '<br/>' +
1622 Highcharts.numberFormat(this.y, 2);
1631 /* Set/Get realtime chart default values */
1632 if(passedSettings.realtime) {
1633 if(!passedSettings.realtime.refreshRate) {
1634 passedSettings.realtime.refreshRate = 5000;
1637 if(!passedSettings.realtime.numMaxPoints) {
1638 passedSettings.realtime.numMaxPoints = 30;
1641 // Allow custom POST vars to be added
1642 passedSettings.realtime.postData = $.extend(false,{ ajax_request: true, chart_data: 1, type: passedSettings.realtime.type },passedSettings.realtime.postData);
1644 if(server_time_diff) {
1645 settings.xAxis.min = new Date().getTime() - server_time_diff - passedSettings.realtime.numMaxPoints * passedSettings.realtime.refreshRate;
1646 settings.xAxis.max = new Date().getTime() - server_time_diff + passedSettings.realtime.refreshRate;
1650 // Overwrite/Merge default settings with passedsettings
1651 $.extend(true,settings,passedSettings);
1653 return new Highcharts.Chart(settings);
1658 * Creates a Profiling Chart. Used in sql.php and server_status.js
1660 function PMA_createProfilingChart(data, options)
1662 return PMA_createChart($.extend(true, {
1664 renderTo: 'profilingchart',
1667 title: { text:'', margin:0 },
1670 name: PMA_messages['strQueryExecutionTime'],
1675 allowPointSelect: true,
1680 formatter: function() {
1681 return '<b>'+ this.point.name +'</b><br/>'+ Highcharts.numberFormat(this.percentage, 2) +' %';
1687 formatter: function() {
1688 return '<b>'+ this.point.name +'</b><br/>'+PMA_prettyProfilingNum(this.y)+'<br/>('+Highcharts.numberFormat(this.percentage, 2) +' %)';
1695 * Formats a profiling duration nicely (in us and ms time). Used in PMA_createProfilingChart() and server_status.js
1697 * @param integer Number to be formatted, should be in the range of microsecond to second
1698 * @param integer Acuracy, how many numbers right to the comma should be
1699 * @return string The formatted number
1701 function PMA_prettyProfilingNum(num, acc)
1706 acc = Math.pow(10,acc);
1707 if (num * 1000 < 0.1) {
1708 num = Math.round(acc * (num * 1000 * 1000)) / acc + 'µ';
1709 } else if (num < 0.1) {
1710 num = Math.round(acc * (num * 1000)) / acc + 'm';
1712 num = Math.round(acc * num) / acc;
1720 * Formats a SQL Query nicely with newlines and indentation. Depends on Codemirror and MySQL Mode!
1722 * @param string Query to be formatted
1723 * @return string The formatted query
1725 function PMA_SQLPrettyPrint(string)
1727 var mode = CodeMirror.getMode({},"text/x-mysql");
1728 var stream = new CodeMirror.StringStream(string);
1729 var state = mode.startState();
1730 var token, tokens = [];
1732 var tabs = function(cnt) {
1734 for (var i=0; i<4*cnt; i++)
1739 // "root-level" statements
1741 'select': ['select', 'from','on','where','having','limit','order by','group by'],
1742 'update': ['update', 'set','where'],
1743 'insert into': ['insert into', 'values']
1745 // don't put spaces before these tokens
1746 var spaceExceptionsBefore = { ';':true, ',': true, '.': true, '(': true };
1747 // don't put spaces after these tokens
1748 var spaceExceptionsAfter = { '.': true };
1750 // Populate tokens array
1752 while (! stream.eol()) {
1753 stream.start = stream.pos;
1754 token = mode.token(stream, state);
1756 tokens.push([token, stream.current().toLowerCase()]);
1760 var currentStatement = tokens[0][1];
1762 if(! statements[currentStatement]) {
1765 // Holds all currently opened code blocks (statement, function or generic)
1766 var blockStack = [];
1767 // Holds the type of block from last iteration (the current is in blockStack[0])
1769 // If a new code block is found, newBlock contains its type for one iteration and vice versa for endBlock
1770 var newBlock, endBlock;
1771 // How much to indent in the current line
1772 var indentLevel = 0;
1773 // Holds the "root-level" statements
1774 var statementPart, lastStatementPart = statements[currentStatement][0];
1776 blockStack.unshift('statement');
1778 // Iterate through every token and format accordingly
1779 for (var i = 0; i < tokens.length; i++) {
1780 previousBlock = blockStack[0];
1782 // New block => push to stack
1783 if (tokens[i][1] == '(') {
1784 if (i < tokens.length - 1 && tokens[i+1][0] == 'statement-verb') {
1785 blockStack.unshift(newBlock = 'statement');
1786 } else if (i > 0 && tokens[i-1][0] == 'builtin') {
1787 blockStack.unshift(newBlock = 'function');
1789 blockStack.unshift(newBlock = 'generic');
1795 // Block end => pop from stack
1796 if (tokens[i][1] == ')') {
1797 endBlock = blockStack[0];
1803 // A subquery is starting
1804 if (i > 0 && newBlock == 'statement') {
1806 output += "\n" + tabs(indentLevel) + tokens[i][1] + ' ' + tokens[i+1][1].toUpperCase() + "\n" + tabs(indentLevel + 1);
1807 currentStatement = tokens[i+1][1];
1812 // A subquery is ending
1813 if (endBlock == 'statement' && indentLevel > 0) {
1814 output += "\n" + tabs(indentLevel);
1818 // One less indentation for statement parts (from, where, order by, etc.) and a newline
1819 statementPart = statements[currentStatement].indexOf(tokens[i][1]);
1820 if (statementPart != -1) {
1821 if (i > 0) output += "\n";
1822 output += tabs(indentLevel) + tokens[i][1].toUpperCase();
1823 output += "\n" + tabs(indentLevel + 1);
1824 lastStatementPart = tokens[i][1];
1826 // Normal indentatin and spaces for everything else
1828 if (! spaceExceptionsBefore[tokens[i][1]]
1829 && ! (i > 0 && spaceExceptionsAfter[tokens[i-1][1]])
1830 && output.charAt(output.length -1) != ' ' ) {
1833 if (tokens[i][0] == 'keyword') {
1834 output += tokens[i][1].toUpperCase();
1836 output += tokens[i][1];
1840 // split columns in select and 'update set' clauses, but only inside statements blocks
1841 if (( lastStatementPart == 'select' || lastStatementPart == 'where' || lastStatementPart == 'set')
1842 && tokens[i][1]==',' && blockStack[0] == 'statement') {
1844 output += "\n" + tabs(indentLevel + 1);
1847 // split conditions in where clauses, but only inside statements blocks
1848 if (lastStatementPart == 'where'
1849 && (tokens[i][1]=='and' || tokens[i][1]=='or' || tokens[i][1]=='xor')) {
1851 if (blockStack[0] == 'statement') {
1852 output += "\n" + tabs(indentLevel + 1);
1854 // Todo: Also split and or blocks in newlines & identation++
1855 //if(blockStack[0] == 'generic')
1863 * jQuery function that uses jQueryUI's dialogs to confirm with user. Does not
1864 * return a jQuery object yet and hence cannot be chained
1866 * @param string question
1867 * @param string url URL to be passed to the callbackFn to make
1869 * @param function callbackFn callback to execute after user clicks on OK
1872 jQuery.fn.PMA_confirm = function(question, url, callbackFn) {
1873 if (PMA_messages['strDoYouReally'] == '') {
1878 * @var button_options Object that stores the options passed to jQueryUI
1881 var button_options = {};
1882 button_options[PMA_messages['strOK']] = function(){
1883 $(this).dialog("close").remove();
1885 if($.isFunction(callbackFn)) {
1886 callbackFn.call(this, url);
1889 button_options[PMA_messages['strCancel']] = function() {$(this).dialog("close").remove();}
1891 $('<div id="confirm_dialog"></div>')
1893 .dialog({buttons: button_options});
1897 * jQuery function to sort a table's body after a new row has been appended to it.
1898 * Also fixes the even/odd classes of the table rows at the end.
1900 * @param string text_selector string to select the sortKey's text
1902 * @return jQuery Object for chaining purposes
1904 jQuery.fn.PMA_sort_table = function(text_selector) {
1905 return this.each(function() {
1908 * @var table_body Object referring to the table's <tbody> element
1910 var table_body = $(this);
1912 * @var rows Object referring to the collection of rows in {@link table_body}
1914 var rows = $(this).find('tr').get();
1916 //get the text of the field that we will sort by
1917 $.each(rows, function(index, row) {
1918 row.sortKey = $.trim($(row).find(text_selector).text().toLowerCase());
1921 //get the sorted order
1922 rows.sort(function(a,b) {
1923 if(a.sortKey < b.sortKey) {
1926 if(a.sortKey > b.sortKey) {
1932 //pull out each row from the table and then append it according to it's order
1933 $.each(rows, function(index, row) {
1934 $(table_body).append(row);
1938 //Re-check the classes of each row
1939 $(this).find('tr:odd')
1940 .removeClass('even').addClass('odd')
1943 .removeClass('odd').addClass('even');
1948 * jQuery coding for 'Create Table'. Used on db_operations.php,
1949 * db_structure.php and db_tracking.php (i.e., wherever
1950 * libraries/display_create_table.lib.php is used)
1952 * Attach Ajax Event handlers for Create Table
1954 $(document).ready(function() {
1957 * Attach event handler to the submit action of the create table minimal form
1958 * and retrieve the full table form and display it in a dialog
1960 $("#create_table_form_minimal.ajax").live('submit', function(event) {
1961 event.preventDefault();
1963 PMA_prepareForAjaxRequest($form);
1965 /*variables which stores the common attributes*/
1966 var url = $form.serialize();
1967 var action = $form.attr('action');
1968 var $div = $('<div id="create_table_dialog"></div>');
1970 /*Calling to the createTableDialog function*/
1971 PMA_createTableDialog($div, url, action);
1973 // empty table name and number of columns from the minimal form
1974 $form.find('input[name=table],input[name=num_fields]').val('');
1978 * Attach event handler for submission of create table form (save)
1980 * @uses PMA_ajaxShowMessage()
1981 * @uses $.PMA_sort_table()
1984 // .live() must be called after a selector, see http://api.jquery.com/live
1985 $("#create_table_form input[name=do_save_data]").live('click', function(event) {
1986 event.preventDefault();
1989 * @var the_form object referring to the create table form
1991 var $form = $("#create_table_form");
1994 * First validate the form; if there is a problem, avoid submitting it
1996 * checkTableEditForm() needs a pure element and not a jQuery object,
1997 * this is why we pass $form[0] as a parameter (the jQuery object
1998 * is actually an array of DOM elements)
2001 if (checkTableEditForm($form[0], $form.find('input[name=orig_num_fields]').val())) {
2002 // OK, form passed validation step
2003 if ($form.hasClass('ajax')) {
2004 PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
2005 PMA_prepareForAjaxRequest($form);
2006 //User wants to submit the form
2007 $.post($form.attr('action'), $form.serialize() + "&do_save_data=" + $(this).val(), function(data) {
2008 if(data.success == true) {
2009 $('#properties_message')
2010 .removeClass('error')
2012 PMA_ajaxShowMessage(data.message);
2013 // Only if the create table dialog (distinct panel) exists
2014 if ($("#create_table_dialog").length > 0) {
2015 $("#create_table_dialog").dialog("close").remove();
2019 * @var tables_table Object referring to the <tbody> element that holds the list of tables
2021 var tables_table = $("#tablesForm").find("tbody").not("#tbl_summary_row");
2022 // this is the first table created in this db
2023 if (tables_table.length == 0) {
2024 if (window.parent && window.parent.frame_content) {
2025 window.parent.frame_content.location.reload();
2029 * @var curr_last_row Object referring to the last <tr> element in {@link tables_table}
2031 var curr_last_row = $(tables_table).find('tr:last');
2033 * @var curr_last_row_index_string String containing the index of {@link curr_last_row}
2035 var curr_last_row_index_string = $(curr_last_row).find('input:checkbox').attr('id').match(/\d+/)[0];
2037 * @var curr_last_row_index Index of {@link curr_last_row}
2039 var curr_last_row_index = parseFloat(curr_last_row_index_string);
2041 * @var new_last_row_index Index of the new row to be appended to {@link tables_table}
2043 var new_last_row_index = curr_last_row_index + 1;
2045 * @var new_last_row_id String containing the id of the row to be appended to {@link tables_table}
2047 var new_last_row_id = 'checkbox_tbl_' + new_last_row_index;
2049 data.new_table_string = data.new_table_string.replace(/checkbox_tbl_/, new_last_row_id);
2051 $(data.new_table_string)
2052 .appendTo(tables_table);
2055 $(tables_table).PMA_sort_table('th');
2057 // Adjust summary row
2061 //Refresh navigation frame as a new table has been added
2062 if (window.parent && window.parent.frame_navigation) {
2063 window.parent.frame_navigation.location.reload();
2066 $('#properties_message')
2069 // scroll to the div containing the error message
2070 $('#properties_message')[0].scrollIntoView();
2073 } // end if ($form.hasClass('ajax')
2076 $form.append('<input type="hidden" name="do_save_data" value="save" />');
2079 } // end if (checkTableEditForm() )
2080 }) // end create table form (save)
2083 * Attach event handler for create table form (add fields)
2085 * @uses PMA_ajaxShowMessage()
2086 * @uses $.PMA_sort_table()
2087 * @uses window.parent.refreshNavigation()
2090 // .live() must be called after a selector, see http://api.jquery.com/live
2091 $("#create_table_form.ajax input[name=submit_num_fields]").live('click', function(event) {
2092 event.preventDefault();
2095 * @var the_form object referring to the create table form
2097 var $form = $("#create_table_form");
2099 var $msgbox = PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
2100 PMA_prepareForAjaxRequest($form);
2102 //User wants to add more fields to the table
2103 $.post($form.attr('action'), $form.serialize() + "&submit_num_fields=" + $(this).val(), function(data) {
2104 // if 'create_table_dialog' exists
2105 if ($("#create_table_dialog").length > 0) {
2106 $("#create_table_dialog").html(data);
2108 // if 'create_table_div' exists
2109 if ($("#create_table_div").length > 0) {
2110 $("#create_table_div").html(data);
2112 PMA_verifyColumnsProperties();
2113 PMA_ajaxRemoveMessage($msgbox);
2116 }) // end create table form (add fields)
2118 }, 'top.frame_content'); //end $(document).ready for 'Create Table'
2121 * jQuery coding for 'Change Table' and 'Add Column'. Used on tbl_structure.php *
2122 * Attach Ajax Event handlers for Change Table
2124 $(document).ready(function() {
2126 *Ajax action for submitting the "Column Change" and "Add Column" form
2128 $("#append_fields_form input[name=do_save_data]").live('click', function(event) {
2129 event.preventDefault();
2131 * @var the_form object referring to the export form
2133 var $form = $("#append_fields_form");
2136 * First validate the form; if there is a problem, avoid submitting it
2138 * checkTableEditForm() needs a pure element and not a jQuery object,
2139 * this is why we pass $form[0] as a parameter (the jQuery object
2140 * is actually an array of DOM elements)
2142 if (checkTableEditForm($form[0], $form.find('input[name=orig_num_fields]').val())) {
2143 // OK, form passed validation step
2144 if ($form.hasClass('ajax')) {
2145 PMA_prepareForAjaxRequest($form);
2146 //User wants to submit the form
2147 $.post($form.attr('action'), $form.serialize()+"&do_save_data=Save", function(data) {
2148 if ($("#sqlqueryresults").length != 0) {
2149 $("#sqlqueryresults").remove();
2150 } else if ($(".error").length != 0) {
2151 $(".error").remove();
2153 if (data.success == true) {
2154 PMA_ajaxShowMessage(data.message);
2155 $("<div id='sqlqueryresults'></div>").insertAfter("#floating_menubar");
2156 $("#sqlqueryresults").html(data.sql_query);
2157 $("#result_query .notice").remove();
2158 $("#result_query").prepend((data.message));
2159 if ($("#change_column_dialog").length > 0) {
2160 $("#change_column_dialog").dialog("close").remove();
2161 } else if ($("#add_columns").length > 0) {
2162 $("#add_columns").dialog("close").remove();
2164 /*Reload the field form*/
2165 $.post($("#fieldsForm").attr('action'), $("#fieldsForm").serialize()+"&ajax_request=true", function(form_data) {
2166 $("#fieldsForm").remove();
2167 $("#addColumns").remove();
2168 var $temp_div = $("<div id='temp_div'><div>").append(form_data);
2169 if ($("#sqlqueryresults").length != 0) {
2170 $temp_div.find("#fieldsForm").insertAfter("#sqlqueryresults");
2172 $temp_div.find("#fieldsForm").insertAfter(".error");
2174 $temp_div.find("#addColumns").insertBefore("iframe.IE_hack");
2175 /*Call the function to display the more options in table*/
2176 displayMoreTableOpts();
2179 var $temp_div = $("<div id='temp_div'><div>").append(data);
2180 var $error = $temp_div.find(".error code").addClass("error");
2181 PMA_ajaxShowMessage($error, false);
2186 $form.append('<input type="hidden" name="do_save_data" value="Save" />');
2190 }) // end change table button "do_save_data"
2192 }, 'top.frame_content'); //end $(document).ready for 'Change Table'
2195 * jQuery coding for 'Table operations'. Used on tbl_operations.php
2196 * Attach Ajax Event handlers for Table operations
2198 $(document).ready(function() {
2200 *Ajax action for submitting the "Alter table order by"
2202 $("#alterTableOrderby.ajax").live('submit', function(event) {
2203 event.preventDefault();
2204 var $form = $(this);
2206 PMA_prepareForAjaxRequest($form);
2207 /*variables which stores the common attributes*/
2208 $.post($form.attr('action'), $form.serialize()+"&submitorderby=Go", function(data) {
2209 if ($("#sqlqueryresults").length != 0) {
2210 $("#sqlqueryresults").remove();
2212 if ($("#result_query").length != 0) {
2213 $("#result_query").remove();
2215 if (data.success == true) {
2216 PMA_ajaxShowMessage(data.message);
2217 $("<div id='sqlqueryresults'></div>").insertAfter("#floating_menubar");
2218 $("#sqlqueryresults").html(data.sql_query);
2219 $("#result_query .notice").remove();
2220 $("#result_query").prepend((data.message));
2222 var $temp_div = $("<div id='temp_div'></div>")
2223 $temp_div.html(data.error);
2224 var $error = $temp_div.find("code").addClass("error");
2225 PMA_ajaxShowMessage($error, false);
2228 });//end of alterTableOrderby ajax submit
2231 *Ajax action for submitting the "Copy table"
2233 $("#copyTable.ajax input[name='submit_copy']").live('click', function(event) {
2234 event.preventDefault();
2235 var $form = $("#copyTable");
2236 if($form.find("input[name='switch_to_new']").attr('checked')) {
2237 $form.append('<input type="hidden" name="submit_copy" value="Go" />');
2238 $form.removeClass('ajax');
2239 $form.find("#ajax_request_hidden").remove();
2242 PMA_prepareForAjaxRequest($form);
2243 /*variables which stores the common attributes*/
2244 $.post($form.attr('action'), $form.serialize()+"&submit_copy=Go", function(data) {
2245 if ($("#sqlqueryresults").length != 0) {
2246 $("#sqlqueryresults").remove();
2248 if ($("#result_query").length != 0) {
2249 $("#result_query").remove();
2251 if (data.success == true) {
2252 PMA_ajaxShowMessage(data.message);
2253 $("<div id='sqlqueryresults'></div>").insertAfter("#floating_menubar");
2254 $("#sqlqueryresults").html(data.sql_query);
2255 $("#result_query .notice").remove();
2256 $("#result_query").prepend((data.message));
2257 $("#copyTable").find("select[name='target_db'] option").filterByValue(data.db).attr('selected', 'selected');
2259 //Refresh navigation frame when the table is coppied
2260 if (window.parent && window.parent.frame_navigation) {
2261 window.parent.frame_navigation.location.reload();
2264 var $temp_div = $("<div id='temp_div'></div>");
2265 $temp_div.html(data.error);
2266 var $error = $temp_div.find("code").addClass("error");
2267 PMA_ajaxShowMessage($error, false);
2271 });//end of copyTable ajax submit
2274 *Ajax events for actions in the "Table maintenance"
2276 $("#tbl_maintenance.ajax li a.maintain_action").live('click', function(event) {
2277 event.preventDefault();
2278 var $link = $(this);
2279 var href = $link.attr("href");
2280 href = href.split('?');
2281 if ($("#sqlqueryresults").length != 0) {
2282 $("#sqlqueryresults").remove();
2284 if ($("#result_query").length != 0) {
2285 $("#result_query").remove();
2287 //variables which stores the common attributes
2288 $.post(href[0], href[1]+"&ajax_request=true", function(data) {
2289 if (data.success == undefined) {
2290 var $temp_div = $("<div id='temp_div'></div>");
2291 $temp_div.html(data);
2292 var $success = $temp_div.find("#result_query .success");
2293 PMA_ajaxShowMessage($success);
2294 $("<div id='sqlqueryresults' class='ajax'></div>").insertAfter("#floating_menubar");
2295 $("#sqlqueryresults").html(data);
2297 $("#sqlqueryresults").children("fieldset").remove();
2298 } else if (data.success == true ) {
2299 PMA_ajaxShowMessage(data.message);
2300 $("<div id='sqlqueryresults' class='ajax'></div>").insertAfter("#floating_menubar");
2301 $("#sqlqueryresults").html(data.sql_query);
2303 var $temp_div = $("<div id='temp_div'></div>");
2304 $temp_div.html(data.error);
2305 var $error = $temp_div.find("code").addClass("error");
2306 PMA_ajaxShowMessage($error, false);
2309 });//end of table maintanance ajax click
2311 }, 'top.frame_content'); //end $(document).ready for 'Table operations'
2315 * Attach Ajax event handlers for Drop Database. Moved here from db_structure.js
2316 * as it was also required on db_create.php
2318 * @uses $.PMA_confirm()
2319 * @uses PMA_ajaxShowMessage()
2320 * @uses window.parent.refreshNavigation()
2321 * @uses window.parent.refreshMain()
2322 * @see $cfg['AjaxEnable']
2324 $(document).ready(function() {
2325 $("#drop_db_anchor").live('click', function(event) {
2326 event.preventDefault();
2328 //context is top.frame_content, so we need to use window.parent.db to access the db var
2330 * @var question String containing the question to be asked for confirmation
2332 var question = PMA_messages['strDropDatabaseStrongWarning'] + '\n' + PMA_messages['strDoYouReally'] + ' :\n' + 'DROP DATABASE ' + escapeHtml(window.parent.db);
2334 $(this).PMA_confirm(question, $(this).attr('href') ,function(url) {
2336 PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
2337 $.get(url, {'is_js_confirmed': '1', 'ajax_request': true}, function(data) {
2338 //Database deleted successfully, refresh both the frames
2339 window.parent.refreshNavigation();
2340 window.parent.refreshMain();
2342 }); // end $.PMA_confirm()
2343 }); //end of Drop Database Ajax action
2344 }) // end of $(document).ready() for Drop Database
2347 * Attach Ajax event handlers for 'Create Database'. Used wherever libraries/
2348 * display_create_database.lib.php is used, ie main.php and server_databases.php
2350 * @uses PMA_ajaxShowMessage()
2351 * @see $cfg['AjaxEnable']
2353 $(document).ready(function() {
2355 $('#create_database_form.ajax').live('submit', function(event) {
2356 event.preventDefault();
2360 PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
2361 PMA_prepareForAjaxRequest($form);
2363 $.post($form.attr('action'), $form.serialize(), function(data) {
2364 if(data.success == true) {
2365 PMA_ajaxShowMessage(data.message);
2367 //Append database's row to table
2368 $("#tabledatabases")
2370 .append(data.new_db_string)
2371 .PMA_sort_table('.name')
2372 .find('#db_summary_row')
2373 .appendTo('#tabledatabases tbody')
2374 .removeClass('odd even');
2376 var $databases_count_object = $('#databases_count');
2377 var databases_count = parseInt($databases_count_object.text());
2378 $databases_count_object.text(++databases_count);
2379 //Refresh navigation frame as a new database has been added
2380 if (window.parent && window.parent.frame_navigation) {
2381 window.parent.frame_navigation.location.reload();
2385 PMA_ajaxShowMessage(data.error, false);
2388 }) // end $().live()
2389 }) // end $(document).ready() for Create Database
2392 * Attach Ajax event handlers for 'Change Password' on main.php
2394 $(document).ready(function() {
2397 * Attach Ajax event handler on the change password anchor
2398 * @see $cfg['AjaxEnable']
2400 $('#change_password_anchor.dialog_active').live('click',function(event) {
2401 event.preventDefault();
2404 $('#change_password_anchor.ajax').live('click', function(event) {
2405 event.preventDefault();
2406 $(this).removeClass('ajax').addClass('dialog_active');
2408 * @var button_options Object containing options to be passed to jQueryUI's dialog
2410 var button_options = {};
2411 button_options[PMA_messages['strCancel']] = function() {$(this).dialog('close').remove();}
2412 $.get($(this).attr('href'), {'ajax_request': true}, function(data) {
2413 $('<div id="change_password_dialog"></div>')
2415 title: PMA_messages['strChangePassword'],
2417 close: function(ev,ui) {$(this).remove();},
2418 buttons : button_options,
2419 beforeClose: function(ev,ui){ $('#change_password_anchor.dialog_active').removeClass('dialog_active').addClass('ajax')}
2422 displayPasswordGenerateButton();
2424 }) // end handler for change password anchor
2427 * Attach Ajax event handler for Change Password form submission
2429 * @uses PMA_ajaxShowMessage()
2430 * @see $cfg['AjaxEnable']
2432 $("#change_password_form.ajax").find('input[name=change_pw]').live('click', function(event) {
2433 event.preventDefault();
2436 * @var the_form Object referring to the change password form
2438 var the_form = $("#change_password_form");
2441 * @var this_value String containing the value of the submit button.
2442 * Need to append this for the change password form on Server Privileges
2445 var this_value = $(this).val();
2447 var $msgbox = PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
2448 $(the_form).append('<input type="hidden" name="ajax_request" value="true" />');
2450 $.post($(the_form).attr('action'), $(the_form).serialize() + '&change_pw='+ this_value, function(data) {
2451 if(data.success == true) {
2452 $("#floating_menubar").after(data.sql_query);
2453 $("#change_password_dialog").hide().remove();
2454 $("#edit_user_dialog").dialog("close").remove();
2455 $('#change_password_anchor.dialog_active').removeClass('dialog_active').addClass('ajax');
2456 PMA_ajaxRemoveMessage($msgbox);
2459 PMA_ajaxShowMessage(data.error, false);
2462 }) // end handler for Change Password form submission
2463 }) // end $(document).ready() for Change Password
2466 * Toggle the hiding/showing of the "Open in ENUM/SET editor" message when
2467 * the page loads and when the selected data type changes
2469 $(document).ready(function() {
2470 // is called here for normal page loads and also when opening
2471 // the Create table dialog
2472 PMA_verifyColumnsProperties();
2474 // needs live() to work also in the Create Table dialog
2475 $("select[class='column_type']").live('change', function() {
2476 PMA_showNoticeForEnum($(this));
2478 $(".default_type").live('change', function() {
2479 PMA_hideShowDefaultValue($(this));
2483 function PMA_verifyColumnsProperties()
2485 $("select[class='column_type']").each(function() {
2486 PMA_showNoticeForEnum($(this));
2488 $(".default_type").each(function() {
2489 PMA_hideShowDefaultValue($(this));
2494 * Hides/shows the default value input field, depending on the default type
2496 function PMA_hideShowDefaultValue($default_type)
2498 if ($default_type.val() == 'USER_DEFINED') {
2499 $default_type.siblings('.default_value').show().focus();
2501 $default_type.siblings('.default_value').hide();
2506 * @var $enum_editor_dialog An object that points to the jQuery
2507 * dialog of the ENUM/SET editor
2509 var $enum_editor_dialog = null;
2511 * Opens the ENUM/SET editor and controls its functions
2513 $(document).ready(function() {
2514 $("a.open_enum_editor").live('click', function() {
2515 // Get the name of the column that is being edited
2516 var colname = $(this).closest('tr').find('input:first').val();
2517 // And use it to make up a title for the page
2518 if (colname.length < 1) {
2519 var title = PMA_messages['enum_newColumnVals'];
2521 var title = PMA_messages['enum_columnVals'].replace(
2523 '"' + decodeURIComponent(colname) + '"'
2526 // Get the values as a string
2527 var inputstring = $(this)
2531 // Escape html entities
2532 inputstring = $('<div/>')
2535 // Parse the values, escaping quotes and
2536 // slashes on the fly, into an array
2538 // There is a PHP port of the below parser in enum_editor.php
2539 // If you are fixing something here, you need to also update the PHP port.
2541 var in_string = false;
2542 var curr, next, buffer = '';
2543 for (var i=0; i<inputstring.length; i++) {
2544 curr = inputstring.charAt(i);
2545 next = i == inputstring.length ? '' : inputstring.charAt(i+1);
2546 if (! in_string && curr == "'") {
2548 } else if (in_string && curr == "\\" && next == "\\") {
2551 } else if (in_string && next == "'" && (curr == "'" || curr == "\\")) {
2554 } else if (in_string && curr == "'") {
2556 values.push(buffer);
2558 } else if (in_string) {
2562 if (buffer.length > 0) {
2563 // The leftovers in the buffer are the last value (if any)
2564 values.push(buffer);
2567 // If there are no values, maybe the user is about to make a
2568 // new list so we add a few for him/her to get started with.
2569 if (values.length == 0) {
2570 values.push('','','','');
2572 // Add the parsed values to the editor
2573 var drop_icon = PMA_getImage('b_drop.png');
2574 for (var i=0; i<values.length; i++) {
2575 fields += "<tr><td>"
2576 + "<input type='text' value='" + values[i] + "'/>"
2577 + "</td><td class='drop'>"
2582 * @var dialog HTML code for the ENUM/SET dialog
2584 var dialog = "<div id='enum_editor'>"
2586 + "<legend>" + title + "</legend>"
2587 + "<p>" + PMA_getImage('s_notice.png')
2588 + PMA_messages['enum_hint'] + "</p>"
2589 + "<table class='values'>" + fields + "</table>"
2590 + "</fieldset><fieldset class='tblFooters'>"
2591 + "<table class='add'><tr><td>"
2592 + "<div class='slider'></div>"
2594 + "<form><div><input type='submit' class='add_value' value='"
2595 + PMA_messages['enum_addValue'].replace(/%d/, 1)
2596 + "'/></div></form>"
2597 + "</td></tr></table>"
2598 + "<input type='hidden' value='" // So we know which column's data is being edited
2599 + $(this).closest('td').find("input").attr("id")
2604 * @var Defines functions to be called when the buttons in
2605 * the buttonOptions jQuery dialog bar are pressed
2607 var buttonOptions = {};
2608 buttonOptions[PMA_messages['strGo']] = function () {
2609 // When the submit button is clicked,
2610 // put the data back into the original form
2611 var value_array = new Array();
2612 $(this).find(".values input").each(function(index, elm) {
2613 var val = elm.value.replace(/\\/g, '\\\\').replace(/'/g, "''");
2614 value_array.push("'" + val + "'");
2616 // get the Length/Values text field where this value belongs
2617 var values_id = $(this).find("input[type='hidden']").attr("value");
2618 $("input[id='" + values_id + "']").attr("value", value_array.join(","));
2619 $(this).dialog("close");
2621 buttonOptions[PMA_messages['strClose']] = function () {
2622 $(this).dialog("close");
2625 var width = parseInt(
2626 (parseInt($('html').css('font-size'), 10)/13)*340,
2632 $enum_editor_dialog = $(dialog).dialog({
2635 title: PMA_messages['enum_editor'],
2636 buttons: buttonOptions,
2638 // Focus the "Go" button after opening the dialog
2639 $(this).closest('.ui-dialog').find('.ui-dialog-buttonpane button:first').focus();
2645 // slider for choosing how many fields to add
2646 $enum_editor_dialog.find(".slider").slider({
2652 slide: function( event, ui ) {
2653 $(this).closest('table').find('input[type=submit]').val(
2654 PMA_messages['enum_addValue'].replace(/%d/, ui.value)
2658 // Focus the slider, otherwise it looks nearly transparent
2659 $('.ui-slider-handle').addClass('ui-state-focus');
2663 // When "add a new value" is clicked, append an empty text field
2664 $("input.add_value").live('click', function(e) {
2666 var num_new_rows = $enum_editor_dialog.find("div.slider").slider('value');
2667 while (num_new_rows--) {
2668 $enum_editor_dialog.find('.values')
2670 "<tr style='display: none;'><td>"
2671 + "<input type='text' />"
2672 + "</td><td class='drop'>"
2673 + PMA_getImage('b_drop.png')
2681 // Removes the specified row from the enum editor
2682 $("#enum_editor td.drop").live('click', function() {
2683 $(this).closest('tr').hide('fast', function () {
2690 * Hides certain table structure actions, replacing them
2691 * with the word "More". They are displayed in a dropdown
2692 * menu when the user hovers over the word "More."
2694 $(document).ready(function() {
2695 displayMoreTableOpts();
2698 function displayMoreTableOpts()
2700 // Remove the actions from the table cells (they are available by default for JavaScript-disabled browsers)
2701 // if the table is not a view or information_schema (otherwise there is only one action to hide and there's no point)
2702 if($("input[type='hidden'][name='table_type']").val() == "table") {
2703 var $table = $("table[id='tablestructure']");
2704 $table.find("td[class='browse']").remove();
2705 $table.find("td[class='primary']").remove();
2706 $table.find("td[class='unique']").remove();
2707 $table.find("td[class='index']").remove();
2708 $table.find("td[class='fulltext']").remove();
2709 $table.find("td[class='spatial']").remove();
2710 $table.find("th[class='action']").attr("colspan", 3);
2712 // Display the "more" text
2713 $table.find("td[class='more_opts']").show();
2715 // Position the dropdown
2716 $(".structure_actions_dropdown").each(function() {
2717 // Optimize DOM querying
2718 var $this_dropdown = $(this);
2719 // The top offset must be set for IE even if it didn't change
2720 var cell_right_edge_offset = $this_dropdown.parent().position().left + $this_dropdown.parent().innerWidth();
2721 var left_offset = cell_right_edge_offset - $this_dropdown.innerWidth();
2722 var top_offset = $this_dropdown.parent().position().top + $this_dropdown.parent().innerHeight();
2723 $this_dropdown.offset({ top: top_offset, left: left_offset });
2726 // A hack for IE6 to prevent the after_field select element from being displayed on top of the dropdown by
2727 // positioning an iframe directly on top of it
2728 var $after_field = $("select[name='after_field']");
2729 $("iframe[class='IE_hack']")
2730 .width($after_field.width())
2731 .height($after_field.height())
2733 top: $after_field.offset().top,
2734 left: $after_field.offset().left
2737 // When "more" is hovered over, show the hidden actions
2738 $table.find("td[class='more_opts']")
2739 .mouseenter(function() {
2740 if($.browser.msie && $.browser.version == "6.0") {
2741 $("iframe[class='IE_hack']")
2743 .width($after_field.width()+4)
2744 .height($after_field.height()+4)
2746 top: $after_field.offset().top,
2747 left: $after_field.offset().left
2750 $(".structure_actions_dropdown").hide(); // Hide all the other ones that may be open
2751 $(this).children(".structure_actions_dropdown").show();
2752 // Need to do this again for IE otherwise the offset is wrong
2753 if($.browser.msie) {
2754 var left_offset_IE = $(this).offset().left + $(this).innerWidth() - $(this).children(".structure_actions_dropdown").innerWidth();
2755 var top_offset_IE = $(this).offset().top + $(this).innerHeight();
2756 $(this).children(".structure_actions_dropdown").offset({
2758 left: left_offset_IE });
2761 .mouseleave(function() {
2762 $(this).children(".structure_actions_dropdown").hide();
2763 if($.browser.msie && $.browser.version == "6.0") {
2764 $("iframe[class='IE_hack']").hide();
2770 $(document).ready(function(){
2771 PMA_convertFootnotesToTooltips();
2775 * Ensures indexes names are valid according to their type and, for a primary
2776 * key, lock index name to 'PRIMARY'
2777 * @param string form_id Variable which parses the form name as
2779 * @return boolean false if there is no index form, true else
2781 function checkIndexName(form_id)
2783 if ($("#"+form_id).length == 0) {
2787 // Gets the elements pointers
2788 var $the_idx_name = $("#input_index_name");
2789 var $the_idx_type = $("#select_index_type");
2791 // Index is a primary key
2792 if ($the_idx_type.find("option:selected").attr("value") == 'PRIMARY') {
2793 $the_idx_name.attr("value", 'PRIMARY');
2794 $the_idx_name.attr("disabled", true);
2799 if ($the_idx_name.attr("value") == 'PRIMARY') {
2800 $the_idx_name.attr("value", '');
2802 $the_idx_name.attr("disabled", false);
2806 } // end of the 'checkIndexName()' function
2809 * function to convert the footnotes to tooltips
2811 * @param jquery-Object $div a div jquery object which specifies the
2812 * domain for searching footnootes. If we
2813 * ommit this parameter the function searches
2814 * the footnotes in the whole body
2816 function PMA_convertFootnotesToTooltips($div)
2818 // Hide the footnotes from the footer (which are displayed for
2819 // JavaScript-disabled browsers) since the tooltip is sufficient
2821 if ($div == undefined || ! $div instanceof jQuery || $div.length == 0) {
2825 $footnotes = $div.find(".footnotes");
2828 $footnotes.find('span').each(function() {
2829 $(this).children("sup").remove();
2831 // The border and padding must be removed otherwise a thin yellow box remains visible
2832 $footnotes.css("border", "none");
2833 $footnotes.css("padding", "0px");
2835 // Replace the superscripts with the help icon
2836 $div.find("sup.footnotemarker").hide();
2837 $div.find("img.footnotemarker").show();
2839 $div.find("img.footnotemarker").each(function() {
2840 var img_class = $(this).attr("class");
2841 /** img contains two classes, as example "footnotemarker footnote_1".
2842 * We split it by second class and take it for the id of span
2844 img_class = img_class.split(" ");
2845 for (i = 0; i < img_class.length; i++) {
2846 if (img_class[i].split("_")[0] == "footnote") {
2847 var span_id = img_class[i].split("_")[1];
2851 * Now we get the #id of the span with span_id variable. As an example if we
2852 * initially get the img class as "footnotemarker footnote_2", now we get
2853 * #2 as the span_id. Using that we can find footnote_2 in footnotes.
2855 var tooltip_text = $footnotes.find("span[id='footnote_" + span_id + "']").html();
2857 content: tooltip_text,
2859 hide: { delay: 1000 },
2860 style: { background: '#ffffcc' }
2866 * This function handles the resizing of the content frame
2867 * and adjusts the top menu according to the new size of the frame
2869 function menuResize()
2871 var $cnt = $('#topmenu');
2872 var wmax = $cnt.innerWidth() - 5; // 5 px margin for jumping menu in Chrome
2873 var $submenu = $cnt.find('.submenu');
2874 var submenu_w = $submenu.outerWidth(true);
2875 var $submenu_ul = $submenu.find('ul');
2876 var $li = $cnt.find('> li');
2877 var $li2 = $submenu_ul.find('li');
2878 var more_shown = $li2.length > 0;
2880 // Calculate the total width used by all the shown tabs
2881 var total_len = more_shown ? submenu_w : 0;
2882 for (var i = 0; i < $li.length-1; i++) {
2883 total_len += $($li[i]).outerWidth(true);
2886 // Now hide menu elements that don't fit into the menubar
2887 var i = $li.length-1;
2888 var hidden = false; // Whether we have hidden any tabs
2889 while (total_len >= wmax && --i >= 0) { // Process the tabs backwards
2892 var el_width = el.outerWidth(true);
2893 el.data('width', el_width);
2895 total_len -= el_width;
2896 el.prependTo($submenu_ul);
2897 total_len += submenu_w;
2900 total_len -= el_width;
2901 el.prependTo($submenu_ul);
2905 // If we didn't hide any tabs, then there might be some space to show some
2907 // Show menu elements that do fit into the menubar
2908 for (var i = 0; i < $li2.length; i++) {
2909 total_len += $($li2[i]).data('width');
2910 // item fits or (it is the last item
2911 // and it would fit if More got removed)
2912 if (total_len < wmax
2913 || (i == $li2.length - 1 && total_len - submenu_w < wmax)
2915 $($li2[i]).insertBefore($submenu);
2922 // Show/hide the "More" tab as needed
2923 if ($submenu_ul.find('li').length > 0) {
2924 $submenu.addClass('shown');
2926 $submenu.removeClass('shown');
2929 if ($cnt.find('> li').length == 1) {
2930 // If there is only the "More" tab left, then we need
2931 // to align the submenu to the left edge of the tab
2932 $submenu_ul.removeClass().addClass('only');
2934 // Otherwise we align the submenu to the right edge of the tab
2935 $submenu_ul.removeClass().addClass('notonly');
2938 if ($submenu.find('.tabactive').length) {
2939 $submenu.addClass('active').find('> a').removeClass('tab').addClass('tabactive');
2941 $submenu.removeClass('active').find('> a').addClass('tab').removeClass('tabactive');
2946 var topmenu = $('#topmenu');
2947 if (topmenu.length == 0) {
2950 // create submenu container
2951 var link = $('<a />', {href: '#', 'class': 'tab'})
2952 .text(PMA_messages['strMore'])
2953 .click(function(e) {
2956 var img = topmenu.find('li:first-child img');
2958 $(PMA_getImage('b_more.png').toString()).prependTo(link);
2960 var submenu = $('<li />', {'class': 'submenu'})
2962 .append($('<ul />'))
2963 .mouseenter(function() {
2964 if ($(this).find('ul .tabactive').length == 0) {
2965 $(this).addClass('submenuhover').find('> a').addClass('tabactive');
2968 .mouseleave(function() {
2969 if ($(this).find('ul .tabactive').length == 0) {
2970 $(this).removeClass('submenuhover').find('> a').removeClass('tabactive');
2973 topmenu.append(submenu);
2975 // populate submenu and register resize event
2977 $(window).resize(menuResize);
2981 * Get the row number from the classlist (for example, row_1)
2983 function PMA_getRowNumber(classlist)
2985 return parseInt(classlist.split(/\s+row_/)[1]);
2989 * Changes status of slider
2991 function PMA_set_status_label($element)
2993 var text = $element.css('display') == 'none'
2996 $element.closest('.slide-wrapper').prev().find('span').text(text);
3000 * Initializes slider effect.
3002 function PMA_init_slider()
3004 $('.pma_auto_slider').each(function() {
3005 var $this = $(this);
3007 if ($this.hasClass('slider_init_done')) {
3010 $this.addClass('slider_init_done');
3012 var $wrapper = $('<div>', {'class': 'slide-wrapper'});
3013 $wrapper.toggle($this.is(':visible'));
3014 $('<a>', {href: '#'+this.id})
3016 .prepend($('<span>'))
3017 .insertBefore($this)
3019 var $wrapper = $this.closest('.slide-wrapper');
3020 var visible = $this.is(':visible');
3024 $this[visible ? 'hide' : 'show']('blind', function() {
3025 $wrapper.toggle(!visible);
3026 PMA_set_status_label($this);
3030 $this.wrap($wrapper);
3031 PMA_set_status_label($this);
3036 * var toggleButton This is a function that creates a toggle
3037 * sliding button given a jQuery reference
3038 * to the correct DOM element
3040 var toggleButton = function ($obj) {
3041 // In rtl mode the toggle switch is flipped horizontally
3042 // so we need to take that into account
3043 if ($('.text_direction', $obj).text() == 'ltr') {
3044 var right = 'right';
3049 * var h Height of the button, used to scale the
3050 * background image and position the layers
3052 var h = $obj.height();
3053 $('img', $obj).height(h);
3054 $('table', $obj).css('bottom', h-1);
3056 * var on Width of the "ON" part of the toggle switch
3057 * var off Width of the "OFF" part of the toggle switch
3059 var on = $('.toggleOn', $obj).width();
3060 var off = $('.toggleOff', $obj).width();
3061 // Make the "ON" and "OFF" parts of the switch the same size
3062 // + 2 pixels to avoid overflowed
3063 $('.toggleOn > div', $obj).width(Math.max(on, off) + 2);
3064 $('.toggleOff > div', $obj).width(Math.max(on, off) + 2);
3066 * var w Width of the central part of the switch
3068 var w = parseInt(($('img', $obj).height() / 16) * 22, 10);
3069 // Resize the central part of the switch on the top
3070 // layer to match the background
3071 $('table td:nth-child(2) > div', $obj).width(w);
3073 * var imgw Width of the background image
3074 * var tblw Width of the foreground layer
3075 * var offset By how many pixels to move the background
3076 * image, so that it matches the top layer
3078 var imgw = $('img', $obj).width();
3079 var tblw = $('table', $obj).width();
3080 var offset = parseInt(((imgw - tblw) / 2), 10);
3081 // Move the background to match the layout of the top layer
3082 $obj.find('img').css(right, offset);
3084 * var offw Outer width of the "ON" part of the toggle switch
3085 * var btnw Outer width of the central part of the switch
3087 var offw = $('.toggleOff', $obj).outerWidth();
3088 var btnw = $('table td:nth-child(2)', $obj).outerWidth();
3089 // Resize the main div so that exactly one side of
3090 // the switch plus the central part fit into it.
3091 $obj.width(offw + btnw + 2);
3093 * var move How many pixels to move the
3094 * switch by when toggling
3096 var move = $('.toggleOff', $obj).outerWidth();
3097 // If the switch is initialized to the
3098 // OFF state we need to move it now.
3099 if ($('.container', $obj).hasClass('off')) {
3100 if (right == 'right') {
3101 $('table, img', $obj).animate({'left': '-=' + move + 'px'}, 0);
3103 $('table, img', $obj).animate({'left': '+=' + move + 'px'}, 0);
3106 // Attach an 'onclick' event to the switch
3107 $('.container', $obj).click(function () {
3108 if ($(this).hasClass('isActive')) {
3111 $(this).addClass('isActive');
3113 var $msg = PMA_ajaxShowMessage();
3114 var $container = $(this);
3115 var callback = $('.callback', this).text();
3116 // Perform the actual toggle
3117 if ($(this).hasClass('on')) {
3118 if (right == 'right') {
3119 var operator = '-=';
3121 var operator = '+=';
3123 var url = $(this).find('.toggleOff > span').text();
3124 var removeClass = 'on';
3125 var addClass = 'off';
3127 if (right == 'right') {
3128 var operator = '+=';
3130 var operator = '-=';
3132 var url = $(this).find('.toggleOn > span').text();
3133 var removeClass = 'off';
3134 var addClass = 'on';
3136 $.post(url, {'ajax_request': true}, function(data) {
3137 if(data.success == true) {
3138 PMA_ajaxRemoveMessage($msg);
3140 .removeClass(removeClass)
3142 .animate({'left': operator + move + 'px'}, function () {
3143 $container.removeClass('isActive');
3147 PMA_ajaxShowMessage(data.error, false);
3148 $container.removeClass('isActive');
3155 * Initialise all toggle buttons
3157 $(window).load(function () {
3158 $('.toggleAjax').each(function () {
3161 .find('.toggleButton')
3162 toggleButton($(this));
3169 $(document).ready(function() {
3170 $('.vpointer').live('hover',
3173 var $this_td = $(this);
3174 var row_num = PMA_getRowNumber($this_td.attr('class'));
3175 // for all td of the same vertical row, toggle hover
3176 $('.vpointer').filter('.row_' + row_num).toggleClass('hover');
3179 }) // end of $(document).ready() for vertical pointer
3181 $(document).ready(function() {
3185 $('.vmarker').live('click', function(e) {
3186 // do not trigger when clicked on anchor
3187 if ($(e.target).is('a, img, a *')) {
3191 var $this_td = $(this);
3192 var row_num = PMA_getRowNumber($this_td.attr('class'));
3194 // XXX: FF fires two click events for <label> (label and checkbox), so we need to handle this differently
3196 var $checkbox = $('.vmarker').filter('.row_' + row_num + ':first').find(':checkbox');
3197 if ($checkbox.length) {
3198 // checkbox in a row, add or remove class depending on checkbox state
3199 var checked = $checkbox.attr('checked');
3200 if (!$(e.target).is(':checkbox, label')) {
3202 $checkbox.attr('checked', checked);
3204 // for all td of the same vertical row, toggle the marked class
3206 $('.vmarker').filter('.row_' + row_num).addClass('marked');
3208 $('.vmarker').filter('.row_' + row_num).removeClass('marked');
3211 // normaln data table, just toggle class
3212 $('.vmarker').filter('.row_' + row_num).toggleClass('marked');
3217 * Reveal visual builder anchor
3220 $('#visual_builder_anchor').show();
3223 * Page selector in db Structure (non-AJAX)
3225 $('#tableslistcontainer').find('#pageselector').live('change', function() {
3226 $(this).parent("form").submit();
3230 * Page selector in navi panel (non-AJAX)
3232 $('#navidbpageselector').find('#pageselector').live('change', function() {
3233 $(this).parent("form").submit();
3237 * Page selector in browse_foreigners windows (non-AJAX)
3239 $('#body_browse_foreigners').find('#pageselector').live('change', function() {
3240 $(this).closest("form").submit();
3244 * Load version information asynchronously.
3246 if ($('.jsversioncheck').length > 0) {
3247 $.getScript('http://www.phpmyadmin.net/home_page/version.js', PMA_current_version);
3256 * Enables the text generated by PMA_linkOrButton() to be clickable
3258 $('a[class~="formLinkSubmit"]').live('click',function(e) {
3260 if($(this).attr('href').indexOf('=') != -1) {
3261 var data = $(this).attr('href').substr($(this).attr('href').indexOf('#')+1).split('=',2);
3262 $(this).parents('form').append('<input type="hidden" name="' + data[0] + '" value="' + data[1] + '"/>');
3264 $(this).parents('form').submit();
3268 $('#update_recent_tables').ready(function() {
3269 if (window.parent.frame_navigation != undefined
3270 && window.parent.frame_navigation.PMA_reloadRecentTable != undefined)
3272 window.parent.frame_navigation.PMA_reloadRecentTable();
3276 }) // end of $(document).ready()
3279 * Creates a message inside an object with a sliding effect
3281 * @param msg A string containing the text to display
3282 * @param $obj a jQuery object containing the reference
3283 * to the element where to put the message
3284 * This is optional, if no element is
3285 * provided, one will be created below the
3286 * navigation links at the top of the page
3288 * @return bool True on success, false on failure
3290 function PMA_slidingMessage(msg, $obj)
3292 if (msg == undefined || msg.length == 0) {
3293 // Don't show an empty message
3296 if ($obj == undefined || ! $obj instanceof jQuery || $obj.length == 0) {
3297 // If the second argument was not supplied,
3298 // we might have to create a new DOM node.
3299 if ($('#PMA_slidingMessage').length == 0) {
3300 $('#floating_menubar')
3301 .after('<span id="PMA_slidingMessage" '
3302 + 'style="display: inline-block;"></span>');
3304 $obj = $('#PMA_slidingMessage');
3306 if ($obj.has('div').length > 0) {
3307 // If there already is a message inside the
3308 // target object, we must get rid of it
3312 .fadeOut(function () {
3317 .append('<div style="display: none;">' + msg + '</div>')
3319 height: $obj.find('div').first().height()
3326 // Object does not already have a message
3327 // inside it, so we simply slide it down
3330 .html('<div style="display: none;">' + msg + '</div>')
3342 // Set the height of the parent
3343 // to the height of the child
3354 } // end PMA_slidingMessage()
3357 * Attach Ajax event handlers for Drop Table.
3359 * @uses $.PMA_confirm()
3360 * @uses PMA_ajaxShowMessage()
3361 * @uses window.parent.refreshNavigation()
3362 * @uses window.parent.refreshMain()
3363 * @see $cfg['AjaxEnable']
3365 $(document).ready(function() {
3366 $("#drop_tbl_anchor").live('click', function(event) {
3367 event.preventDefault();
3369 //context is top.frame_content, so we need to use window.parent.table to access the table var
3371 * @var question String containing the question to be asked for confirmation
3373 var question = PMA_messages['strDropTableStrongWarning'] + '\n' + PMA_messages['strDoYouReally'] + ' :\n' + 'DROP TABLE ' + window.parent.table;
3375 $(this).PMA_confirm(question, $(this).attr('href') ,function(url) {
3377 PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
3378 $.get(url, {'is_js_confirmed': '1', 'ajax_request': true}, function(data) {
3379 //Database deleted successfully, refresh both the frames
3380 window.parent.refreshNavigation();
3381 window.parent.refreshMain();
3383 }); // end $.PMA_confirm()
3384 }); //end of Drop Table Ajax action
3385 }) // end of $(document).ready() for Drop Table
3388 * Attach Ajax event handlers for Truncate Table.
3390 * @uses $.PMA_confirm()
3391 * @uses PMA_ajaxShowMessage()
3392 * @uses window.parent.refreshNavigation()
3393 * @uses window.parent.refreshMain()
3394 * @see $cfg['AjaxEnable']
3396 $(document).ready(function() {
3397 $("#truncate_tbl_anchor.ajax").live('click', function(event) {
3398 event.preventDefault();
3400 //context is top.frame_content, so we need to use window.parent.table to access the table var
3402 * @var question String containing the question to be asked for confirmation
3404 var question = PMA_messages['strTruncateTableStrongWarning'] + '\n' + PMA_messages['strDoYouReally'] + ' :\n' + 'TRUNCATE TABLE ' + window.parent.table;
3406 $(this).PMA_confirm(question, $(this).attr('href') ,function(url) {
3408 PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
3409 $.get(url, {'is_js_confirmed': '1', 'ajax_request': true}, function(data) {
3410 if ($("#sqlqueryresults").length != 0) {
3411 $("#sqlqueryresults").remove();
3413 if ($("#result_query").length != 0) {
3414 $("#result_query").remove();
3416 if (data.success == true) {
3417 PMA_ajaxShowMessage(data.message);
3418 $("<div id='sqlqueryresults'></div>").insertAfter("#floating_menubar");
3419 $("#sqlqueryresults").html(data.sql_query);
3421 var $temp_div = $("<div id='temp_div'></div>")
3422 $temp_div.html(data.error);
3423 var $error = $temp_div.find("code").addClass("error");
3424 PMA_ajaxShowMessage($error, false);
3427 }); // end $.PMA_confirm()
3428 }); //end of Truncate Table Ajax action
3429 }) // end of $(document).ready() for Truncate Table
3432 * Attach CodeMirror2 editor to SQL edit area.
3434 $(document).ready(function() {
3435 var elm = $('#sqlquery');
3436 if (elm.length > 0 && typeof CodeMirror != 'undefined') {
3437 codemirror_editor = CodeMirror.fromTextArea(elm[0], {
3439 matchBrackets: true,
3441 mode: "text/x-mysql",
3448 * jQuery plugin to cancel selection in HTML code.
3451 $.fn.noSelect = function (p) { //no select plugin by Paulo P.Marinas
3452 var prevent = (p == null) ? true : p;
3454 return this.each(function () {
3455 if ($.browser.msie || $.browser.safari) $(this).bind('selectstart', function () {
3458 else if ($.browser.mozilla) {
3459 $(this).css('MozUserSelect', 'none');
3460 $('body').trigger('focus');
3461 } else if ($.browser.opera) $(this).bind('mousedown', function () {
3464 else $(this).attr('unselectable', 'on');
3467 return this.each(function () {
3468 if ($.browser.msie || $.browser.safari) $(this).unbind('selectstart');
3469 else if ($.browser.mozilla) $(this).css('MozUserSelect', 'inherit');
3470 else if ($.browser.opera) $(this).unbind('mousedown');
3471 else $(this).removeAttr('unselectable', 'on');
3478 * jQuery plugin to correctly filter input fields by value, needed
3479 * because some nasty values may break selector syntax
3482 $.fn.filterByValue = function (value) {
3483 return this.filter(function () {
3484 return $(this).val() === value
3490 * Create default PMA tooltip for the element specified. The default appearance
3491 * can be overriden by specifying optional "options" parameter (see qTip options).
3493 function PMA_createqTip($elements, content, options)
3495 if ($('#no_hint').length > 0) {
3503 tooltip: 'normalqTip',
3504 content: 'normalqTipContent'
3510 corner: { target: 'rightMiddle', tooltip: 'leftMiddle' },
3511 adjust: { x: 10, y: 20 }
3528 $elements.qtip($.extend(true, o, options));
3532 * Return value of a cell in a table.
3534 function PMA_getCellValue(td) {
3535 if ($(td).is('.null')) {
3537 } else if (! $(td).is('.to_be_saved') && $(td).data('original_data')) {
3538 return $(td).data('original_data');
3540 return $(td).text();
3544 /* Loads a js file, an array may be passed as well */
3545 loadJavascript=function(file) {
3546 if($.isArray(file)) {
3547 for(var i=0; i<file.length; i++) {
3548 $('head').append('<script type="text/javascript" src="'+file[i]+'"></script>');
3551 $('head').append('<script type="text/javascript" src="'+file+'"></script>');
3555 $(document).ready(function() {
3559 $('a.themeselect').live('click', function(e) {
3563 'left=10,top=20,width=510,height=350,scrollbars=yes,status=yes,resizable=yes'
3569 * Automatic form submission on change.
3571 $('.autosubmit').change(function(e) {
3572 e.target.form.submit();
3578 $('.take_theme').click(function(e) {
3579 var what = this.name;
3580 if (window.opener && window.opener.document.forms['setTheme'].elements['set_theme']) {
3581 window.opener.document.forms['setTheme'].elements['set_theme'].value = what;
3582 window.opener.document.forms['setTheme'].submit();
3591 * Clear text selection
3593 function PMA_clearSelection() {
3594 if(document.selection && document.selection.empty) {
3595 document.selection.empty();
3596 } else if(window.getSelection) {
3597 var sel = window.getSelection();
3598 if(sel.empty) sel.empty();
3599 if(sel.removeAllRanges) sel.removeAllRanges();
3606 function escapeHtml(unsafe) {
3608 .replace(/&/g, "&")
3609 .replace(/</g, "<")
3610 .replace(/>/g, ">")
3611 .replace(/"/g, """)
3612 .replace(/'/g, "'");
3618 function printPage()
3620 // Do print the page
3621 if (typeof(window.print) != 'undefined') {
3626 $(document).ready(function() {
3627 $('input#print').click(printPage);
3631 * Makes the breadcrumbs and the menu bar float at the top of the viewport
3633 $(document).ready(function () {
3634 if ($("#floating_menubar").length && $('#PMA_disable_floating_menubar').length == 0) {
3635 $("#floating_menubar")
3637 'position': 'fixed',
3643 .append($('#serverinfo'))
3644 .append($('#topmenucontainer'));
3647 $('#floating_menubar').outerHeight(true)
3653 * Toggles row colors of a set of 'tr' elements starting from a given element
3655 * @param $start Starting element
3657 function toggleRowColors($start)
3659 for (var $curr_row = $start; $curr_row.length > 0; $curr_row = $curr_row.next()) {
3660 if ($curr_row.hasClass('odd')) {
3661 $curr_row.removeClass('odd').addClass('even');
3662 } else if ($curr_row.hasClass('even')) {
3663 $curr_row.removeClass('even').addClass('odd');