server_status_monitor.js 83.8 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181
/* vim: set expandtab sw=4 ts=4 sts=4: */
var runtime = {};
var server_time_diff;
var server_os;
var is_superuser;
var server_db_isLocal;
var chartSize;
AJAX.registerOnload('server_status_monitor.js', function () {
    var $js_data_form = $('#js_data');
    server_time_diff  = new Date().getTime() - $js_data_form.find('input[name=server_time]').val();
    server_os =         $js_data_form.find('input[name=server_os]').val();
    is_superuser =      $js_data_form.find('input[name=is_superuser]').val();
    server_db_isLocal = $js_data_form.find('input[name=server_db_isLocal]').val();
});

/**
 * Unbind all event handlers before tearing down a page
 */
AJAX.registerTeardown('server_status_monitor.js', function () {
    $('#emptyDialog').remove();
    $('#addChartDialog').remove();
    $('a.popupLink').off('click');
    $('body').off('click');
});
/**
 * Popup behaviour
 */
AJAX.registerOnload('server_status_monitor.js', function () {
    $('<div />')
        .attr('id', 'emptyDialog')
        .appendTo('#page_content');
    $('#addChartDialog')
        .appendTo('#page_content');

    $('a.popupLink').click(function () {
        var $link = $(this);
        $('div.' + $link.attr('href').substr(1))
            .show()
            .offset({ top: $link.offset().top + $link.height() + 5, left: $link.offset().left })
            .addClass('openedPopup');

        return false;
    });
    $('body').click(function (event) {
        $('div.openedPopup').each(function () {
            var $cnt = $(this);
            var pos = $cnt.offset();
            // Hide if the mouseclick is outside the popupcontent
            if (event.pageX < pos.left ||
                event.pageY < pos.top ||
                event.pageX > pos.left + $cnt.outerWidth() ||
                event.pageY > pos.top + $cnt.outerHeight()
            ) {
                $cnt.hide().removeClass('openedPopup');
            }
        });
    });
});

AJAX.registerTeardown('server_status_monitor.js', function () {
    $('a[href="#rearrangeCharts"], a[href="#endChartEditMode"]').off('click');
    $('div.popupContent select[name="chartColumns"]').off('change');
    $('div.popupContent select[name="gridChartRefresh"]').off('change');
    $('a[href="#addNewChart"]').off('click');
    $('a[href="#exportMonitorConfig"]').off('click');
    $('a[href="#importMonitorConfig"]').off('click');
    $('a[href="#clearMonitorConfig"]').off('click');
    $('a[href="#pauseCharts"]').off('click');
    $('a[href="#monitorInstructionsDialog"]').off('click');
    $('input[name="chartType"]').off('click');
    $('input[name="useDivisor"]').off('click');
    $('input[name="useUnit"]').off('click');
    $('select[name="varChartList"]').off('click');
    $('a[href="#kibDivisor"]').off('click');
    $('a[href="#mibDivisor"]').off('click');
    $('a[href="#submitClearSeries"]').off('click');
    $('a[href="#submitAddSeries"]').off('click');
    // $("input#variableInput").destroy();
    $('#chartPreset').off('click');
    $('#chartStatusVar').off('click');
    destroyGrid();
});

AJAX.registerOnload('server_status_monitor.js', function () {
    // Show tab links
    $('div.tabLinks').show();
    $('#loadingMonitorIcon').remove();
    // Codemirror is loaded on demand so we might need to initialize it
    if (! codemirror_editor) {
        var $elm = $('#sqlquery');
        if ($elm.length > 0 && typeof CodeMirror !== 'undefined') {
            codemirror_editor = CodeMirror.fromTextArea(
                $elm[0],
                {
                    lineNumbers: true,
                    matchBrackets: true,
                    indentUnit: 4,
                    mode: 'text/x-mysql',
                    lineWrapping: true
                }
            );
        }
    }
    // Timepicker is loaded on demand so we need to initialize
    // datetime fields from the 'load log' dialog
    $('#logAnalyseDialog').find('.datetimefield').each(function () {
        PMA_addDatepicker($(this));
    });

    /** ** Monitor charting implementation ****/
    /* Saves the previous ajax response for differential values */
    var oldChartData = null;
    // Holds about to be created chart
    var newChart = null;
    var chartSpacing;

    // Whenever the monitor object (runtime.charts) or the settings object
    // (monitorSettings) changes in a way incompatible to the previous version,
    // increase this number. It will reset the users monitor and settings object
    // in his localStorage to the default configuration
    var monitorProtocolVersion = '1.0';

    // Runtime parameter of the monitor, is being fully set in initGrid()
    runtime = {
        // Holds all visible charts in the grid
        charts: null,
        // Stores the timeout handler so it can be cleared
        refreshTimeout: null,
        // Stores the GET request to refresh the charts
        refreshRequest: null,
        // Chart auto increment
        chartAI: 0,
        // To play/pause the monitor
        redrawCharts: false,
        // Object that contains a list of nodes that need to be retrieved
        // from the server for chart updates
        dataList: [],
        // Current max points per chart (needed for auto calculation)
        gridMaxPoints: 20,
        // displayed time frame
        xmin: -1,
        xmax: -1
    };
    var monitorSettings = null;

    var defaultMonitorSettings = {
        columns: 3,
        chartSize: { width: 295, height: 250 },
        // Max points in each chart. Settings it to 'auto' sets
        // gridMaxPoints to (chartwidth - 40) / 12
        gridMaxPoints: 'auto',
        /* Refresh rate of all grid charts in ms */
        gridRefresh: 5000
    };

    // Allows drag and drop rearrange and print/edit icons on charts
    var editMode = false;

    /* List of preconfigured charts that the user may select */
    var presetCharts = {
        // Query cache efficiency
        'qce': {
            title: PMA_messages.strQueryCacheEfficiency,
            series: [{
                label: PMA_messages.strQueryCacheEfficiency
            }],
            nodes: [{
                dataPoints: [{ type: 'statusvar', name: 'Qcache_hits' }, { type: 'statusvar', name: 'Com_select' }],
                transformFn: 'qce'
            }],
            maxYLabel: 0
        },
        // Query cache usage
        'qcu': {
            title: PMA_messages.strQueryCacheUsage,
            series: [{
                label: PMA_messages.strQueryCacheUsed
            }],
            nodes: [{
                dataPoints: [{ type: 'statusvar', name: 'Qcache_free_memory' }, { type: 'servervar', name: 'query_cache_size' }],
                transformFn: 'qcu'
            }],
            maxYLabel: 0
        }
    };

    // time span selection
    var selectionTimeDiff = [];
    var selectionStartX;
    var selectionStartY;
    var selectionEndX;
    var selectionEndY;
    var drawTimeSpan = false;

    // chart tooltip
    var tooltipBox;

    /* Add OS specific system info charts to the preset chart list */
    switch (server_os) {
    case 'WINNT':
        $.extend(presetCharts, {
            'cpu': {
                title: PMA_messages.strSystemCPUUsage,
                series: [{
                    label: PMA_messages.strAverageLoad
                }],
                nodes: [{
                    dataPoints: [{ type: 'cpu', name: 'loadavg' }]
                }],
                maxYLabel: 100
            },

            'memory': {
                title: PMA_messages.strSystemMemory,
                series: [{
                    label: PMA_messages.strTotalMemory,
                    fill: true
                }, {
                    dataType: 'memory',
                    label: PMA_messages.strUsedMemory,
                    fill: true
                }],
                nodes: [{ dataPoints: [{ type: 'memory', name: 'MemTotal' }], valueDivisor: 1024 },
                    { dataPoints: [{ type: 'memory', name: 'MemUsed' }], valueDivisor: 1024 }
                ],
                maxYLabel: 0
            },

            'swap': {
                title: PMA_messages.strSystemSwap,
                series: [{
                    label: PMA_messages.strTotalSwap,
                    fill: true
                }, {
                    label: PMA_messages.strUsedSwap,
                    fill: true
                }],
                nodes: [{ dataPoints: [{ type: 'memory', name: 'SwapTotal' }] },
                    { dataPoints: [{ type: 'memory', name: 'SwapUsed' }] }
                ],
                maxYLabel: 0
            }
        });
        break;

    case 'Linux':
        $.extend(presetCharts, {
            'cpu': {
                title: PMA_messages.strSystemCPUUsage,
                series: [{
                    label: PMA_messages.strAverageLoad
                }],
                nodes: [{ dataPoints: [{ type: 'cpu', name: 'irrelevant' }], transformFn: 'cpu-linux' }],
                maxYLabel: 0
            },
            'memory': {
                title: PMA_messages.strSystemMemory,
                series: [
                    { label: PMA_messages.strBufferedMemory, fill: true },
                    { label: PMA_messages.strUsedMemory, fill: true },
                    { label: PMA_messages.strCachedMemory, fill: true },
                    { label: PMA_messages.strFreeMemory, fill: true }
                ],
                nodes: [
                    { dataPoints: [{ type: 'memory', name: 'Buffers' }], valueDivisor: 1024 },
                    { dataPoints: [{ type: 'memory', name: 'MemUsed' }], valueDivisor: 1024 },
                    { dataPoints: [{ type: 'memory', name: 'Cached' }],  valueDivisor: 1024 },
                    { dataPoints: [{ type: 'memory', name: 'MemFree' }], valueDivisor: 1024 }
                ],
                maxYLabel: 0
            },
            'swap': {
                title: PMA_messages.strSystemSwap,
                series: [
                    { label: PMA_messages.strCachedSwap, fill: true },
                    { label: PMA_messages.strUsedSwap, fill: true },
                    { label: PMA_messages.strFreeSwap, fill: true }
                ],
                nodes: [
                    { dataPoints: [{ type: 'memory', name: 'SwapCached' }], valueDivisor: 1024 },
                    { dataPoints: [{ type: 'memory', name: 'SwapUsed' }], valueDivisor: 1024 },
                    { dataPoints: [{ type: 'memory', name: 'SwapFree' }], valueDivisor: 1024 }
                ],
                maxYLabel: 0
            }
        });
        break;

    case 'SunOS':
        $.extend(presetCharts, {
            'cpu': {
                title: PMA_messages.strSystemCPUUsage,
                series: [{
                    label: PMA_messages.strAverageLoad
                }],
                nodes: [{
                    dataPoints: [{ type: 'cpu', name: 'loadavg' }]
                }],
                maxYLabel: 0
            },
            'memory': {
                title: PMA_messages.strSystemMemory,
                series: [
                    { label: PMA_messages.strUsedMemory, fill: true },
                    { label: PMA_messages.strFreeMemory, fill: true }
                ],
                nodes: [
                    { dataPoints: [{ type: 'memory', name: 'MemUsed' }], valueDivisor: 1024 },
                    { dataPoints: [{ type: 'memory', name: 'MemFree' }], valueDivisor: 1024 }
                ],
                maxYLabel: 0
            },
            'swap': {
                title: PMA_messages.strSystemSwap,
                series: [
                    { label: PMA_messages.strUsedSwap, fill: true },
                    { label: PMA_messages.strFreeSwap, fill: true }
                ],
                nodes: [
                    { dataPoints: [{ type: 'memory', name: 'SwapUsed' }], valueDivisor: 1024 },
                    { dataPoints: [{ type: 'memory', name: 'SwapFree' }], valueDivisor: 1024 }
                ],
                maxYLabel: 0
            }
        });
        break;
    }

    // Default setting for the chart grid
    var defaultChartGrid = {
        'c0': {
            title: PMA_messages.strQuestions,
            series: [
                { label: PMA_messages.strQuestions }
            ],
            nodes: [
                { dataPoints: [{ type: 'statusvar', name: 'Questions' }], display: 'differential' }
            ],
            maxYLabel: 0
        },
        'c1': {
            title: PMA_messages.strChartConnectionsTitle,
            series: [
                { label: PMA_messages.strConnections },
                { label: PMA_messages.strProcesses }
            ],
            nodes: [
                { dataPoints: [{ type: 'statusvar', name: 'Connections' }], display: 'differential' },
                { dataPoints: [{ type: 'proc', name: 'processes' }] }
            ],
            maxYLabel: 0
        },
        'c2': {
            title: PMA_messages.strTraffic,
            series: [
                { label: PMA_messages.strBytesSent },
                { label: PMA_messages.strBytesReceived }
            ],
            nodes: [
                { dataPoints: [{ type: 'statusvar', name: 'Bytes_sent' }], display: 'differential', valueDivisor: 1024 },
                { dataPoints: [{ type: 'statusvar', name: 'Bytes_received' }], display: 'differential', valueDivisor: 1024 }
            ],
            maxYLabel: 0
        }
    };

    // Server is localhost => We can add cpu/memory/swap to the default chart
    if (server_db_isLocal && typeof presetCharts.cpu !== 'undefined') {
        defaultChartGrid.c3 = presetCharts.cpu;
        defaultChartGrid.c4 = presetCharts.memory;
        defaultChartGrid.c5 = presetCharts.swap;
    }

    $('a[href="#rearrangeCharts"], a[href="#endChartEditMode"]').click(function (event) {
        event.preventDefault();
        editMode = !editMode;
        if ($(this).attr('href') === '#endChartEditMode') {
            editMode = false;
        }

        $('a[href="#endChartEditMode"]').toggle(editMode);

        if (editMode) {
            // Close the settings popup
            $('div.popupContent').hide().removeClass('openedPopup');

            $('#chartGrid').sortableTable({
                ignoreRect: {
                    top: 8,
                    left: chartSize.width - 63,
                    width: 54,
                    height: 24
                }
            });
        } else {
            $('#chartGrid').sortableTable('destroy');
        }
        saveMonitor(); // Save settings
        return false;
    });

    // global settings
    $('div.popupContent select[name="chartColumns"]').change(function () {
        monitorSettings.columns = parseInt(this.value, 10);

        calculateChartSize();
        // Empty cells should keep their size so you can drop onto them
        $('#chartGrid').find('tr td').css('width', chartSize.width + 'px');
        $('#chartGrid').find('.monitorChart').css({
            width: chartSize.width + 'px',
            height: chartSize.height + 'px'
        });

        /* Reorder all charts that it fills all column cells */
        var numColumns;
        var $tr = $('#chartGrid').find('tr:first');
        var row = 0;

        var tempManageCols = function () {
            if (numColumns > monitorSettings.columns) {
                if ($tr.next().length === 0) {
                    $tr.after('<tr></tr>');
                }
                $tr.next().prepend($(this));
            }
            numColumns++;
        };

        var tempAddCol = function () {
            if ($(this).next().length !== 0) {
                $(this).append($(this).next().find('td:first'));
            }
        };

        while ($tr.length !== 0) {
            numColumns = 1;
            // To many cells in one row => put into next row
            $tr.find('td').each(tempManageCols);

            // To little cells in one row => for each cell to little,
            // move all cells backwards by 1
            if ($tr.next().length > 0) {
                var cnt = monitorSettings.columns - $tr.find('td').length;
                for (var i = 0; i < cnt; i++) {
                    $tr.append($tr.next().find('td:first'));
                    $tr.nextAll().each(tempAddCol);
                }
            }

            $tr = $tr.next();
            row++;
        }

        if (monitorSettings.gridMaxPoints === 'auto') {
            runtime.gridMaxPoints = Math.round((chartSize.width - 40) / 12);
        }

        runtime.xmin = new Date().getTime() - server_time_diff - runtime.gridMaxPoints * monitorSettings.gridRefresh;
        runtime.xmax = new Date().getTime() - server_time_diff + monitorSettings.gridRefresh;

        if (editMode) {
            $('#chartGrid').sortableTable('refresh');
        }

        refreshChartGrid();
        saveMonitor(); // Save settings
    });

    $('div.popupContent select[name="gridChartRefresh"]').change(function () {
        monitorSettings.gridRefresh = parseInt(this.value, 10) * 1000;
        clearTimeout(runtime.refreshTimeout);

        if (runtime.refreshRequest) {
            runtime.refreshRequest.abort();
        }

        runtime.xmin = new Date().getTime() - server_time_diff - runtime.gridMaxPoints * monitorSettings.gridRefresh;
        // fixing chart shift towards left on refresh rate change
        // runtime.xmax = new Date().getTime() - server_time_diff + monitorSettings.gridRefresh;
        runtime.refreshTimeout = setTimeout(refreshChartGrid, monitorSettings.gridRefresh);

        saveMonitor(); // Save settings
    });

    $('a[href="#addNewChart"]').click(function (event) {
        event.preventDefault();
        var dlgButtons = { };

        dlgButtons[PMA_messages.strAddChart] = function () {
            var type = $('input[name="chartType"]:checked').val();

            if (type === 'preset') {
                newChart = presetCharts[$('#addChartDialog').find('select[name="presetCharts"]').prop('value')];
            } else {
                // If user builds his own chart, it's being set/updated
                // each time he adds a series
                // So here we only warn if he didn't add a series yet
                if (! newChart || ! newChart.nodes || newChart.nodes.length === 0) {
                    alert(PMA_messages.strAddOneSeriesWarning);
                    return;
                }
            }

            newChart.title = $('input[name="chartTitle"]').val();
            // Add a cloned object to the chart grid
            addChart($.extend(true, {}, newChart));

            newChart = null;

            saveMonitor(); // Save settings

            $(this).dialog('close');
        };

        dlgButtons[PMA_messages.strClose] = function () {
            newChart = null;
            $('span#clearSeriesLink').hide();
            $('#seriesPreview').html('');
            $(this).dialog('close');
        };

        var $presetList = $('#addChartDialog').find('select[name="presetCharts"]');
        if ($presetList.html().length === 0) {
            $.each(presetCharts, function (key, value) {
                $presetList.append('<option value="' + key + '">' + value.title + '</option>');
            });
            $presetList.change(function () {
                $('input[name="chartTitle"]').val(
                    $presetList.find(':selected').text()
                );
                $('#chartPreset').prop('checked', true);
            });
            $('#chartPreset').click(function () {
                $('input[name="chartTitle"]').val(
                    $presetList.find(':selected').text()
                );
            });
            $('#chartStatusVar').click(function () {
                $('input[name="chartTitle"]').val(
                    $('#chartSeries').find(':selected').text().replace(/_/g, ' ')
                );
            });
            $('#chartSeries').change(function () {
                $('input[name="chartTitle"]').val(
                    $('#chartSeries').find(':selected').text().replace(/_/g, ' ')
                );
            });
        }

        $('#addChartDialog').dialog({
            width: 'auto',
            height: 'auto',
            buttons: dlgButtons
        });

        $('#seriesPreview').html('<i>' + PMA_messages.strNone + '</i>');

        return false;
    });

    $('a[href="#exportMonitorConfig"]').click(function (event) {
        event.preventDefault();
        var gridCopy = {};
        $.each(runtime.charts, function (key, elem) {
            gridCopy[key] = {};
            gridCopy[key].nodes = elem.nodes;
            gridCopy[key].settings = elem.settings;
            gridCopy[key].title = elem.title;
        });
        var exportData = {
            monitorCharts: gridCopy,
            monitorSettings: monitorSettings
        };

        var blob = new Blob([JSON.stringify(exportData)], { type: 'application/octet-stream' });
        var url = window.URL.createObjectURL(blob);
        window.location.href = url;
        window.URL.revokeObjectURL(url);
    });

    $('a[href="#importMonitorConfig"]').click(function (event) {
        event.preventDefault();
        $('#emptyDialog').dialog({ title: PMA_messages.strImportDialogTitle });
        $('#emptyDialog').html(PMA_messages.strImportDialogMessage + ':<br/><form>' +
            '<input type="file" name="file" id="import_file"> </form>');

        var dlgBtns = {};

        dlgBtns[PMA_messages.strImport] = function () {
            var input = $('#emptyDialog').find('#import_file')[0];
            var reader = new FileReader();

            reader.onerror = function (event) {
                alert(PMA_messages.strFailedParsingConfig + '\n' + event.target.error.code);
            };
            reader.onload = function (e) {
                var data = e.target.result;

                // Try loading config
                try {
                    json = JSON.parse(data);
                } catch (err) {
                    alert(PMA_messages.strFailedParsingConfig);
                    $('#emptyDialog').dialog('close');
                    return;
                }

                // Basic check, is this a monitor config json?
                if (!json || ! json.monitorCharts || ! json.monitorCharts) {
                    alert(PMA_messages.strFailedParsingConfig);
                    $('#emptyDialog').dialog('close');
                    return;
                }

                // If json ok, try applying config
                try {
                    window.localStorage.monitorCharts = JSON.stringify(json.monitorCharts);
                    window.localStorage.monitorSettings = JSON.stringify(json.monitorSettings);
                    rebuildGrid();
                } catch (err) {
                    console.log(err);
                    alert(PMA_messages.strFailedBuildingGrid);
                    // If an exception is thrown, load default again
                    if (isStorageSupported('localStorage')) {
                        window.localStorage.removeItem('monitorCharts');
                        window.localStorage.removeItem('monitorSettings');
                    }
                    rebuildGrid();
                }

                $('#emptyDialog').dialog('close');
            };
            reader.readAsText(input.files[0]);
        };

        dlgBtns[PMA_messages.strCancel] = function () {
            $(this).dialog('close');
        };

        $('#emptyDialog').dialog({
            width: 'auto',
            height: 'auto',
            buttons: dlgBtns
        });
    });

    $('a[href="#clearMonitorConfig"]').click(function (event) {
        event.preventDefault();
        if (isStorageSupported('localStorage')) {
            window.localStorage.removeItem('monitorCharts');
            window.localStorage.removeItem('monitorSettings');
            window.localStorage.removeItem('monitorVersion');
        }
        $(this).hide();
        rebuildGrid();
    });

    $('a[href="#pauseCharts"]').click(function (event) {
        event.preventDefault();
        runtime.redrawCharts = ! runtime.redrawCharts;
        if (! runtime.redrawCharts) {
            $(this).html(PMA_getImage('play') + PMA_messages.strResumeMonitor);
        } else {
            $(this).html(PMA_getImage('pause') + PMA_messages.strPauseMonitor);
            if (! runtime.charts) {
                initGrid();
                $('a[href="#settingsPopup"]').show();
            }
        }
        return false;
    });

    $('a[href="#monitorInstructionsDialog"]').click(function (event) {
        event.preventDefault();

        var $dialog = $('#monitorInstructionsDialog');

        $dialog.dialog({
            width: 595,
            height: 'auto'
        }).find('img.ajaxIcon').show();

        var loadLogVars = function (getvars) {
            var vars = { ajax_request: true, logging_vars: true };
            if (getvars) {
                $.extend(vars, getvars);
            }

            $.post('server_status_monitor.php' + PMA_commonParams.get('common_query'), vars,
                function (data) {
                    var logVars;
                    if (typeof data !== 'undefined' && data.success === true) {
                        logVars = data.message;
                    } else {
                        return serverResponseError();
                    }
                    var icon = PMA_getImage('s_success');
                    var msg = '';
                    var str = '';

                    if (logVars.general_log === 'ON') {
                        if (logVars.slow_query_log === 'ON') {
                            msg = PMA_messages.strBothLogOn;
                        } else {
                            msg = PMA_messages.strGenLogOn;
                        }
                    }

                    if (msg.length === 0 && logVars.slow_query_log === 'ON') {
                        msg = PMA_messages.strSlowLogOn;
                    }

                    if (msg.length === 0) {
                        icon = PMA_getImage('s_error');
                        msg = PMA_messages.strBothLogOff;
                    }

                    str = '<b>' + PMA_messages.strCurrentSettings + '</b><br/><div class="smallIndent">';
                    str += icon + msg + '<br />';

                    if (logVars.log_output !== 'TABLE') {
                        str += PMA_getImage('s_error') + ' ' + PMA_messages.strLogOutNotTable + '<br />';
                    } else {
                        str += PMA_getImage('s_success') + ' ' + PMA_messages.strLogOutIsTable + '<br />';
                    }

                    if (logVars.slow_query_log === 'ON') {
                        if (logVars.long_query_time > 2) {
                            str += PMA_getImage('s_attention') + ' ';
                            str += PMA_sprintf(PMA_messages.strSmallerLongQueryTimeAdvice, logVars.long_query_time);
                            str += '<br />';
                        }

                        if (logVars.long_query_time < 2) {
                            str += PMA_getImage('s_success') + ' ';
                            str += PMA_sprintf(PMA_messages.strLongQueryTimeSet, logVars.long_query_time);
                            str += '<br />';
                        }
                    }

                    str += '</div>';

                    if (is_superuser) {
                        str += '<p></p><b>' + PMA_messages.strChangeSettings + '</b>';
                        str += '<div class="smallIndent">';
                        str += PMA_messages.strSettingsAppliedGlobal + '<br/>';

                        var varValue = 'TABLE';
                        if (logVars.log_output === 'TABLE') {
                            varValue = 'FILE';
                        }

                        str += '- <a class="set" href="#log_output-' + varValue + '">';
                        str += PMA_sprintf(PMA_messages.strSetLogOutput, varValue);
                        str += ' </a><br />';

                        if (logVars.general_log !== 'ON') {
                            str += '- <a class="set" href="#general_log-ON">';
                            str += PMA_sprintf(PMA_messages.strEnableVar, 'general_log');
                            str += ' </a><br />';
                        } else {
                            str += '- <a class="set" href="#general_log-OFF">';
                            str += PMA_sprintf(PMA_messages.strDisableVar, 'general_log');
                            str += ' </a><br />';
                        }

                        if (logVars.slow_query_log !== 'ON') {
                            str += '- <a class="set" href="#slow_query_log-ON">';
                            str +=  PMA_sprintf(PMA_messages.strEnableVar, 'slow_query_log');
                            str += ' </a><br />';
                        } else {
                            str += '- <a class="set" href="#slow_query_log-OFF">';
                            str +=  PMA_sprintf(PMA_messages.strDisableVar, 'slow_query_log');
                            str += ' </a><br />';
                        }

                        varValue = 5;
                        if (logVars.long_query_time > 2) {
                            varValue = 1;
                        }

                        str += '- <a class="set" href="#long_query_time-' + varValue + '">';
                        str += PMA_sprintf(PMA_messages.setSetLongQueryTime, varValue);
                        str += ' </a><br />';
                    } else {
                        str += PMA_messages.strNoSuperUser + '<br/>';
                    }

                    str += '</div>';

                    $dialog.find('div.monitorUse').toggle(
                        logVars.log_output === 'TABLE' && (logVars.slow_query_log === 'ON' || logVars.general_log === 'ON')
                    );

                    $dialog.find('div.ajaxContent').html(str);
                    $dialog.find('img.ajaxIcon').hide();
                    $dialog.find('a.set').click(function () {
                        var nameValue = $(this).attr('href').split('-');
                        loadLogVars({ varName: nameValue[0].substr(1), varValue: nameValue[1] });
                        $dialog.find('img.ajaxIcon').show();
                    });
                }
            );
        };


        loadLogVars();

        return false;
    });

    $('input[name="chartType"]').change(function () {
        $('#chartVariableSettings').toggle(this.checked && this.value === 'variable');
        var title = $('input[name="chartTitle"]').val();
        if (title === PMA_messages.strChartTitle ||
            title === $('label[for="' + $('input[name="chartTitle"]').data('lastRadio') + '"]').text()
        ) {
            $('input[name="chartTitle"]')
                .data('lastRadio', $(this).attr('id'))
                .val($('label[for="' + $(this).attr('id') + '"]').text());
        }
    });

    $('input[name="useDivisor"]').change(function () {
        $('span.divisorInput').toggle(this.checked);
    });

    $('input[name="useUnit"]').change(function () {
        $('span.unitInput').toggle(this.checked);
    });

    $('select[name="varChartList"]').change(function () {
        if (this.selectedIndex !== 0) {
            $('#variableInput').val(this.value);
        }
    });

    $('a[href="#kibDivisor"]').click(function (event) {
        event.preventDefault();
        $('input[name="valueDivisor"]').val(1024);
        $('input[name="valueUnit"]').val(PMA_messages.strKiB);
        $('span.unitInput').toggle(true);
        $('input[name="useUnit"]').prop('checked', true);
        return false;
    });

    $('a[href="#mibDivisor"]').click(function (event) {
        event.preventDefault();
        $('input[name="valueDivisor"]').val(1024 * 1024);
        $('input[name="valueUnit"]').val(PMA_messages.strMiB);
        $('span.unitInput').toggle(true);
        $('input[name="useUnit"]').prop('checked', true);
        return false;
    });

    $('a[href="#submitClearSeries"]').click(function (event) {
        event.preventDefault();
        $('#seriesPreview').html('<i>' + PMA_messages.strNone + '</i>');
        newChart = null;
        $('#clearSeriesLink').hide();
    });

    $('a[href="#submitAddSeries"]').click(function (event) {
        event.preventDefault();
        if ($('#variableInput').val() === '') {
            return false;
        }

        if (newChart === null) {
            $('#seriesPreview').html('');

            newChart = {
                title: $('input[name="chartTitle"]').val(),
                nodes: [],
                series: [],
                maxYLabel: 0
            };
        }

        var serie = {
            dataPoints: [{ type: 'statusvar', name: $('#variableInput').val() }],
            display: $('input[name="differentialValue"]').prop('checked') ? 'differential' : ''
        };

        if (serie.dataPoints[0].name === 'Processes') {
            serie.dataPoints[0].type = 'proc';
        }

        if ($('input[name="useDivisor"]').prop('checked')) {
            serie.valueDivisor = parseInt($('input[name="valueDivisor"]').val(), 10);
        }

        if ($('input[name="useUnit"]').prop('checked')) {
            serie.unit = $('input[name="valueUnit"]').val();
        }

        var str = serie.display === 'differential' ? ', ' + PMA_messages.strDifferential : '';
        str += serie.valueDivisor ? (', ' + PMA_sprintf(PMA_messages.strDividedBy, serie.valueDivisor)) : '';
        str += serie.unit ? (', ' + PMA_messages.strUnit + ': ' + serie.unit) : '';

        var newSeries = {
            label: $('#variableInput').val().replace(/_/g, ' ')
        };
        newChart.series.push(newSeries);
        $('#seriesPreview').append('- ' + escapeHtml(newSeries.label + str) + '<br/>');
        newChart.nodes.push(serie);
        $('#variableInput').val('');
        $('input[name="differentialValue"]').prop('checked', true);
        $('input[name="useDivisor"]').prop('checked', false);
        $('input[name="useUnit"]').prop('checked', false);
        $('input[name="useDivisor"]').trigger('change');
        $('input[name="useUnit"]').trigger('change');
        $('select[name="varChartList"]').get(0).selectedIndex = 0;

        $('#clearSeriesLink').show();

        return false;
    });

    $('#variableInput').autocomplete({
        source: variableNames
    });

    /* Initializes the monitor, called only once */
    function initGrid () {
        var i;

        /* Apply default values & config */
        if (isStorageSupported('localStorage')) {
            if (typeof window.localStorage.monitorCharts !== 'undefined') {
                runtime.charts = JSON.parse(window.localStorage.monitorCharts);
            }
            if (typeof window.localStorage.monitorSettings !== 'undefined') {
                monitorSettings = JSON.parse(window.localStorage.monitorSettings);
            }

            $('a[href="#clearMonitorConfig"]').toggle(runtime.charts !== null);

            if (runtime.charts !== null
                && typeof window.localStorage.monitorVersion !== 'undefined'
                && monitorProtocolVersion !== window.localStorage.monitorVersion
            ) {
                $('#emptyDialog').dialog({ title: PMA_messages.strIncompatibleMonitorConfig });
                $('#emptyDialog').html(PMA_messages.strIncompatibleMonitorConfigDescription);

                var dlgBtns = {};
                dlgBtns[PMA_messages.strClose] = function () {
                    $(this).dialog('close');
                };

                $('#emptyDialog').dialog({
                    width: 400,
                    buttons: dlgBtns
                });
            }
        }

        if (runtime.charts === null) {
            runtime.charts = defaultChartGrid;
        }
        if (monitorSettings === null) {
            monitorSettings = defaultMonitorSettings;
        }

        $('select[name="gridChartRefresh"]').val(monitorSettings.gridRefresh / 1000);
        $('select[name="chartColumns"]').val(monitorSettings.columns);

        if (monitorSettings.gridMaxPoints === 'auto') {
            runtime.gridMaxPoints = Math.round((monitorSettings.chartSize.width - 40) / 12);
        } else {
            runtime.gridMaxPoints = monitorSettings.gridMaxPoints;
        }

        runtime.xmin = new Date().getTime() - server_time_diff - runtime.gridMaxPoints * monitorSettings.gridRefresh;
        runtime.xmax = new Date().getTime() - server_time_diff + monitorSettings.gridRefresh;

        /* Calculate how much spacing there is between each chart */
        $('#chartGrid').html('<tr><td></td><td></td></tr><tr><td></td><td></td></tr>');
        chartSpacing = {
            width: $('#chartGrid').find('td:nth-child(2)').offset().left -
                $('#chartGrid').find('td:nth-child(1)').offset().left,
            height: $('#chartGrid').find('tr:nth-child(2) td:nth-child(2)').offset().top -
                $('#chartGrid').find('tr:nth-child(1) td:nth-child(1)').offset().top
        };
        $('#chartGrid').html('');

        /* Add all charts - in correct order */
        var keys = [];
        $.each(runtime.charts, function (key, value) {
            keys.push(key);
        });
        keys.sort();
        for (i = 0; i < keys.length; i++) {
            addChart(runtime.charts[keys[i]], true);
        }

        /* Fill in missing cells */
        var numCharts = $('#chartGrid').find('.monitorChart').length;
        var numMissingCells = (monitorSettings.columns - numCharts % monitorSettings.columns) % monitorSettings.columns;
        for (i = 0; i < numMissingCells; i++) {
            $('#chartGrid').find('tr:last').append('<td></td>');
        }

        // Empty cells should keep their size so you can drop onto them
        calculateChartSize();
        $('#chartGrid').find('tr td').css('width', chartSize.width + 'px');

        buildRequiredDataList();
        refreshChartGrid();
    }

    /* Calls destroyGrid() and initGrid(), but before doing so it saves the chart
     * data from each chart and restores it after the monitor is initialized again */
    function rebuildGrid () {
        var oldData = null;
        if (runtime.charts) {
            oldData = {};
            $.each(runtime.charts, function (key, chartObj) {
                for (var i = 0, l = chartObj.nodes.length; i < l; i++) {
                    oldData[chartObj.nodes[i].dataPoint] = [];
                    for (var j = 0, ll = chartObj.chart.series[i].data.length; j < ll; j++) {
                        oldData[chartObj.nodes[i].dataPoint].push([chartObj.chart.series[i].data[j].x, chartObj.chart.series[i].data[j].y]);
                    }
                }
            });
        }

        destroyGrid();
        initGrid();
    }

    /* Calculactes the dynamic chart size that depends on the column width */
    function calculateChartSize () {
        var panelWidth;
        if ($('body').height() > $(window).height()) { // has vertical scroll bar
            panelWidth = $('#logTable').innerWidth();
        } else {
            panelWidth = $('#logTable').innerWidth() - 10; // leave some space for vertical scroll bar
        }

        var wdt = panelWidth;
        var windowWidth = $(window).width();

        if (windowWidth > 768) {
            wdt = (panelWidth - monitorSettings.columns * chartSpacing.width) / monitorSettings.columns;
        }

        chartSize = {
            width: Math.floor(wdt),
            height: Math.floor(0.75 * wdt)
        };
    }

    /* Adds a chart to the chart grid */
    function addChart (chartObj, initialize) {
        var i;
        var settings = {
            title: escapeHtml(chartObj.title),
            grid: {
                drawBorder: false,
                shadow: false,
                background: 'rgba(0,0,0,0)'
            },
            axes: {
                xaxis: {
                    renderer: $.jqplot.DateAxisRenderer,
                    tickOptions: {
                        formatString: '%H:%M:%S',
                        showGridline: false
                    },
                    min: runtime.xmin,
                    max: runtime.xmax
                },
                yaxis: {
                    min: 0,
                    max: 100,
                    tickInterval: 20
                }
            },
            seriesDefaults: {
                rendererOptions: {
                    smooth: true
                },
                showLine: true,
                lineWidth: 2,
                markerOptions: {
                    size: 6
                }
            },
            highlighter: {
                show: true
            }
        };

        if (settings.title === PMA_messages.strSystemCPUUsage ||
            settings.title === PMA_messages.strQueryCacheEfficiency
        ) {
            settings.axes.yaxis.tickOptions = {
                formatString: '%d %%'
            };
        } else if (settings.title === PMA_messages.strSystemMemory ||
            settings.title === PMA_messages.strSystemSwap
        ) {
            settings.stackSeries = true;
            settings.axes.yaxis.tickOptions = {
                formatter: $.jqplot.byteFormatter(2) // MiB
            };
        } else if (settings.title === PMA_messages.strTraffic) {
            settings.axes.yaxis.tickOptions = {
                formatter: $.jqplot.byteFormatter(1) // KiB
            };
        } else if (settings.title === PMA_messages.strQuestions ||
            settings.title === PMA_messages.strConnections
        ) {
            settings.axes.yaxis.tickOptions = {
                formatter: function (format, val) {
                    if (Math.abs(val) >= 1000000) {
                        return $.jqplot.sprintf('%.3g M', val / 1000000);
                    } else if (Math.abs(val) >= 1000) {
                        return $.jqplot.sprintf('%.3g k', val / 1000);
                    } else {
                        return $.jqplot.sprintf('%d', val);
                    }
                }
            };
        }

        settings.series = chartObj.series;

        if ($('#' + 'gridchart' + runtime.chartAI).length === 0) {
            var numCharts = $('#chartGrid').find('.monitorChart').length;

            if (numCharts === 0 || (numCharts % monitorSettings.columns === 0)) {
                $('#chartGrid').append('<tr></tr>');
            }

            if (!chartSize) {
                calculateChartSize();
            }
            $('#chartGrid').find('tr:last').append(
                '<td><div id="gridChartContainer' + runtime.chartAI + '" class="">' +
                '<div class="ui-state-default monitorChart"' +
                ' id="gridchart' + runtime.chartAI + '"' +
                ' style="width:' + chartSize.width + 'px; height:' + chartSize.height + 'px;"></div>' +
                '</div></td>'
            );
        }

        // Set series' data as [0,0], smooth lines won't plot with data array having null values.
        // also chart won't plot initially with no data and data comes on refreshChartGrid()
        var series = [];
        for (i in chartObj.series) {
            series.push([[0, 0]]);
        }

        var tempTooltipContentEditor = function (str, seriesIndex, pointIndex, plot) {
            var j;
            // TODO: move style to theme CSS
            var tooltipHtml = '<div style="font-size:12px;background-color:#FFFFFF;' +
                'opacity:0.95;filter:alpha(opacity=95);padding:5px;">';
            // x value i.e. time
            var timeValue = str.split(',')[0];
            var seriesValue;
            tooltipHtml += 'Time: ' + timeValue;
            tooltipHtml += '<span style="font-weight:bold;">';
            // Add y values to the tooltip per series
            for (j in plot.series) {
                // get y value if present
                if (plot.series[j].data.length > pointIndex) {
                    seriesValue = plot.series[j].data[pointIndex][1];
                } else {
                    return;
                }
                var seriesLabel = plot.series[j].label;
                var seriesColor = plot.series[j].color;
                // format y value
                if (plot.series[0]._yaxis.tickOptions.formatter) {
                    // using formatter function
                    seriesValue = plot.series[0]._yaxis.tickOptions.formatter('%s', seriesValue);
                } else if (plot.series[0]._yaxis.tickOptions.formatString) {
                    // using format string
                    seriesValue = PMA_sprintf(plot.series[0]._yaxis.tickOptions.formatString, seriesValue);
                }
                tooltipHtml += '<br /><span style="color:' + seriesColor + '">' +
                    seriesLabel + ': ' + seriesValue + '</span>';
            }
            tooltipHtml += '</span></div>';
            return tooltipHtml;
        };

        // set Tooltip for each series
        for (i in settings.series) {
            settings.series[i].highlighter = {
                show: true,
                tooltipContentEditor: tempTooltipContentEditor
            };
        }

        chartObj.chart = $.jqplot('gridchart' + runtime.chartAI, series, settings);
        // remove [0,0] after plotting
        for (i in chartObj.chart.series) {
            chartObj.chart.series[i].data.shift();
        }

        var $legend = $('<div />').css('padding', '0.5em');
        for (i in chartObj.chart.series) {
            $legend.append(
                $('<div />').append(
                    $('<div>').css({
                        width: '1em',
                        height: '1em',
                        background: chartObj.chart.seriesColors[i]
                    }).addClass('floatleft')
                ).append(
                    $('<div>').text(
                        chartObj.chart.series[i].label
                    ).addClass('floatleft')
                ).append(
                    $('<div class="clearfloat">')
                ).addClass('floatleft')
            );
        }
        $('#gridchart' + runtime.chartAI)
            .parent()
            .append($legend);

        if (initialize !== true) {
            runtime.charts['c' + runtime.chartAI] = chartObj;
            buildRequiredDataList();
        }

        // time span selection
        $('#gridchart' + runtime.chartAI).on('jqplotMouseDown', function (ev, gridpos, datapos, neighbor, plot) {
            drawTimeSpan = true;
            selectionTimeDiff.push(datapos.xaxis);
            if ($('#selection_box').length) {
                $('#selection_box').remove();
            }
            var selectionBox = $('<div id="selection_box" style="z-index:1000;height:205px;position:absolute;background-color:#87CEEB;opacity:0.4;filter:alpha(opacity=40);pointer-events:none;">');
            $(document.body).append(selectionBox);
            selectionStartX = ev.pageX;
            selectionStartY = ev.pageY;
            selectionBox
                .attr({ id: 'selection_box' })
                .css({
                    top: selectionStartY - gridpos.y,
                    left: selectionStartX
                })
                .fadeIn();
        });

        $('#gridchart' + runtime.chartAI).on('jqplotMouseUp', function (ev, gridpos, datapos, neighbor, plot) {
            if (! drawTimeSpan || editMode) {
                return;
            }

            selectionTimeDiff.push(datapos.xaxis);

            if (selectionTimeDiff[1] <= selectionTimeDiff[0]) {
                selectionTimeDiff = [];
                return;
            }
            // get date from timestamp
            var min = new Date(Math.ceil(selectionTimeDiff[0]));
            var max = new Date(Math.ceil(selectionTimeDiff[1]));
            PMA_getLogAnalyseDialog(min, max);
            selectionTimeDiff = [];
            drawTimeSpan = false;
        });

        $('#gridchart' + runtime.chartAI).on('jqplotMouseMove', function (ev, gridpos, datapos, neighbor, plot) {
            if (! drawTimeSpan || editMode) {
                return;
            }
            if (selectionStartX !== undefined) {
                $('#selection_box')
                    .css({
                        width: Math.ceil(ev.pageX - selectionStartX)
                    })
                    .fadeIn();
            }
        });

        $('#gridchart' + runtime.chartAI).on('jqplotMouseLeave', function (ev, gridpos, datapos, neighbor, plot) {
            drawTimeSpan = false;
        });

        $(document.body).mouseup(function () {
            if ($('#selection_box').length) {
                $('#selection_box').remove();
            }
        });

        // Edit, Print icon only in edit mode
        $('#chartGrid').find('div svg').find('*[zIndex=20], *[zIndex=21], *[zIndex=19]').toggle(editMode);

        runtime.chartAI++;
    }

    function PMA_getLogAnalyseDialog (min, max) {
        var $logAnalyseDialog = $('#logAnalyseDialog');
        var $dateStart = $logAnalyseDialog.find('input[name="dateStart"]');
        var $dateEnd = $logAnalyseDialog.find('input[name="dateEnd"]');
        $dateStart.prop('readonly', true);
        $dateEnd.prop('readonly', true);

        var dlgBtns = { };

        dlgBtns[PMA_messages.strFromSlowLog] = function () {
            loadLog('slow', min, max);
            $(this).dialog('close');
        };

        dlgBtns[PMA_messages.strFromGeneralLog] = function () {
            loadLog('general', min, max);
            $(this).dialog('close');
        };

        $logAnalyseDialog.dialog({
            width: 'auto',
            height: 'auto',
            buttons: dlgBtns
        });

        PMA_addDatepicker($dateStart, 'datetime', {
            showMillisec: false,
            showMicrosec: false,
            timeFormat: 'HH:mm:ss'
        });
        PMA_addDatepicker($dateEnd, 'datetime', {
            showMillisec: false,
            showMicrosec: false,
            timeFormat: 'HH:mm:ss'
        });
        $dateStart.datepicker('setDate', min);
        $dateEnd.datepicker('setDate', max);
    }

    function loadLog (type, min, max) {
        var dateStart = Date.parse($('#logAnalyseDialog').find('input[name="dateStart"]').datepicker('getDate')) || min;
        var dateEnd = Date.parse($('#logAnalyseDialog').find('input[name="dateEnd"]').datepicker('getDate')) || max;

        loadLogStatistics({
            src: type,
            start: dateStart,
            end: dateEnd,
            removeVariables: $('#removeVariables').prop('checked'),
            limitTypes: $('#limitTypes').prop('checked')
        });
    }

    /* Called in regular intervals, this function updates the values of each chart in the grid */
    function refreshChartGrid () {
        /* Send to server */
        runtime.refreshRequest = $.post('server_status_monitor.php' + PMA_commonParams.get('common_query'), {
            ajax_request: true,
            chart_data: 1,
            type: 'chartgrid',
            requiredData: JSON.stringify(runtime.dataList),
            server: PMA_commonParams.get('server')
        }, function (data) {
            var chartData;
            if (typeof data !== 'undefined' && data.success === true) {
                chartData = data.message;
            } else {
                return serverResponseError();
            }
            var value;
            var i = 0;
            var diff;
            var total;

            /* Update values in each graph */
            $.each(runtime.charts, function (orderKey, elem) {
                var key = elem.chartID;
                // If newly added chart, we have no data for it yet
                if (! chartData[key]) {
                    return;
                }
                // Draw all series
                total = 0;
                for (var j = 0; j < elem.nodes.length; j++) {
                    // Update x-axis
                    if (i === 0 && j === 0) {
                        if (oldChartData === null) {
                            diff = chartData.x - runtime.xmax;
                        } else {
                            diff = parseInt(chartData.x - oldChartData.x, 10);
                        }

                        runtime.xmin += diff;
                        runtime.xmax += diff;
                    }

                    // elem.chart.xAxis[0].setExtremes(runtime.xmin, runtime.xmax, false);
                    /* Calculate y value */

                    // If transform function given, use it
                    if (elem.nodes[j].transformFn) {
                        value = chartValueTransform(
                            elem.nodes[j].transformFn,
                            chartData[key][j],
                            // Check if first iteration (oldChartData==null), or if newly added chart oldChartData[key]==null
                            (
                                oldChartData === null ||
                                oldChartData[key] === null ||
                                oldChartData[key] === undefined ? null : oldChartData[key][j]
                            )
                        );

                    // Otherwise use original value and apply differential and divisor if given,
                    // in this case we have only one data point per series - located at chartData[key][j][0]
                    } else {
                        value = parseFloat(chartData[key][j][0].value);

                        if (elem.nodes[j].display === 'differential') {
                            if (oldChartData === null ||
                                oldChartData[key] === null ||
                                oldChartData[key] === undefined
                            ) {
                                continue;
                            }
                            value -= oldChartData[key][j][0].value;
                        }

                        if (elem.nodes[j].valueDivisor) {
                            value = value / elem.nodes[j].valueDivisor;
                        }
                    }

                    // Set y value, if defined
                    if (value !== undefined) {
                        elem.chart.series[j].data.push([chartData.x, value]);
                        if (value > elem.maxYLabel) {
                            elem.maxYLabel = value;
                        } else if (elem.maxYLabel === 0) {
                            elem.maxYLabel = 0.5;
                        }
                        // free old data point values and update maxYLabel
                        if (elem.chart.series[j].data.length > runtime.gridMaxPoints &&
                            elem.chart.series[j].data[0][0] < runtime.xmin
                        ) {
                            // check if the next freeable point is highest
                            if (elem.maxYLabel <= elem.chart.series[j].data[0][1]) {
                                elem.chart.series[j].data.splice(0, elem.chart.series[j].data.length - runtime.gridMaxPoints);
                                elem.maxYLabel = getMaxYLabel(elem.chart.series[j].data);
                            } else {
                                elem.chart.series[j].data.splice(0, elem.chart.series[j].data.length - runtime.gridMaxPoints);
                            }
                        }
                        if (elem.title === PMA_messages.strSystemMemory ||
                            elem.title === PMA_messages.strSystemSwap
                        ) {
                            total += value;
                        }
                    }
                }

                // update chart options
                // keep ticks number/positioning consistent while refreshrate changes
                var tickInterval = (runtime.xmax - runtime.xmin) / 5;
                elem.chart.axes.xaxis.ticks = [(runtime.xmax - tickInterval * 4),
                    (runtime.xmax - tickInterval * 3), (runtime.xmax - tickInterval * 2),
                    (runtime.xmax - tickInterval), runtime.xmax];

                if (elem.title !== PMA_messages.strSystemCPUUsage &&
                    elem.title !== PMA_messages.strQueryCacheEfficiency &&
                    elem.title !== PMA_messages.strSystemMemory &&
                    elem.title !== PMA_messages.strSystemSwap
                ) {
                    elem.chart.axes.yaxis.max = Math.ceil(elem.maxYLabel * 1.1);
                    elem.chart.axes.yaxis.tickInterval = Math.ceil(elem.maxYLabel * 1.1 / 5);
                } else if (elem.title === PMA_messages.strSystemMemory ||
                    elem.title === PMA_messages.strSystemSwap
                ) {
                    elem.chart.axes.yaxis.max = Math.ceil(total * 1.1 / 100) * 100;
                    elem.chart.axes.yaxis.tickInterval = Math.ceil(total * 1.1 / 5);
                }
                i++;

                if (runtime.redrawCharts) {
                    elem.chart.replot();
                }
            });

            oldChartData = chartData;

            runtime.refreshTimeout = setTimeout(refreshChartGrid, monitorSettings.gridRefresh);
        });
    }

    /* Function to get highest plotted point's y label, to scale the chart,
     * TODO: make jqplot's autoscale:true work here
     */
    function getMaxYLabel (dataValues) {
        var maxY = dataValues[0][1];
        $.each(dataValues, function (k, v) {
            maxY = (v[1] > maxY) ? v[1] : maxY;
        });
        return maxY;
    }

    /* Function that supplies special value transform functions for chart values */
    function chartValueTransform (name, cur, prev) {
        switch (name) {
        case 'cpu-linux':
            if (prev === null) {
                return undefined;
            }
            // cur and prev are datapoint arrays, but containing
            // only 1 element for cpu-linux
            cur = cur[0];
            prev = prev[0];

            var diff_total = cur.busy + cur.idle - (prev.busy + prev.idle);
            var diff_idle = cur.idle - prev.idle;
            return 100 * (diff_total - diff_idle) / diff_total;

        // Query cache efficiency (%)
        case 'qce':
            if (prev === null) {
                return undefined;
            }
            // cur[0].value is Qcache_hits, cur[1].value is Com_select
            var diffQHits = cur[0].value - prev[0].value;
            // No NaN please :-)
            if (cur[1].value - prev[1].value === 0) {
                return 0;
            }

            return diffQHits / (cur[1].value - prev[1].value + diffQHits) * 100;

        // Query cache usage (%)
        case 'qcu':
            if (cur[1].value === 0) {
                return 0;
            }
            // cur[0].value is Qcache_free_memory, cur[1].value is query_cache_size
            return 100 - cur[0].value / cur[1].value * 100;
        }
        return undefined;
    }

    /* Build list of nodes that need to be retrieved from server.
     * It creates something like a stripped down version of the runtime.charts object.
     */
    function buildRequiredDataList () {
        runtime.dataList = {};
        // Store an own id, because the property name is subject of reordering,
        // thus destroying our mapping with runtime.charts <=> runtime.dataList
        var chartID = 0;
        $.each(runtime.charts, function (key, chart) {
            runtime.dataList[chartID] = [];
            for (var i = 0, l = chart.nodes.length; i < l; i++) {
                runtime.dataList[chartID][i] = chart.nodes[i].dataPoints;
            }
            runtime.charts[key].chartID = chartID;
            chartID++;
        });
    }

    /* Loads the log table data, generates the table and handles the filters */
    function loadLogStatistics (opts) {
        var tableStr = '';
        var logRequest = null;

        if (! opts.removeVariables) {
            opts.removeVariables = false;
        }
        if (! opts.limitTypes) {
            opts.limitTypes = false;
        }

        $('#emptyDialog').dialog({ title: PMA_messages.strAnalysingLogsTitle });
        $('#emptyDialog').html(PMA_messages.strAnalysingLogs +
                                ' <img class="ajaxIcon" src="' + pmaThemeImage +
                                'ajax_clock_small.gif" alt="">');
        var dlgBtns = {};

        dlgBtns[PMA_messages.strCancelRequest] = function () {
            if (logRequest !== null) {
                logRequest.abort();
            }

            $(this).dialog('close');
        };

        $('#emptyDialog').dialog({
            width: 'auto',
            height: 'auto',
            buttons: dlgBtns
        });

        logRequest = $.post(
            'server_status_monitor.php' + PMA_commonParams.get('common_query'),
            {
                ajax_request: true,
                log_data: 1,
                type: opts.src,
                time_start: Math.round(opts.start / 1000),
                time_end: Math.round(opts.end / 1000),
                removeVariables: opts.removeVariables,
                limitTypes: opts.limitTypes
            },
            function (data) {
                var logData;
                var dlgBtns = {};
                if (typeof data !== 'undefined' && data.success === true) {
                    logData = data.message;
                } else {
                    return serverResponseError();
                }

                if (logData.rows.length === 0) {
                    $('#emptyDialog').dialog({ title: PMA_messages.strNoDataFoundTitle });
                    $('#emptyDialog').html('<p>' + PMA_messages.strNoDataFound + '</p>');

                    dlgBtns[PMA_messages.strClose] = function () {
                        $(this).dialog('close');
                    };

                    $('#emptyDialog').dialog('option', 'buttons', dlgBtns);
                    return;
                }

                runtime.logDataCols = buildLogTable(logData, opts.removeVariables);

                /* Show some stats in the dialog */
                $('#emptyDialog').dialog({ title: PMA_messages.strLoadingLogs });
                $('#emptyDialog').html('<p>' + PMA_messages.strLogDataLoaded + '</p>');
                $.each(logData.sum, function (key, value) {
                    key = key.charAt(0).toUpperCase() + key.slice(1).toLowerCase();
                    if (key === 'Total') {
                        key = '<b>' + key + '</b>';
                    }
                    $('#emptyDialog').append(key + ': ' + value + '<br/>');
                });

                /* Add filter options if more than a bunch of rows there to filter */
                if (logData.numRows > 12) {
                    $('#logTable').prepend(
                        '<fieldset id="logDataFilter">' +
                        '    <legend>' + PMA_messages.strFiltersForLogTable + '</legend>' +
                        '    <div class="formelement">' +
                        '        <label for="filterQueryText">' + PMA_messages.strFilterByWordRegexp + '</label>' +
                        '        <input name="filterQueryText" type="text" id="filterQueryText" style="vertical-align: baseline;" />' +
                        '    </div>' +
                        ((logData.numRows > 250) ? ' <div class="formelement"><button name="startFilterQueryText" id="startFilterQueryText">' + PMA_messages.strFilter + '</button></div>' : '') +
                        '    <div class="formelement">' +
                        '       <input type="checkbox" id="noWHEREData" name="noWHEREData" value="1" /> ' +
                        '       <label for="noWHEREData"> ' + PMA_messages.strIgnoreWhereAndGroup + '</label>' +
                        '   </div' +
                        '</fieldset>'
                    );

                    $('#noWHEREData').change(function () {
                        filterQueries(true);
                    });

                    if (logData.numRows > 250) {
                        $('#startFilterQueryText').click(filterQueries);
                    } else {
                        $('#filterQueryText').keyup(filterQueries);
                    }
                }

                dlgBtns[PMA_messages.strJumpToTable] = function () {
                    $(this).dialog('close');
                    $(document).scrollTop($('#logTable').offset().top);
                };

                $('#emptyDialog').dialog('option', 'buttons', dlgBtns);
            }
        );

        /* Handles the actions performed when the user uses any of the
         * log table filters which are the filter by name and grouping
         * with ignoring data in WHERE clauses
         *
         * @param boolean Should be true when the users enabled or disabled
         *                to group queries ignoring data in WHERE clauses
        */
        function filterQueries (varFilterChange) {
            var cell;
            var textFilter;
            var val = $('#filterQueryText').val();

            if (val.length === 0) {
                textFilter = null;
            } else {
                try {
                    textFilter = new RegExp(val, 'i');
                    $('#filterQueryText').removeClass('error');
                } catch (e) {
                    if (e instanceof SyntaxError) {
                        $('#filterQueryText').addClass('error');
                        textFilter = null;
                    }
                }
            }

            var rowSum = 0;
            var totalSum = 0;
            var i = 0;
            var q;
            var noVars = $('#noWHEREData').prop('checked');
            var equalsFilter = /([^=]+)=(\d+|((\'|"|).*?[^\\])\4((\s+)|$))/gi;
            var functionFilter = /([a-z0-9_]+)\(.+?\)/gi;
            var filteredQueries = {};
            var filteredQueriesLines = {};
            var hide = false;
            var rowData;
            var queryColumnName = runtime.logDataCols[runtime.logDataCols.length - 2];
            var sumColumnName = runtime.logDataCols[runtime.logDataCols.length - 1];
            var isSlowLog = opts.src === 'slow';
            var columnSums = {};

            // For the slow log we have to count many columns (query_time, lock_time, rows_examined, rows_sent, etc.)
            var countRow = function (query, row) {
                var cells = row.match(/<td>(.*?)<\/td>/gi);
                if (!columnSums[query]) {
                    columnSums[query] = [0, 0, 0, 0];
                }

                // lock_time and query_time and displayed in timespan format
                columnSums[query][0] += timeToSec(cells[2].replace(/(<td>|<\/td>)/gi, ''));
                columnSums[query][1] += timeToSec(cells[3].replace(/(<td>|<\/td>)/gi, ''));
                // rows_examind and rows_sent are just numbers
                columnSums[query][2] += parseInt(cells[4].replace(/(<td>|<\/td>)/gi, ''), 10);
                columnSums[query][3] += parseInt(cells[5].replace(/(<td>|<\/td>)/gi, ''), 10);
            };

            // We just assume the sql text is always in the second last column, and that the total count is right of it
            $('#logTable').find('table tbody tr td:nth-child(' + (runtime.logDataCols.length - 1) + ')').each(function () {
                var $t = $(this);
                // If query is a SELECT and user enabled or disabled to group
                // queries ignoring data in where statements, we
                // need to re-calculate the sums of each row
                if (varFilterChange && $t.html().match(/^SELECT/i)) {
                    if (noVars) {
                        // Group on => Sum up identical columns, and hide all but 1

                        q = $t.text().replace(equalsFilter, '$1=...$6').trim();
                        q = q.replace(functionFilter, ' $1(...)');

                        // Js does not specify a limit on property name length,
                        // so we can abuse it as index :-)
                        if (filteredQueries[q]) {
                            filteredQueries[q] += parseInt($t.next().text(), 10);
                            totalSum += parseInt($t.next().text(), 10);
                            hide = true;
                        } else {
                            filteredQueries[q] = parseInt($t.next().text(), 10);
                            filteredQueriesLines[q] = i;
                            $t.text(q);
                        }
                        if (isSlowLog) {
                            countRow(q, $t.parent().html());
                        }
                    } else {
                        // Group off: Restore original columns

                        rowData = $t.parent().data('query');
                        // Restore SQL text
                        $t.text(rowData[queryColumnName]);
                        // Restore total count
                        $t.next().text(rowData[sumColumnName]);
                        // Restore slow log columns
                        if (isSlowLog) {
                            $t.parent().children('td:nth-child(3)').text(rowData.query_time);
                            $t.parent().children('td:nth-child(4)').text(rowData.lock_time);
                            $t.parent().children('td:nth-child(5)').text(rowData.rows_sent);
                            $t.parent().children('td:nth-child(6)').text(rowData.rows_examined);
                        }
                    }
                }

                // If not required to be hidden, do we need
                // to hide because of a not matching text filter?
                if (! hide && (textFilter !== null && ! textFilter.exec($t.text()))) {
                    hide = true;
                }

                // Now display or hide this column
                if (hide) {
                    $t.parent().css('display', 'none');
                } else {
                    totalSum += parseInt($t.next().text(), 10);
                    rowSum++;
                    $t.parent().css('display', '');
                }

                hide = false;
                i++;
            });

            // We finished summarizing counts => Update count values of all grouped entries
            if (varFilterChange) {
                if (noVars) {
                    var numCol;
                    var row;
                    var $table = $('#logTable').find('table tbody');
                    $.each(filteredQueriesLines, function (key, value) {
                        if (filteredQueries[key] <= 1) {
                            return;
                        }

                        row =  $table.children('tr:nth-child(' + (value + 1) + ')');
                        numCol = row.children(':nth-child(' + (runtime.logDataCols.length) + ')');
                        numCol.text(filteredQueries[key]);

                        if (isSlowLog) {
                            row.children('td:nth-child(3)').text(secToTime(columnSums[key][0]));
                            row.children('td:nth-child(4)').text(secToTime(columnSums[key][1]));
                            row.children('td:nth-child(5)').text(columnSums[key][2]);
                            row.children('td:nth-child(6)').text(columnSums[key][3]);
                        }
                    });
                }

                $('#logTable').find('table').trigger('update');
                setTimeout(function () {
                    $('#logTable').find('table').trigger('sorton', [[[runtime.logDataCols.length - 1, 1]]]);
                }, 0);
            }

            // Display some stats at the bottom of the table
            $('#logTable').find('table tfoot tr')
                .html('<th colspan="' + (runtime.logDataCols.length - 1) + '">' +
                      PMA_messages.strSumRows + ' ' + rowSum + '<span class="floatright">' +
                      PMA_messages.strTotal + '</span></th><th class="right">' + totalSum + '</th>');
        }
    }

    /* Turns a timespan (12:12:12) into a number */
    function timeToSec (timeStr) {
        var time = timeStr.split(':');
        return (parseInt(time[0], 10) * 3600) + (parseInt(time[1], 10) * 60) + parseInt(time[2], 10);
    }

    /* Turns a number into a timespan (100 into 00:01:40) */
    function secToTime (timeInt) {
        var hours = Math.floor(timeInt / 3600);
        timeInt -= hours * 3600;
        var minutes = Math.floor(timeInt / 60);
        timeInt -= minutes * 60;

        if (hours < 10) {
            hours = '0' + hours;
        }
        if (minutes < 10) {
            minutes = '0' + minutes;
        }
        if (timeInt < 10) {
            timeInt = '0' + timeInt;
        }

        return hours + ':' + minutes + ':' + timeInt;
    }

    /* Constructs the log table out of the retrieved server data */
    function buildLogTable (data, groupInserts) {
        var rows = data.rows;
        var cols = [];
        var $table = $('<table class="sortable"></table>');
        var $tBody;
        var $tRow;
        var $tCell;

        $('#logTable').html($table);

        var tempPushKey = function (key, value) {
            cols.push(key);
        };

        var formatValue = function (name, value) {
            if (name === 'user_host') {
                return value.replace(/(\[.*?\])+/g, '');
            }
            return escapeHtml(value);
        };

        for (var i = 0, l = rows.length; i < l; i++) {
            if (i === 0) {
                $.each(rows[0], tempPushKey);
                $table.append('<thead>' +
                              '<tr><th class="nowrap">' + cols.join('</th><th class="nowrap">') + '</th></tr>' +
                              '</thead>'
                );

                $table.append($tBody = $('<tbody></tbody>'));
            }

            $tBody.append($tRow = $('<tr class="noclick"></tr>'));
            var cl = '';
            for (var j = 0, ll = cols.length; j < ll; j++) {
                // Assuming the query column is the second last
                if (j === cols.length - 2 && rows[i][cols[j]].match(/^SELECT/i)) {
                    $tRow.append($tCell = $('<td class="linkElem">' + formatValue(cols[j], rows[i][cols[j]]) + '</td>'));
                    $tCell.click(openQueryAnalyzer);
                } else {
                    $tRow.append('<td>' + formatValue(cols[j], rows[i][cols[j]]) + '</td>');
                }

                $tRow.data('query', rows[i]);
            }
        }

        $table.append('<tfoot>' +
                    '<tr><th colspan="' + (cols.length - 1) + '">' + PMA_messages.strSumRows +
                    ' ' + data.numRows + '<span class="floatright">' + PMA_messages.strTotal +
                    '</span></th><th class="right">' + data.sum.TOTAL + '</th></tr></tfoot>');

        // Append a tooltip to the count column, if there exist one
        if ($('#logTable').find('tr:first th:last').text().indexOf('#') > -1) {
            $('#logTable').find('tr:first th:last').append('&nbsp;' + PMA_getImage('b_help', '', { 'class': 'qroupedQueryInfoIcon' }));

            var tooltipContent = PMA_messages.strCountColumnExplanation;
            if (groupInserts) {
                tooltipContent += '<p>' + PMA_messages.strMoreCountColumnExplanation + '</p>';
            }

            PMA_tooltip(
                $('img.qroupedQueryInfoIcon'),
                'img',
                tooltipContent
            );
        }

        $('#logTable').find('table').tablesorter({
            sortList: [[cols.length - 1, 1]],
            widgets: ['fast-zebra']
        });

        $('#logTable').find('table thead th')
            .append('<div class="sorticon"></div>');

        return cols;
    }

    /* Opens the query analyzer dialog */
    function openQueryAnalyzer () {
        var rowData = $(this).parent().data('query');
        var query = rowData.argument || rowData.sql_text;

        if (codemirror_editor) {
            // TODO: somehow PMA_SQLPrettyPrint messes up the query, needs be fixed
            // query = PMA_SQLPrettyPrint(query);
            codemirror_editor.setValue(query);
            // Codemirror is bugged, it doesn't refresh properly sometimes.
            // Following lines seem to fix that
            setTimeout(function () {
                codemirror_editor.refresh();
            }, 50);
        } else {
            $('#sqlquery').val(query);
        }

        var profilingChart = null;
        var dlgBtns = {};

        dlgBtns[PMA_messages.strAnalyzeQuery] = function () {
            loadQueryAnalysis(rowData);
        };
        dlgBtns[PMA_messages.strClose] = function () {
            $(this).dialog('close');
        };

        $('#queryAnalyzerDialog').dialog({
            width: 'auto',
            height: 'auto',
            resizable: false,
            buttons: dlgBtns,
            close: function () {
                if (profilingChart !== null) {
                    profilingChart.destroy();
                }
                $('#queryAnalyzerDialog').find('div.placeHolder').html('');
                if (codemirror_editor) {
                    codemirror_editor.setValue('');
                } else {
                    $('#sqlquery').val('');
                }
            }
        });
    }

    /* Loads and displays the analyzed query data */
    function loadQueryAnalysis (rowData) {
        var db = rowData.db || '';

        $('#queryAnalyzerDialog').find('div.placeHolder').html(
            PMA_messages.strAnalyzing + ' <img class="ajaxIcon" src="' +
            pmaThemeImage + 'ajax_clock_small.gif" alt="">');

        $.post('server_status_monitor.php' + PMA_commonParams.get('common_query'), {
            ajax_request: true,
            query_analyzer: true,
            query: codemirror_editor ? codemirror_editor.getValue() : $('#sqlquery').val(),
            database: db,
            server: PMA_commonParams.get('server')
        }, function (data) {
            var i;
            var l;
            if (typeof data !== 'undefined' && data.success === true) {
                data = data.message;
            }
            if (data.error) {
                if (data.error.indexOf('1146') !== -1 || data.error.indexOf('1046') !== -1) {
                    data.error = PMA_messages.strServerLogError;
                }
                $('#queryAnalyzerDialog').find('div.placeHolder').html('<div class="error">' + data.error + '</div>');
                return;
            }
            var totalTime = 0;
            // Float sux, I'll use table :(
            $('#queryAnalyzerDialog').find('div.placeHolder')
                .html('<table width="100%" border="0"><tr><td class="explain"></td><td class="chart"></td></tr></table>');

            var explain = '<b>' + PMA_messages.strExplainOutput + '</b> ' + $('#explain_docu').html();
            if (data.explain.length > 1) {
                explain += ' (';
                for (i = 0; i < data.explain.length; i++) {
                    if (i > 0) {
                        explain += ', ';
                    }
                    explain += '<a href="#showExplain-' + i + '">' + i + '</a>';
                }
                explain += ')';
            }
            explain += '<p></p>';

            var tempExplain = function (key, value) {
                value = (value === null) ? 'null' : escapeHtml(value);

                if (key === 'type' && value.toLowerCase() === 'all') {
                    value = '<span class="attention">' + value + '</span>';
                }
                if (key === 'Extra') {
                    value = value.replace(/(using (temporary|filesort))/gi, '<span class="attention">$1</span>');
                }
                explain += key + ': ' + value + '<br />';
            };

            for (i = 0, l = data.explain.length; i < l; i++) {
                explain += '<div class="explain-' + i + '"' + (i > 0 ?  'style="display:none;"' : '') + '>';
                $.each(data.explain[i], tempExplain);
                explain += '</div>';
            }

            explain += '<p><b>' + PMA_messages.strAffectedRows + '</b> ' + data.affectedRows;

            $('#queryAnalyzerDialog').find('div.placeHolder td.explain').append(explain);

            $('#queryAnalyzerDialog').find('div.placeHolder a[href*="#showExplain"]').click(function () {
                var id = $(this).attr('href').split('-')[1];
                $(this).parent().find('div[class*="explain"]').hide();
                $(this).parent().find('div[class*="explain-' + id + '"]').show();
            });

            if (data.profiling) {
                var chartData = [];
                var numberTable = '<table class="queryNums"><thead><tr><th>' + PMA_messages.strStatus + '</th><th>' + PMA_messages.strTime + '</th></tr></thead><tbody>';
                var duration;
                var otherTime = 0;

                for (i = 0, l = data.profiling.length; i < l; i++) {
                    duration = parseFloat(data.profiling[i].duration);

                    totalTime += duration;

                    numberTable += '<tr><td>' + data.profiling[i].state + ' </td><td> ' + PMA_prettyProfilingNum(duration, 2) + '</td></tr>';
                }

                // Only put those values in the pie which are > 2%
                for (i = 0, l = data.profiling.length; i < l; i++) {
                    duration = parseFloat(data.profiling[i].duration);

                    if (duration / totalTime > 0.02) {
                        chartData.push([PMA_prettyProfilingNum(duration, 2) + ' ' + data.profiling[i].state, duration]);
                    } else {
                        otherTime += duration;
                    }
                }

                if (otherTime > 0) {
                    chartData.push([PMA_prettyProfilingNum(otherTime, 2) + ' ' + PMA_messages.strOther, otherTime]);
                }

                numberTable += '<tr><td><b>' + PMA_messages.strTotalTime + '</b></td><td>' + PMA_prettyProfilingNum(totalTime, 2) + '</td></tr>';
                numberTable += '</tbody></table>';

                $('#queryAnalyzerDialog').find('div.placeHolder td.chart').append(
                    '<b>' + PMA_messages.strProfilingResults + ' ' + $('#profiling_docu').html() + '</b> ' +
                    '(<a href="#showNums">' + PMA_messages.strTable + '</a>, <a href="#showChart">' + PMA_messages.strChart + '</a>)<br/>' +
                    numberTable + ' <div id="queryProfiling"></div>');

                $('#queryAnalyzerDialog').find('div.placeHolder a[href="#showNums"]').click(function () {
                    $('#queryAnalyzerDialog').find('#queryProfiling').hide();
                    $('#queryAnalyzerDialog').find('table.queryNums').show();
                    return false;
                });

                $('#queryAnalyzerDialog').find('div.placeHolder a[href="#showChart"]').click(function () {
                    $('#queryAnalyzerDialog').find('#queryProfiling').show();
                    $('#queryAnalyzerDialog').find('table.queryNums').hide();
                    return false;
                });

                profilingChart = PMA_createProfilingChart(
                    'queryProfiling',
                    chartData
                );

                // $('#queryProfiling').resizable();
            }
        });
    }

    /* Saves the monitor to localstorage */
    function saveMonitor () {
        var gridCopy = {};

        $.each(runtime.charts, function (key, elem) {
            gridCopy[key] = {};
            gridCopy[key].nodes = elem.nodes;
            gridCopy[key].settings = elem.settings;
            gridCopy[key].title = elem.title;
            gridCopy[key].series = elem.series;
            gridCopy[key].maxYLabel = elem.maxYLabel;
        });

        if (isStorageSupported('localStorage')) {
            window.localStorage.monitorCharts = JSON.stringify(gridCopy);
            window.localStorage.monitorSettings = JSON.stringify(monitorSettings);
            window.localStorage.monitorVersion = monitorProtocolVersion;
        }

        $('a[href="#clearMonitorConfig"]').show();
    }
});

// Run the monitor once loaded
AJAX.registerOnload('server_status_monitor.js', function () {
    $('a[href="#pauseCharts"]').trigger('click');
});

function serverResponseError () {
    var btns = {};
    btns[PMA_messages.strReloadPage] = function () {
        window.location.reload();
    };
    $('#emptyDialog').dialog({ title: PMA_messages.strRefreshFailed });
    $('#emptyDialog').html(
        PMA_getImage('s_attention') +
        PMA_messages.strInvalidResponseExplanation
    );
    $('#emptyDialog').dialog({ buttons: btns });
}

/* Destroys all monitor related resources */
function destroyGrid () {
    if (runtime.charts) {
        $.each(runtime.charts, function (key, value) {
            try {
                value.chart.destroy();
            } catch (err) {}
        });
    }

    try {
        runtime.refreshRequest.abort();
    } catch (err) {}
    try {
        clearTimeout(runtime.refreshTimeout);
    } catch (err) {}
    $('#chartGrid').html('');
    runtime.charts = null;
    runtime.chartAI = 0;
    monitorSettings = null; // TODO:this not global variable
}