added japanese language
[openemr.git] / phpmyadmin / js / tbl_structure.js
blobf754832c8ad2aedc9e07809028a10671d4e30a3e
1 /* vim: set expandtab sw=4 ts=4 sts=4: */
2 /**
3  * @fileoverview    functions used on the table structure page
4  * @name            Table Structure
5  *
6  * @requires    jQuery
7  * @requires    jQueryUI
8  * @required    js/functions.js
9  */
11 /**
12  * AJAX scripts for tbl_structure.php
13  *
14  * Actions ajaxified here:
15  * Drop Column
16  * Add Primary Key
17  * Drop Primary Key/Index
18  *
19  */
21 /**
22  * This function returns the horizontal space available for the menu in pixels.
23  * To calculate this value we start we the width of the main panel, then we
24  * substract the margin of the page content, then we substract any cellspacing
25  * that the table may have (original theme only) and finally we substract the
26  * width of all columns of the table except for the last one (which is where
27  * the menu will go). What we should end up with is the distance between the
28  * start of the last column on the table and the edge of the page, again this
29  * is the space available for the menu.
30  *
31  * In the case where the table cell where the menu will be displayed is already
32  * off-screen (the table is wider than the page), a negative value will be returned,
33  * but this will be treated as a zero by the menuResizer plugin.
34  *
35  * @return int
36  */
37 function PMA_tbl_structure_menu_resizer_callback() {
38     var pagewidth = $('body').width();
39     var $page = $('#page_content');
40     pagewidth -= $page.outerWidth(true) - $page.outerWidth();
41     var columnsWidth = 0;
42     var $columns = $('#tablestructure').find('tr:eq(1)').find('td,th');
43     $columns.not(':last').each(function () {
44         columnsWidth += $(this).outerWidth(true);
45     });
46     var totalCellSpacing = $('#tablestructure').width();
47     $columns.each(function () {
48         totalCellSpacing -= $(this).outerWidth(true);
49     });
50     return pagewidth - columnsWidth - totalCellSpacing - 15; // 15px extra margin
53 /**
54  * Reload fields table
55  */
56 function reloadFieldForm() {
57     $.post($("#fieldsForm").attr('action'), $("#fieldsForm").serialize() + "&ajax_request=true", function (form_data) {
58         var $temp_div = $("<div id='temp_div'><div>").append(form_data.message);
59         $("#fieldsForm").replaceWith($temp_div.find("#fieldsForm"));
60         $("#addColumns").replaceWith($temp_div.find("#addColumns"));
61         $('#move_columns_dialog ul').replaceWith($temp_div.find("#move_columns_dialog ul"));
62         $("#moveColumns").removeClass("move-active");
63         /* reinitialise the more options in table */
64         $('#fieldsForm ul.table-structure-actions').menuResizer(PMA_tbl_structure_menu_resizer_callback);
65     });
66     $('#page_content').show();
69 /**
70  * Unbind all event handlers before tearing down a page
71  */
72 AJAX.registerTeardown('tbl_structure.js', function () {
73     $("a.change_column_anchor.ajax").die('click');
74     $("button.change_columns_anchor.ajax, input.change_columns_anchor.ajax").die('click');
75     $("a.drop_column_anchor.ajax").die('click');
76     $("a.add_primary_key_anchor.ajax").die('click');
77     $("a.add_index_anchor.ajax").die('click');
78     $("a.add_unique_anchor.ajax").die('click');
79     $("#move_columns_anchor").die('click');
80     $(".append_fields_form.ajax").unbind('submit');
81 });
83 AJAX.registerOnload('tbl_structure.js', function () {
85     /**
86      *Ajax action for submitting the "Column Change" and "Add Column" form
87      */
88     $(".append_fields_form.ajax").die().live('submit', function (event) {
89         event.preventDefault();
90         /**
91          * @var    the_form    object referring to the export form
92          */
93         var $form = $(this);
95         /*
96          * First validate the form; if there is a problem, avoid submitting it
97          *
98          * checkTableEditForm() needs a pure element and not a jQuery object,
99          * this is why we pass $form[0] as a parameter (the jQuery object
100          * is actually an array of DOM elements)
101          */
102         if (checkTableEditForm($form[0], $form.find('input[name=orig_num_fields]').val())) {
103             // OK, form passed validation step
104             PMA_prepareForAjaxRequest($form);
105             //User wants to submit the form
106             $msg = PMA_ajaxShowMessage();
107             $.post($form.attr('action'), $form.serialize() + '&do_save_data=1', function (data) {
108                 if ($("#sqlqueryresults").length !== 0) {
109                     $("#sqlqueryresults").remove();
110                 } else if ($(".error:not(.tab)").length !== 0) {
111                     $(".error:not(.tab)").remove();
112                 }
113                 if (data.success === true) {
114                     $("#page_content")
115                         .empty()
116                         .append(data.message)
117                         .append(data.sql_query)
118                         .show();
119                     PMA_highlightSQL($('#page_content'));
120                     $("#result_query .notice").remove();
121                     reloadFieldForm();
122                     $form.remove();
123                     PMA_ajaxRemoveMessage($msg);
124                     PMA_init_slider();
125                     PMA_reloadNavigation();
126                 } else {
127                     PMA_ajaxShowMessage(data.error, false);
128                 }
129             }); // end $.post()
130         }
131     }); // end change table button "do_save_data"
133     /**
134      * Attach Event Handler for 'Change Column'
135      */
136     $("a.change_column_anchor.ajax").live('click', function (event) {
137         event.preventDefault();
138         var $msg = PMA_ajaxShowMessage();
139         $('#page_content').hide();
140         $.get($(this).attr('href'), {'ajax_request': true}, function (data) {
141             PMA_ajaxRemoveMessage($msg);
142             if (data.success) {
143                 $('<div id="change_column_dialog" class="margin"></div>')
144                     .html(data.message)
145                     .insertBefore('#page_content');
146                 PMA_highlightSQL($('#page_content'));
147                 PMA_showHints();
148                 PMA_verifyColumnsProperties();
149             } else {
150                 PMA_ajaxShowMessage(PMA_messages.strErrorProcessingRequest + " : " + data.error, false);
151             }
152         });
153     });
155     /**
156      * Attach Event Handler for 'Change multiple columns'
157      */
158     $("button.change_columns_anchor.ajax, input.change_columns_anchor.ajax").live('click', function (event) {
159         event.preventDefault();
160         var $msg = PMA_ajaxShowMessage();
161         $('#page_content').hide();
162         var $form = $(this).closest('form');
163         var params = $form.serialize() + "&ajax_request=true&submit_mult=change";
164         $.post($form.prop("action"), params, function (data) {
165             PMA_ajaxRemoveMessage($msg);
166             if (data.success) {
167                 $('#page_content')
168                     .empty()
169                     .append(
170                         $('<div id="change_column_dialog"></div>')
171                             .html(data.message)
172                     )
173                     .show();
174                 PMA_highlightSQL($('#page_content'));
175                 PMA_showHints();
176                 PMA_verifyColumnsProperties();
177             } else {
178                 $('#page_content').show();
179                 PMA_ajaxShowMessage(data.error);
180             }
181         });
182     });
184     /**
185      * Attach Event Handler for 'Drop Column'
186      */
187     $("a.drop_column_anchor.ajax").live('click', function (event) {
188         event.preventDefault();
189         /**
190          * @var curr_table_name String containing the name of the current table
191          */
192         var curr_table_name = $(this).closest('form').find('input[name=table]').val();
193         /**
194          * @var curr_row    Object reference to the currently selected row (i.e. field in the table)
195          */
196         var $curr_row = $(this).parents('tr');
197         /**
198          * @var curr_column_name    String containing name of the field referred to by {@link curr_row}
199          */
200         var curr_column_name = $curr_row.children('th').children('label').text();
201         /**
202          * @var $after_field_item    Corresponding entry in the 'After' field.
203          */
204         var $after_field_item = $("select[name='after_field'] option[value='" + curr_column_name + "']");
205         /**
206          * @var question    String containing the question to be asked for confirmation
207          */
208         var question = $.sprintf(PMA_messages.strDoYouReally, 'ALTER TABLE `' + escapeHtml(curr_table_name) + '` DROP `' + escapeHtml(curr_column_name) + '`;');
209         $(this).PMA_confirm(question, $(this).attr('href'), function (url) {
210             var $msg = PMA_ajaxShowMessage(PMA_messages.strDroppingColumn, false);
211             $.get(url, {'is_js_confirmed' : 1, 'ajax_request' : true, 'ajax_page_request' : true}, function (data) {
212                 if (data.success === true) {
213                     PMA_ajaxRemoveMessage($msg);
214                     if ($('#result_query').length) {
215                         $('#result_query').remove();
216                     }
217                     if (data.sql_query) {
218                         $('<div id="result_query"></div>')
219                             .html(data.sql_query)
220                             .prependTo('#page_content');
221                         PMA_highlightSQL($('#page_content'));
222                     }
223                     toggleRowColors($curr_row.next());
224                     // Adjust the row numbers
225                     for (var $row = $curr_row.next(); $row.length > 0; $row = $row.next()) {
226                         var new_val = parseInt($row.find('td:nth-child(2)').text(), 10) - 1;
227                         $row.find('td:nth-child(2)').text(new_val);
228                     }
229                     $after_field_item.remove();
230                     $curr_row.hide("medium").remove();
231                     //refresh table stats
232                     if (data.tableStat) {
233                         $('#tablestatistics').html(data.tableStat);
234                     }
235                     // refresh the list of indexes (comes from sql.php)
236                     $('.index_info').replaceWith(data.indexes_list);
237                     PMA_reloadNavigation();
238                 } else {
239                     PMA_ajaxShowMessage(PMA_messages.strErrorProcessingRequest + " : " + data.error, false);
240                 }
241             }); // end $.get()
242         }); // end $.PMA_confirm()
243     }); //end of Drop Column Anchor action
245     /**
246      * Ajax Event handler for 'Add Primary Key'
247      */
248     $("a.add_primary_key_anchor.ajax").live('click', function (event) {
249         event.preventDefault();
250         /**
251          * @var curr_table_name String containing the name of the current table
252          */
253         var curr_table_name = $(this).closest('form').find('input[name=table]').val();
254         /**
255          * @var curr_column_name    String containing name of the field referred to by {@link curr_row}
256          */
257         var curr_column_name = $(this).parents('tr').children('th').children('label').text();
258         /**
259          * @var question    String containing the question to be asked for confirmation
260          */
261         var question = $.sprintf(PMA_messages.strDoYouReally, 'ALTER TABLE `' + escapeHtml(curr_table_name) + '` ADD PRIMARY KEY(`' + escapeHtml(curr_column_name) + '`);');
262         $(this).PMA_confirm(question, $(this).attr('href'), function (url) {
263             var $msg = PMA_ajaxShowMessage(PMA_messages.strAddingPrimaryKey, false);
264             $.get(url
265                 , {'is_js_confirmed' : 1, 'ajax_request' : true, 'index_change' : true}
266                 , function (data) {
267                 if (data.success === true) {
268                     PMA_ajaxRemoveMessage($msg);
269                     $(this).remove();
270                     if (typeof data.reload != 'undefined') {
271                         PMA_commonActions.refreshMain(false, function () {
272                             if ($('#result_query').length) {
273                                 $('#result_query').remove();
274                             }
275                             if (data.sql_query) {
276                                 $('<div id="result_query"></div>')
277                                     .html(data.sql_query)
278                                     .prependTo('#page_content');
279                                 PMA_highlightSQL($('#page_content'));
280                             }
281                         });
282                         PMA_reloadNavigation();
283                     }
284                     if (data.indexes_list) {
285                         $('.index_info').replaceWith(data.indexes_list);
286                     }
287                 } else {
288                     PMA_ajaxShowMessage(PMA_messages.strErrorProcessingRequest + " : " + data.error, false);
289                 }
290             }); // end $.get()
291         }); // end $.PMA_confirm()
292     }); //end Add Primary Key
294     /**
295      * Ajax Event handler for 'Add Index'
296      */
297     $("a.add_index_anchor.ajax").live('click', function (event) {
298         event.preventDefault();
299         /**
300          * @var curr_table_name String containing the name of the current table
301          */
302         var curr_table_name = $(this).closest('form').find('input[name=table]').val();
303         /**
304          * @var curr_column_name    String containing name of the field referred to by {@link curr_row}
305          */
306         var curr_column_name = $(this).parents('tr').children('th').children('label').text();
307         /**
308          * @var question    String containing the question to be asked for confirmation
309          */
310         var question = $.sprintf(PMA_messages.strDoYouReally, 'ALTER TABLE `' + escapeHtml(curr_table_name) + '` ADD INDEX(`' + escapeHtml(curr_column_name) + '`);');
311         $(this).PMA_confirm(question, $(this).attr('href'), function (url) {
312             var $msg = PMA_ajaxShowMessage(PMA_messages.strAddingIndex, false);
313             $.get(url
314                 , {'is_js_confirmed' : 1, 'ajax_request' : true, 'index_change' : true}
315                 , function (data) {
316                 if (data.success === true) {
317                     PMA_ajaxRemoveMessage($msg);
318                     if ($('#result_query').length) {
319                         $('#result_query').remove();
320                     }
321                     if (data.sql_query) {
322                         $('<div id="result_query"></div>')
323                             .html(data.sql_query)
324                             .prependTo('#page_content');
325                         PMA_highlightSQL($('#page_content'));
326                     }
327                     if (data.indexes_list) {
328                         $('.index_info').replaceWith(data.indexes_list);
329                     }
330                     PMA_reloadNavigation();
331                 } else {
332                     PMA_ajaxShowMessage(PMA_messages.strErrorProcessingRequest + " : " + data.error, false);
333                 }
334             }); // end $.get()
335         }); // end $.PMA_confirm()
336     }); //end Add Index
338     /**
339      * Ajax Event handler for 'Add Unique'
340      */
341     $("a.add_unique_anchor.ajax").live('click', function (event) {
342         event.preventDefault();
343         /**
344          * @var curr_table_name String containing the name of the current table
345          */
346         var curr_table_name = $(this).closest('form').find('input[name=table]').val();
347         /**
348          * @var curr_column_name    String containing name of the field referred to by {@link curr_row}
349          */
350         var curr_column_name = $(this).parents('tr').children('th').children('label').text();
351         /**
352          * @var question    String containing the question to be asked for confirmation
353          */
354         var question = $.sprintf(PMA_messages.strDoYouReally, 'ALTER TABLE `' + escapeHtml(curr_table_name) + '` ADD UNIQUE(`' + escapeHtml(curr_column_name) + '`);');
355         $(this).PMA_confirm(question, $(this).attr('href'), function (url) {
356             var $msg = PMA_ajaxShowMessage(PMA_messages.strAddingUnique, false);
357             $.get(url
358                 , {'is_js_confirmed' : 1, 'ajax_request' : true, 'index_change' : true}
359                 , function (data) {
360                 if (data.success === true) {
361                     PMA_ajaxRemoveMessage($msg);
362                     if ($('#result_query').length) {
363                         $('#result_query').remove();
364                     }
365                     if (data.sql_query) {
366                         $('<div id="result_query"></div>')
367                             .html(data.sql_query)
368                             .prependTo('#page_content');
369                         PMA_highlightSQL($('#page_content'));
370                     }
371                     if (data.indexes_list) {
372                         $('.index_info').replaceWith(data.indexes_list);
373                     }
374                     PMA_reloadNavigation();
375                 } else {
376                     PMA_ajaxShowMessage(PMA_messages.strErrorProcessingRequest + " : " + data.error, false);
377                 }
378             }); // end $.get()
379         }); // end $.PMA_confirm()
380     }); //end Add Unique
382     /**
383      * Inline move columns
384     **/
385     $("#move_columns_anchor").live('click', function (e) {
386         e.preventDefault();
388         if ($(this).hasClass("move-active")) {
389             return;
390         }
392         /**
393          * @var    button_options  Object that stores the options passed to jQueryUI
394          *                          dialog
395          */
396         var button_options = {};
398         button_options[PMA_messages.strGo] = function (event) {
399             event.preventDefault();
400             var $msgbox = PMA_ajaxShowMessage();
401             var $this = $(this);
402             var $form = $this.find("form");
403             var serialized = $form.serialize();
405             // check if any columns were moved at all
406             if (serialized == $form.data("serialized-unmoved")) {
407                 PMA_ajaxRemoveMessage($msgbox);
408                 $this.dialog('close');
409                 return;
410             }
412             $.post($form.prop("action"), serialized + "&ajax_request=true", function (data) {
413                 if (data.success === false) {
414                     PMA_ajaxRemoveMessage($msgbox);
415                     $this
416                     .clone()
417                     .html(data.error)
418                     .dialog({
419                         title: $(this).prop("title"),
420                         height: 230,
421                         width: 900,
422                         modal: true,
423                         buttons: button_options_error
424                     }); // end dialog options
425                 } else {
426                     $('#fieldsForm ul.table-structure-actions').menuResizer('destroy');
427                     // sort the fields table
428                     var $fields_table = $("table#tablestructure tbody");
429                     // remove all existing rows and remember them
430                     var $rows = $fields_table.find("tr").remove();
431                     // loop through the correct order
432                     for (var i in data.columns) {
433                         var the_column = data.columns[i];
434                         var $the_row = $rows
435                             .find("input:checkbox[value=" + the_column + "]")
436                             .closest("tr");
437                         // append the row for this column to the table
438                         $fields_table.append($the_row);
439                     }
440                     var $firstrow = $fields_table.find("tr").eq(0);
441                     // Adjust the row numbers and colors
442                     for (var $row = $firstrow; $row.length > 0; $row = $row.next()) {
443                         $row
444                         .find('td:nth-child(2)')
445                         .text($row.index() + 1)
446                         .end()
447                         .removeClass("odd even")
448                         .addClass($row.index() % 2 === 0 ? "odd" : "even");
449                     }
450                     PMA_ajaxShowMessage(data.message);
451                     $this.dialog('close');
452                     $('#fieldsForm ul.table-structure-actions').menuResizer(PMA_tbl_structure_menu_resizer_callback);
453                 }
454             });
455         };
456         button_options[PMA_messages.strCancel] = function () {
457             $(this).dialog('close');
458         };
460         var button_options_error = {};
461         button_options_error[PMA_messages.strOK] = function () {
462             $(this).dialog('close').remove();
463         };
465         var columns = [];
467         $("#tablestructure tbody tr").each(function () {
468             var col_name = $(this).find("input:checkbox").eq(0).val();
469             var hidden_input = $("<input/>")
470                 .prop({
471                     name: "move_columns[]",
472                     type: "hidden"
473                 })
474                 .val(col_name);
475             columns[columns.length] = $("<li/>")
476                 .addClass("placeholderDrag")
477                 .text(col_name)
478                 .append(hidden_input);
479         });
481         var col_list = $("#move_columns_dialog ul")
482             .find("li").remove().end();
483         for (var i in columns) {
484             col_list.append(columns[i]);
485         }
486         col_list.sortable({
487             axis: 'y',
488             containment: $("#move_columns_dialog div"),
489             tolerance: 'pointer'
490         }).disableSelection();
491         var $form = $("#move_columns_dialog form");
492         $form.data("serialized-unmoved", $form.serialize());
494         $("#move_columns_dialog").dialog({
495             modal: true,
496             buttons: button_options,
497             beforeClose: function () {
498                 $("#move_columns_anchor").removeClass("move-active");
499             }
500         });
501     });
504 /** Handler for "More" dropdown in structure table rows */
505 AJAX.registerOnload('tbl_structure.js', function () {
506     if ($('#fieldsForm').hasClass('HideStructureActions')) {
507         $('#fieldsForm ul.table-structure-actions').menuResizer(PMA_tbl_structure_menu_resizer_callback);
508     }
510 AJAX.registerTeardown('tbl_structure.js', function () {
511     $('#fieldsForm ul.table-structure-actions').menuResizer('destroy');
513 $(function () {
514     $(window).resize($.throttle(function () {
515         var $list = $('#fieldsForm ul.table-structure-actions');
516         if ($list.length) {
517             $list.menuResizer('resize');
518         }
519     }));