Merge remote-tracking branch 'origin/master'
[phpmyadmin.git] / js / tbl_zoom_plot_jqplot.js
bloba97dfa0113dd27e02ba13a7563af6b043960a493
1 // TODO: change the axis
2 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 /**
4  ** @fileoverview JavaScript functions used on tbl_select.php
5  **
6  ** @requires    jQuery
7  ** @requires    js/functions.js
8  **/
11 /**
12  **  Display Help/Info
13  **/
14 function displayHelp() {
15     PMA_ajaxShowMessage(PMA_messages.strDisplayHelp, 10000);
18 /**
19  ** Extend the array object for max function
20  ** @param array
21  **/
22 Array.max = function (array) {
23     return Math.max.apply(Math, array);
26 /**
27  ** Extend the array object for min function
28  ** @param array
29  **/
30 Array.min = function (array) {
31     return Math.min.apply(Math, array);
34 /**
35  ** Checks if a string contains only numeric value
36  ** @param n: String (to be checked)
37  **/
38 function isNumeric(n) {
39     return !isNaN(parseFloat(n)) && isFinite(n);
42 /**
43  ** Checks if an object is empty
44  ** @param n: Object (to be checked)
45  **/
46 function isEmpty(obj) {
47     var name;
48     for (name in obj) {
49         return false;
50     }
51     return true;
54 /**
55  ** Converts a date/time into timestamp
56  ** @param val  String Date
57  ** @param type Sring  Field type(datetime/timestamp/time/date)
58  **/
59 function getTimeStamp(val, type) {
60     if (type.toString().search(/datetime/i) != -1 ||
61         type.toString().search(/timestamp/i) != -1
62     ) {
63         return $.datepicker.parseDateTime('yy-mm-dd', 'HH:mm:ss', val);
64     }
65     else if (type.toString().search(/time/i) != -1) {
66         return $.datepicker.parseDateTime('yy-mm-dd', 'HH:mm:ss', '1970-01-01 ' + val);
67     }
68     else if (type.toString().search(/date/i) != -1) {
69         return $.datepicker.parseDate('yy-mm-dd', val);
70     }
73 /**
74  ** Classifies the field type into numeric,timeseries or text
75  ** @param field: field type (as in database structure)
76  **/
77 function getType(field) {
78     if (field.toString().search(/int/i) != -1 ||
79         field.toString().search(/decimal/i) != -1 ||
80         field.toString().search(/year/i) != -1
81     ) {
82         return 'numeric';
83     } else if (field.toString().search(/time/i) != -1 ||
84         field.toString().search(/date/i) != -1
85     ) {
86         return 'time';
87     } else {
88         return 'text';
89     }
91 /**
92  ** Converts a categorical array into numeric array
93  ** @param array categorical values array
94  **/
95 function getCord(arr) {
96     var newCord = [];
97     var original = $.extend(true, [], arr);
98     arr = jQuery.unique(arr).sort();
99     $.each(original, function (index, value) {
100         newCord.push(jQuery.inArray(value, arr));
101     });
102     return [newCord, arr, original];
106  ** Scrolls the view to the display section
107  **/
108 function scrollToChart() {
109     var x = $('#dataDisplay').offset().top - 100; // 100 provides buffer in viewport
110     $('html,body').animate({scrollTop: x}, 500);
114  * Unbind all event handlers before tearing down a page
115  */
116 AJAX.registerTeardown('tbl_zoom_plot_jqplot.js', function () {
117     $('#tableid_0').unbind('change');
118     $('#tableid_1').unbind('change');
119     $('#tableid_2').unbind('change');
120     $('#tableid_3').unbind('change');
121     $('#inputFormSubmitId').unbind('click');
122     $('#togglesearchformlink').unbind('click');
123     $(document).on('keydown', "#dataDisplay :input");
124     $('button.button-reset').unbind('click');
125     $('div#resizer').unbind('resizestop');
126     $('div#querychart').unbind('jqplotDataClick');
129 AJAX.registerOnload('tbl_zoom_plot_jqplot.js', function () {
130     var cursorMode = ($("input[name='mode']:checked").val() == 'edit') ? 'crosshair' : 'pointer';
131     var currentChart = null;
132     var searchedDataKey = null;
133     var xLabel = $('#tableid_0').val();
134     var yLabel = $('#tableid_1').val();
135     // will be updated via Ajax
136     var xType = $('#types_0').val();
137     var yType = $('#types_1').val();
138     var dataLabel = $('#dataLabel').val();
139     var lastX;
140     var lastY;
141     var zoomRatio = 1;
144     // Get query result
145     var searchedData;
146     try {
147         searchedData = jQuery.parseJSON($('#querydata').html());
148     } catch (err) {
149         searchedData = null;
150     }
152     /**
153      ** Input form submit on field change
154      **/
156     // first column choice corresponds to the X axis
157     $('#tableid_0').change(function () {
158         //AJAX request for field type, collation, operators, and value field
159         $.post('tbl_zoom_select.php', {
160             'ajax_request' : true,
161             'change_tbl_info' : true,
162             'server' : PMA_commonParams.get('server'),
163             'db' : PMA_commonParams.get('db'),
164             'table' : PMA_commonParams.get('table'),
165             'field' : $('#tableid_0').val(),
166             'it' : 0,
167             'token' : PMA_commonParams.get('token')
168         }, function (data) {
169             $('#tableFieldsId tr:eq(1) td:eq(0)').html(data.field_type);
170             $('#tableFieldsId tr:eq(1) td:eq(1)').html(data.field_collation);
171             $('#tableFieldsId tr:eq(1) td:eq(2)').html(data.field_operators);
172             $('#tableFieldsId tr:eq(1) td:eq(3)').html(data.field_value);
173             xLabel = $('#tableid_0').val();
174             $('#types_0').val(data.field_type);
175             xType = data.field_type;
176             $('#collations_0').val(data.field_collations);
177             addDateTimePicker();
178         });
179     });
181     // second column choice corresponds to the Y axis
182     $('#tableid_1').change(function () {
183         //AJAX request for field type, collation, operators, and value field
184         $.post('tbl_zoom_select.php', {
185             'ajax_request' : true,
186             'change_tbl_info' : true,
187             'server' : PMA_commonParams.get('server'),
188             'db' : PMA_commonParams.get('db'),
189             'table' : PMA_commonParams.get('table'),
190             'field' : $('#tableid_1').val(),
191             'it' : 1,
192             'token' : PMA_commonParams.get('token')
193         }, function (data) {
194             $('#tableFieldsId tr:eq(3) td:eq(0)').html(data.field_type);
195             $('#tableFieldsId tr:eq(3) td:eq(1)').html(data.field_collation);
196             $('#tableFieldsId tr:eq(3) td:eq(2)').html(data.field_operators);
197             $('#tableFieldsId tr:eq(3) td:eq(3)').html(data.field_value);
198             yLabel = $('#tableid_1').val();
199             $('#types_1').val(data.field_type);
200             yType = data.field_type;
201             $('#collations_1').val(data.field_collations);
202             addDateTimePicker();
203         });
204     });
206     $('#tableid_2').change(function () {
207         //AJAX request for field type, collation, operators, and value field
208         $.post('tbl_zoom_select.php', {
209             'ajax_request' : true,
210             'change_tbl_info' : true,
211             'server' : PMA_commonParams.get('server'),
212             'db' : PMA_commonParams.get('db'),
213             'table' : PMA_commonParams.get('table'),
214             'field' : $('#tableid_2').val(),
215             'it' : 2,
216             'token' : PMA_commonParams.get('token')
217         }, function (data) {
218             $('#tableFieldsId tr:eq(6) td:eq(0)').html(data.field_type);
219             $('#tableFieldsId tr:eq(6) td:eq(1)').html(data.field_collation);
220             $('#tableFieldsId tr:eq(6) td:eq(2)').html(data.field_operators);
221             $('#tableFieldsId tr:eq(6) td:eq(3)').html(data.field_value);
222             $('#types_2').val(data.field_type);
223             $('#collations_2').val(data.field_collations);
224             addDateTimePicker();
225         });
226     });
228     $('#tableid_3').change(function () {
229         //AJAX request for field type, collation, operators, and value field
230         $.post('tbl_zoom_select.php', {
231             'ajax_request' : true,
232             'change_tbl_info' : true,
233             'server' : PMA_commonParams.get('server'),
234             'db' : PMA_commonParams.get('db'),
235             'table' : PMA_commonParams.get('table'),
236             'field' : $('#tableid_3').val(),
237             'it' : 3,
238             'token' : PMA_commonParams.get('token')
239         }, function (data) {
240             $('#tableFieldsId tr:eq(8) td:eq(0)').html(data.field_type);
241             $('#tableFieldsId tr:eq(8) td:eq(1)').html(data.field_collation);
242             $('#tableFieldsId tr:eq(8) td:eq(2)').html(data.field_operators);
243             $('#tableFieldsId tr:eq(8) td:eq(3)').html(data.field_value);
244             $('#types_3').val(data.field_type);
245             $('#collations_3').val(data.field_collations);
246             addDateTimePicker();
247         });
248     });
250     /**
251      * Input form validation
252      **/
253     $('#inputFormSubmitId').click(function () {
254         if ($('#tableid_0').get(0).selectedIndex === 0 || $('#tableid_1').get(0).selectedIndex === 0) {
255             PMA_ajaxShowMessage(PMA_messages.strInputNull);
256         } else if (xLabel == yLabel) {
257             PMA_ajaxShowMessage(PMA_messages.strSameInputs);
258         }
259     });
261     /**
262       ** Prepare a div containing a link, otherwise it's incorrectly displayed
263       ** after a couple of clicks
264       **/
265     $('<div id="togglesearchformdiv"><a id="togglesearchformlink"></a></div>')
266         .insertAfter('#zoom_search_form')
267         // don't show it until we have results on-screen
268         .hide();
270     $('#togglesearchformlink')
271         .html(PMA_messages.strShowSearchCriteria)
272         .bind('click', function () {
273             var $link = $(this);
274             $('#zoom_search_form').slideToggle();
275             if ($link.text() == PMA_messages.strHideSearchCriteria) {
276                 $link.text(PMA_messages.strShowSearchCriteria);
277             } else {
278                 $link.text(PMA_messages.strHideSearchCriteria);
279             }
280             // avoid default click action
281             return false;
282         });
284     /**
285      ** Set dialog properties for the data display form
286      **/
287     var buttonOptions = {};
288     /*
289      * Handle saving of a row in the editor
290      */
291     buttonOptions[PMA_messages.strSave] = function () {
292         //Find changed values by comparing form values with selectedRow Object
293         var newValues = {};//Stores the values changed from original
294         var sqlTypes = {};
295         var it = 0;
296         var xChange = false;
297         var yChange = false;
298         var key;
299         var tempGetVal = function () {
300             return $(this).val();
301         };
302         for (key in selectedRow) {
303             var oldVal = selectedRow[key];
304             var newVal = ($('#edit_fields_null_id_' + it).prop('checked')) ? null : $('#edit_fieldID_' + it).val();
305             if (newVal instanceof Array) { // when the column is of type SET
306                 newVal =  $('#edit_fieldID_' + it).map(tempGetVal).get().join(",");
307             }
308             if (oldVal != newVal) {
309                 selectedRow[key] = newVal;
310                 newValues[key] = newVal;
311                 if (key == xLabel) {
312                     xChange = true;
313                     searchedData[searchedDataKey][xLabel] = newVal;
314                 } else if (key == yLabel) {
315                     yChange = true;
316                     searchedData[searchedDataKey][yLabel] = newVal;
317                 }
318             }
319             var $input = $('#edit_fieldID_' + it);
320             if ($input.hasClass('bit')) {
321                 sqlTypes[key] = 'bit';
322             } else {
323                 sqlTypes[key] = null;
324             }
325             it++;
326         } //End data update
328         //Update the chart series and replot
329         if (xChange || yChange) {
330             //Logic similar to plot generation, replot only if xAxis changes or yAxis changes.
331             //Code includes a lot of checks so as to replot only when necessary
332             if (xChange) {
333                 xCord[searchedDataKey] = selectedRow[xLabel];
334                 // [searchedDataKey][0] contains the x value
335                 if (xType == 'numeric') {
336                     series[0][searchedDataKey][0] = selectedRow[xLabel];
337                 } else if (xType == 'time') {
338                     series[0][searchedDataKey][0] =
339                         getTimeStamp(selectedRow[xLabel], $('#types_0').val());
340                 } else {
341                     series[0][searchedDataKey][0] = '';
342                     // TODO: text values
343                 }
344                 currentChart.series[0].data = series[0];
345                 // TODO: axis changing
346                 currentChart.replot();
348             }
349             if (yChange) {
350                 yCord[searchedDataKey] = selectedRow[yLabel];
351                 // [searchedDataKey][1] contains the y value
352                 if (yType == 'numeric') {
353                     series[0][searchedDataKey][1] = selectedRow[yLabel];
354                 } else if (yType == 'time') {
355                     series[0][searchedDataKey][1] =
356                         getTimeStamp(selectedRow[yLabel], $('#types_1').val());
357                 } else {
358                     series[0][searchedDataKey][1] = '';
359                     // TODO: text values
360                 }
361                 currentChart.series[0].data = series[0];
362                 // TODO: axis changing
363                 currentChart.replot();
364             }
365         } //End plot update
367         //Generate SQL query for update
368         if (!isEmpty(newValues)) {
369             var sql_query = 'UPDATE `' + PMA_commonParams.get('table') + '` SET ';
370             for (key in newValues) {
371                 sql_query += '`' + key + '`=';
372                 var value = newValues[key];
374                 // null
375                 if (value === null) {
376                     sql_query += 'NULL, ';
378                 // empty
379                 } else if ($.trim(value) === '') {
380                     sql_query += "'', ";
382                 // other
383                 } else {
384                     // type explicitly identified
385                     if (sqlTypes[key] !== null) {
386                         if (sqlTypes[key] == 'bit') {
387                             sql_query += "b'" + value + "', ";
388                         }
389                     // type not explicitly identified
390                     } else {
391                         if (!isNumeric(value)) {
392                             sql_query += "'" + value + "', ";
393                         } else {
394                             sql_query += value + ', ';
395                         }
396                     }
397                 }
398             }
399             // remove two extraneous characters ', '
400             sql_query = sql_query.substring(0, sql_query.length - 2);
401             sql_query += ' WHERE ' + PMA_urldecode(searchedData[searchedDataKey].where_clause);
403             //Post SQL query to sql.php
404             $.post('sql.php', {
405                     'token' : PMA_commonParams.get('token'),
406                     'server' : PMA_commonParams.get('server'),
407                     'db' : PMA_commonParams.get('db'),
408                     'ajax_request' : true,
409                     'sql_query' : sql_query,
410                     'inline_edit' : false
411                 }, function (data) {
412                     if (typeof data !== 'undefined' && data.success === true) {
413                         $('#sqlqueryresultsouter').html(data.sql_query);
414                         PMA_highlightSQL($('#sqlqueryresultsouter'));
415                     } else {
416                         PMA_ajaxShowMessage(data.error, false);
417                     }
418                 }); //End $.post
419         }//End database update
420         $("#dataDisplay").dialog('close');
421     };
422     buttonOptions[PMA_messages.strCancel] = function () {
423         $(this).dialog('close');
424     };
425     $("#dataDisplay").dialog({
426         autoOpen: false,
427         title: PMA_messages.strDataPointContent,
428         modal: true,
429         buttons: buttonOptions,
430         width: $('#dataDisplay').width() + 80,
431         open: function () {
432             $(this).find('input[type=checkbox]').css('margin', '0.5em');
433         }
434     });
435     /**
436      * Attach Ajax event handlers for input fields
437      * in the dialog. Used to submit the Ajax
438      * request when the ENTER key is pressed.
439      */
440     $(document).on('keydown', "#dataDisplay :input", function (e) {
441         if (e.which === 13) { // 13 is the ENTER key
442             e.preventDefault();
443             if (typeof buttonOptions[PMA_messages.strSave] === 'function') {
444                 buttonOptions[PMA_messages.strSave].call();
445             }
446         }
447     });
450     /*
451      * Generate plot using jqplot
452      */
454     if (searchedData !== null) {
455         $('#zoom_search_form')
456          .slideToggle()
457          .hide();
458         $('#togglesearchformlink')
459          .text(PMA_messages.strShowSearchCriteria);
460         $('#togglesearchformdiv').show();
461         var selectedRow;
462         var colorCodes = ['#FF0000', '#00FFFF', '#0000FF', '#0000A0', '#FF0080', '#800080', '#FFFF00', '#00FF00', '#FF00FF'];
463         var series = [];
464         var xCord = [];
465         var yCord = [];
466         var tempX, tempY;
467         var it = 0;
468         var xMax; // xAxis extreme max
469         var xMin; // xAxis extreme min
470         var yMax; // yAxis extreme max
471         var yMin; // yAxis extreme min
472         var xVal;
473         var yVal;
474         var format;
476         var options = {
477             series: [
478                 // for a scatter plot
479                 { showLine: false }
480             ],
481             grid: {
482                 drawBorder: false,
483                 shadow: false,
484                 background: 'rgba(0,0,0,0)'
485             },
486             axes: {
487                 xaxis: {
488                     label: $('#tableid_0').val(),
489                     labelRenderer: $.jqplot.CanvasAxisLabelRenderer
490                 },
491                 yaxis: {
492                     label: $('#tableid_1').val(),
493                     labelRenderer: $.jqplot.CanvasAxisLabelRenderer
494                 }
495             },
496             highlighter: {
497                 show: true,
498                 tooltipAxes: 'y',
499                 yvalues: 2,
500                 // hide the first y value
501                 formatString: '<span class="hide">%s</span>%s'
502             },
503             cursor: {
504                 show: true,
505                 zoom: true,
506                 showTooltip: false
507             }
508         };
510         // If data label is not set, do not show tooltips
511         if (dataLabel === '') {
512             options.highlighter.show = false;
513         }
515         // Classify types as either numeric,time,text
516         xType = getType(xType);
517         yType = getType(yType);
519         // could have multiple series but we'll have just one
520         series[0] = [];
522         if (xType == 'time') {
523             var originalXType = $('#types_0').val();
524             if (originalXType == 'date') {
525                 format = '%Y-%m-%d';
526             }
527             // TODO: does not seem to work
528             //else if (originalXType == 'time') {
529               //  format = '%H:%M';
530             //} else {
531             //    format = '%Y-%m-%d %H:%M';
532             //}
533             $.extend(options.axes.xaxis, {
534                 renderer: $.jqplot.DateAxisRenderer,
535                 tickOptions: {
536                     formatString: format
537                 }
538             });
539         }
540         if (yType == 'time') {
541             var originalYType = $('#types_1').val();
542             if (originalYType == 'date') {
543                 format = '%Y-%m-%d';
544             }
545             $.extend(options.axes.yaxis, {
546                 renderer: $.jqplot.DateAxisRenderer,
547                 tickOptions: {
548                     formatString: format
549                 }
550             });
551         }
553         $.each(searchedData, function (key, value) {
554             if (xType == 'numeric') {
555                 xVal = parseFloat(value[xLabel]);
556             }
557             if (xType == 'time') {
558                 xVal = getTimeStamp(value[xLabel], originalXType);
559             }
560             if (yType == 'numeric') {
561                 yVal = parseFloat(value[yLabel]);
562             }
563             if (yType == 'time') {
564                 yVal = getTimeStamp(value[yLabel], originalYType);
565             }
566             series[0].push([
567                 xVal,
568                 yVal,
569                 // extra Y values
570                 value[dataLabel], // for highlighter
571                                   // (may set an undefined value)
572                 value.where_clause, // for click on point
573                 key               // key from searchedData
574             ]);
575         });
577         // under IE 8, the initial display is mangled; after a manual
578         // resizing, it's ok
579         // under IE 9, everything is fine
580         currentChart = $.jqplot('querychart', series, options);
581         currentChart.resetZoom();
583         $('button.button-reset').click(function (event) {
584             event.preventDefault();
585             currentChart.resetZoom();
586         });
588         $('div#resizer').resizable();
589         $('div#resizer').bind('resizestop', function (event, ui) {
590             // make room so that the handle will still appear
591             $('div#querychart').height($('div#resizer').height() * 0.96);
592             $('div#querychart').width($('div#resizer').width() * 0.96);
593             currentChart.replot({resetAxes: true});
594         });
596         $('div#querychart').bind('jqplotDataClick',
597             function (event, seriesIndex, pointIndex, data) {
598                 searchedDataKey = data[4]; // key from searchedData (global)
599                 var field_id = 0;
600                 var post_params = {
601                     'ajax_request' : true,
602                     'get_data_row' : true,
603                     'server' : PMA_commonParams.get('server'),
604                     'db' : PMA_commonParams.get('db'),
605                     'table' : PMA_commonParams.get('table'),
606                     'where_clause' : data[3],
607                     'token' : PMA_commonParams.get('token')
608                 };
610                 $.post('tbl_zoom_select.php', post_params, function (data) {
611                     // Row is contained in data.row_info,
612                     // now fill the displayResultForm with row values
613                     var key;
614                     for (key in data.row_info) {
615                         var $field = $('#edit_fieldID_' + field_id);
616                         var $field_null = $('#edit_fields_null_id_' + field_id);
617                         if (data.row_info[key] === null) {
618                             $field_null.prop('checked', true);
619                             $field.val('');
620                         } else {
621                             $field_null.prop('checked', false);
622                             if ($field.attr('multiple')) { // when the column is of type SET
623                                 $field.val(data.row_info[key].split(','));
624                             } else {
625                                 $field.val(data.row_info[key]);
626                             }
627                         }
628                         field_id++;
629                     }
630                     selectedRow = {};
631                     selectedRow = data.row_info;
632                 });
634                 $("#dataDisplay").dialog("open");
635             }
636         );
637     }