data.src.js 68.5 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
/**
 * Data module
 *
 * (c) 2012-2018 Torstein Honsi
 *
 * License: www.highcharts.com/license
 */
'use strict';
import Highcharts from '../parts/Globals.js';
import '../parts/Utilities.js';
import '../parts/Chart.js';
import '../mixins/ajax.js';

// Utilities
var addEvent = Highcharts.addEvent,
    Chart = Highcharts.Chart,
    win = Highcharts.win,
    doc = win.document,
    each = Highcharts.each,
    objectEach = Highcharts.objectEach,
    pick = Highcharts.pick,
    inArray = Highcharts.inArray,
    isNumber = Highcharts.isNumber,
    merge = Highcharts.merge,
    splat = Highcharts.splat,
    fireEvent = Highcharts.fireEvent,
    some = Highcharts.some,
    SeriesBuilder;


/**
 * The Data module provides a simplified interface for adding data to
 * a chart from sources like CVS, HTML tables or grid views. See also
 * the [tutorial article on the Data module](https://www.highcharts.com/docs/working-
 * with-data/data-module).
 *
 * It requires the `modules/data.js` file to be loaded.
 *
 * Please note that the default way of adding data in Highcharts, without
 * the need of a module, is through the [series.data](#series.data)
 * option.
 *
 * @sample {highcharts} highcharts/demo/column-parsed/ HTML table
 * @sample {highcharts} highcharts/data/csv/ CSV
 * @since 4.0
 * @apioption data
 */

/**
 * A callback function to modify the CSV before parsing it. Return the modified
 * string.
 *
 * @type {Function}
 * @sample {highcharts} highcharts/demo/line-ajax/ Modify CSV before parse
 * @since 6.1
 * @apioption data.beforeParse
 */

/**
 * A two-dimensional array representing the input data on tabular form.
 * This input can be used when the data is already parsed, for example
 * from a grid view component. Each cell can be a string or number.
 * If not switchRowsAndColumns is set, the columns are interpreted as
 * series.
 *
 * @type {Array<Array<Mixed>>}
 * @see [data.rows](#data.rows)
 * @sample {highcharts} highcharts/data/columns/ Columns
 * @since 4.0
 * @apioption data.columns
 */

/**
 * The callback that is evaluated when the data is finished loading,
 * optionally from an external source, and parsed. The first argument
 * passed is a finished chart options object, containing the series.
 * These options can be extended with additional options and passed
 * directly to the chart constructor.
 *
 * @type {Function}
 * @see [data.parsed](#data.parsed)
 * @sample {highcharts} highcharts/data/complete/ Modify data on complete
 * @since 4.0
 * @apioption data.complete
 */

/**
 * A comma delimited string to be parsed. Related options are [startRow](
 * #data.startRow), [endRow](#data.endRow), [startColumn](#data.startColumn)
 * and [endColumn](#data.endColumn) to delimit what part of the table
 * is used. The [lineDelimiter](#data.lineDelimiter) and [itemDelimiter](
 * #data.itemDelimiter) options define the CSV delimiter formats.
 *
 * The built-in CSV parser doesn't support all flavours of CSV, so in
 * some cases it may be necessary to use an external CSV parser. See
 * [this example](https://jsfiddle.net/highcharts/u59176h4/) of parsing
 * CSV through the MIT licensed [Papa Parse](http://papaparse.com/)
 * library.
 *
 * @type {String}
 * @sample {highcharts} highcharts/data/csv/ Data from CSV
 * @since 4.0
 * @apioption data.csv
 */

/**
 * Which of the predefined date formats in Date.prototype.dateFormats
 * to use to parse date values. Defaults to a best guess based on what
 * format gives valid and ordered dates.
 *
 * Valid options include:
 *
 * *   `YYYY/mm/dd`
 * *   `dd/mm/YYYY`
 * *   `mm/dd/YYYY`
 * *   `dd/mm/YY`
 * *   `mm/dd/YY`
 *
 * @validvalue [undefined, "YYYY/mm/dd", "dd/mm/YYYY", "mm/dd/YYYY",
 *             "dd/mm/YYYY", "dd/mm/YY", "mm/dd/YY"]
 * @type {String}
 * @see [data.parseDate](#data.parseDate)
 * @sample {highcharts} highcharts/data/dateformat-auto/ Best guess date format
 * @since 4.0
 * @apioption data.dateFormat
 */

/**
 * The decimal point used for parsing numbers in the CSV.
 *
 * If both this and data.delimiter is set to false, the parser will
 * attempt to deduce the decimal point automatically.
 *
 * @type {String}
 * @sample {highcharts} highcharts/data/delimiters/ Comma as decimal point
 * @default .
 * @since 4.1.0
 * @apioption data.decimalPoint
 */

/**
 * In tabular input data, the last column (indexed by 0) to use. Defaults
 * to the last column containing data.
 *
 * @type {Number}
 * @sample {highcharts} highcharts/data/start-end/ Limited data
 * @since 4.0
 * @apioption data.endColumn
 */

/**
 * In tabular input data, the last row (indexed by 0) to use. Defaults
 * to the last row containing data.
 *
 * @type {Number}
 * @sample {highcharts} highcharts/data/start-end/ Limited data
 * @since 4.0.4
 * @apioption data.endRow
 */

/**
 * Whether to use the first row in the data set as series names.
 *
 * @type {Boolean}
 * @sample {highcharts} highcharts/data/start-end/ Don't get series names from the CSV
 * @sample {highstock} highcharts/data/start-end/ Don't get series names from the CSV
 * @default true
 * @since 4.1.0
 * @product highcharts highstock gantt
 * @apioption data.firstRowAsNames
 */

/**
 * The key for a Google Spreadsheet to load. See [general information
 * on GS](https://developers.google.com/gdata/samples/spreadsheet_sample).
 *
 * @type {String}
 * @sample {highcharts} highcharts/data/google-spreadsheet/
 *         Load a Google Spreadsheet
 * @since 4.0
 * @apioption data.googleSpreadsheetKey
 */

/**
 * The Google Spreadsheet worksheet to use in combination with
 * [googleSpreadsheetKey](#data.googleSpreadsheetKey). The available id's from
 * your sheet can be read from `https://spreadsheets.google.com/feeds/worksheets/{key}/public/basic`.
 *
 * @type {String}
 * @sample {highcharts} highcharts/data/google-spreadsheet/ Load a Google Spreadsheet
 * @since 4.0
 * @apioption data.googleSpreadsheetWorksheet
 */

/**
 * Item or cell delimiter for parsing CSV. Defaults to the tab character
 * `\t` if a tab character is found in the CSV string, if not it defaults
 * to `,`.
 *
 * If this is set to false or undefined, the parser will attempt to deduce
 * the delimiter automatically.
 *
 * @type {String}
 * @sample {highcharts} highcharts/data/delimiters/ Delimiters
 * @since 4.0
 * @apioption data.itemDelimiter
 */

/**
 * Line delimiter for parsing CSV.
 *
 * @type {String}
 * @sample {highcharts} highcharts/data/delimiters/ Delimiters
 * @default \n
 * @since 4.0
 * @apioption data.lineDelimiter
 */

/**
 * A callback function to parse string representations of dates into
 * JavaScript timestamps. Should return an integer timestamp on success.
 *
 * @type {Function}
 * @see [dateFormat](#data.dateFormat)
 * @since 4.0
 * @apioption data.parseDate
 */

/**
 * A callback function to access the parsed columns, the two-dimentional
 * input data array directly, before they are interpreted into series
 * data and categories. Return `false` to stop completion, or call
 * `this.complete()` to continue async.
 *
 * @type {Function}
 * @see [data.complete](#data.complete)
 * @sample {highcharts} highcharts/data/parsed/ Modify data after parse
 * @since 4.0
 * @apioption data.parsed
 */

/**
 * The same as the columns input option, but defining rows intead of
 * columns.
 *
 * @type {Array<Array<Mixed>>}
 * @see [data.columns](#data.columns)
 * @sample {highcharts} highcharts/data/rows/ Data in rows
 * @since 4.0
 * @apioption data.rows
 */

/**
 * An array containing object with Point property names along with what
 * column id the property should be taken from.
 *
 * @type {Array<Object>}
 * @sample {highcharts} highcharts/data/seriesmapping-label/ Label from data set
 * @since 4.0.4
 * @apioption data.seriesMapping
 */

/**
 * In tabular input data, the first column (indexed by 0) to use.
 *
 * @type {Number}
 * @sample {highcharts} highcharts/data/start-end/ Limited data
 * @default 0
 * @since 4.0
 * @apioption data.startColumn
 */

/**
 * In tabular input data, the first row (indexed by 0) to use.
 *
 * @type {Number}
 * @sample {highcharts} highcharts/data/start-end/ Limited data
 * @default 0
 * @since 4.0
 * @apioption data.startRow
 */

/**
 * Switch rows and columns of the input data, so that `this.columns`
 * effectively becomes the rows of the data set, and the rows are interpreted
 * as series.
 *
 * @type {Boolean}
 * @sample {highcharts} highcharts/data/switchrowsandcolumns/ Switch rows and columns
 * @default false
 * @since 4.0
 * @apioption data.switchRowsAndColumns
 */

/**
 * An HTML table or the id of such to be parsed as input data. Related
 * options are `startRow`, `endRow`, `startColumn` and `endColumn` to
 * delimit what part of the table is used.
 *
 * @type {String|HTMLElement}
 * @sample {highcharts} highcharts/demo/column-parsed/ Parsed table
 * @since 4.0
 * @apioption data.table
 */

/**
 * A URL to a remote CSV dataset.
 * Will be fetched when the chart is created using Ajax.
 *
 * @type {String}
 * @sample highcharts/data/livedata-columns
 *           Categorized bar chart with CSV and live polling
 * @sample highcharts/data/livedata-csv
 *         Time based line chart with CSV and live polling
 * @apioption data.csvURL
 */

/**
 * A URL to a remote JSON dataset, structured as a row array.
 * Will be fetched when the chart is created using Ajax.
 *
 * @type {String}
 * @sample highcharts/data/livedata-rows
 *         Rows with live polling
 * @apioption data.rowsURL
 */

/**
 * A URL to a remote JSON dataset, structured as a column array.
 * Will be fetched when the chart is created using Ajax.
 *
 * @type {String}
 * @sample highcharts/data/livedata-columns
 *         Columns with live polling
 * @apioption data.columnsURL
 */

/**
 * Sets the refresh rate for data polling when importing remote dataset by
 * setting [data.csvURL](data.csvURL), [data.rowsURL](data.rowsURL),
 * [data.columnsURL](data.columnsURL), or
 * [data.googleSpreadsheetKey](data.googleSpreadsheetKey).
 *
 * Note that polling must be enabled by setting
 * [data.enablePolling](data.enablePolling) to true.
 *
 * The value is the number of seconds between pollings.
 * It cannot be set to less than 1 second.
 *
 * @default 1
 * @type {Number}
 * @sample highcharts/demo/live-data
 *         Live data with user set refresh rate
 * @apioption data.dataRefreshRate
 */

/**
 * Enables automatic refetching of remote datasets every _n_ seconds (defined by
 * setting [data.dataRefreshRate](data.dataRefreshRate)).
 *
 * Only works when either [data.csvURL](data.csvURL),
 * [data.rowsURL](data.rowsURL), [data.columnsURL](data.columnsURL), or
 * [data.googleSpreadsheetKey](data.googleSpreadsheetKey).
 *
 * @sample highcharts/demo/live-data
 *         Live data
 * @sample highcharts/data/livedata-columns
 *           Categorized bar chart with CSV and live polling
 *
 * @type {Boolean}
 * @default false
 * @apioption data.enablePolling
 */

// The Data constructor
var Data = function (dataOptions, chartOptions, chart) {
    this.init(dataOptions, chartOptions, chart);
};

// Set the prototype properties
Highcharts.extend(Data.prototype, {

    /**
     * Initialize the Data object with the given options
     */
    init: function (options, chartOptions, chart) {

        var decimalPoint = options.decimalPoint,
            hasData;

        if (chartOptions) {
            this.chartOptions = chartOptions;
        }
        if (chart) {
            this.chart = chart;
        }

        if (decimalPoint !== '.' && decimalPoint !== ',') {
            decimalPoint = undefined;
        }

        this.options = options;
        this.columns = (
            options.columns ||
            this.rowsToColumns(options.rows) ||
            []
        );

        this.firstRowAsNames = pick(
            options.firstRowAsNames,
            this.firstRowAsNames,
            true
        );

        this.decimalRegex = (
            decimalPoint &&
            new RegExp('^(-?[0-9]+)' + decimalPoint + '([0-9]+)$') // eslint-disable-line security/detect-non-literal-regexp
        );

        // This is a two-dimensional array holding the raw, trimmed string
        // values with the same organisation as the columns array. It makes it
        // possible for example to revert from interpreted timestamps to
        // string-based categories.
        this.rawColumns = [];

        // No need to parse or interpret anything
        if (this.columns.length) {
            this.dataFound();
            hasData = true;
        }

        if (!hasData) {
            // Fetch live data
            hasData = this.fetchLiveData();
        }

        if (!hasData) {
            // Parse a CSV string if options.csv is given. The parseCSV function
            // returns a columns array, if it has no length, we have no data
            hasData = Boolean(this.parseCSV().length);
        }

        if (!hasData) {
            // Parse a HTML table if options.table is given
            hasData = Boolean(this.parseTable().length);
        }

        if (!hasData) {
            // Parse a Google Spreadsheet
            hasData = this.parseGoogleSpreadsheet();
        }

        if (!hasData && options.afterComplete) {
            options.afterComplete();
        }
    },

    /**
     * Get the column distribution. For example, a line series takes a single
     * column for Y values. A range series takes two columns for low and high
     * values respectively, and an OHLC series takes four columns.
     */
    getColumnDistribution: function () {
        var chartOptions = this.chartOptions,
            options = this.options,
            xColumns = [],
            getValueCount = function (type) {
                return (
                    Highcharts.seriesTypes[type || 'line'].prototype
                        .pointArrayMap ||
                    [0]
                ).length;
            },
            getPointArrayMap = function (type) {
                return Highcharts.seriesTypes[type || 'line']
                    .prototype.pointArrayMap;
            },
            globalType = (
                chartOptions &&
                chartOptions.chart &&
                chartOptions.chart.type
            ),
            individualCounts = [],
            seriesBuilders = [],
            seriesIndex = 0,

            // If no series mapping is defined, check if the series array is
            // defined with types.
            seriesMapping = (
                (options && options.seriesMapping) ||
                (
                    chartOptions &&
                    chartOptions.series &&
                    Highcharts.map(chartOptions.series, function () {
                        return { x: 0 };
                    })
                ) ||
                []
            ),
            i;

        each((chartOptions && chartOptions.series) || [], function (series) {
            individualCounts.push(getValueCount(series.type || globalType));
        });

        // Collect the x-column indexes from seriesMapping
        each(seriesMapping, function (mapping) {
            xColumns.push(mapping.x || 0);
        });

        // If there are no defined series with x-columns, use the first column
        // as x column
        if (xColumns.length === 0) {
            xColumns.push(0);
        }

        // Loop all seriesMappings and constructs SeriesBuilders from
        // the mapping options.
        each(seriesMapping, function (mapping) {
            var builder = new SeriesBuilder(),
                numberOfValueColumnsNeeded = individualCounts[seriesIndex] ||
                    getValueCount(globalType),
                seriesArr = (chartOptions && chartOptions.series) || [],
                series = seriesArr[seriesIndex] || {},
                pointArrayMap = getPointArrayMap(series.type || globalType) ||
                    ['y'];

            // Add an x reader from the x property or from an undefined column
            // if the property is not set. It will then be auto populated later.
            builder.addColumnReader(mapping.x, 'x');

            // Add all column mappings
            objectEach(mapping, function (val, name) {
                if (name !== 'x') {
                    builder.addColumnReader(val, name);
                }
            });

            // Add missing columns
            for (i = 0; i < numberOfValueColumnsNeeded; i++) {
                if (!builder.hasReader(pointArrayMap[i])) {
                    // Create and add a column reader for the next free column
                    // index
                    builder.addColumnReader(undefined, pointArrayMap[i]);
                }
            }

            seriesBuilders.push(builder);
            seriesIndex++;
        });

        var globalPointArrayMap = getPointArrayMap(globalType);
        if (globalPointArrayMap === undefined) {
            globalPointArrayMap = ['y'];
        }

        this.valueCount = {
            global: getValueCount(globalType),
            xColumns: xColumns,
            individual: individualCounts,
            seriesBuilders: seriesBuilders,
            globalPointArrayMap: globalPointArrayMap
        };
    },

    /**
     * When the data is parsed into columns, either by CSV, table, GS or direct
     * input, continue with other operations.
     */
    dataFound: function () {
        if (this.options.switchRowsAndColumns) {
            this.columns = this.rowsToColumns(this.columns);
        }

        // Interpret the info about series and columns
        this.getColumnDistribution();

        // Interpret the values into right types
        this.parseTypes();

        // Handle columns if a handleColumns callback is given
        if (this.parsed() !== false) {

            // Complete if a complete callback is given
            this.complete();
        }

    },

    /**
     * Parse a CSV input string
     */
    parseCSV: function (inOptions) {
        var self = this,
            options = inOptions || this.options,
            csv = options.csv,
            columns,
            startRow = (
                typeof options.startRow !== 'undefined' && options.startRow ?
                    options.startRow :
                    0
            ),
            endRow = options.endRow || Number.MAX_VALUE,
            startColumn = (
                typeof options.startColumn !== 'undefined' &&
                options.startColumn
            ) ? options.startColumn : 0,
            endColumn = options.endColumn || Number.MAX_VALUE,
            itemDelimiter,
            lines,
            rowIt = 0,
            // activeRowNo = 0,
            dataTypes = [],
            // We count potential delimiters in the prepass, and use the
            // result as the basis of half-intelligent guesses.
            potDelimiters = {
                ',': 0,
                ';': 0,
                '\t': 0
            };

        columns = this.columns = [];

        /*
            This implementation is quite verbose. It will be shortened once
            it's stable and passes all the test.

            It's also not written with speed in mind, instead everything is
            very seggregated, and there a several redundant loops.
            This is to make it easier to stabilize the code initially.

            We do a pre-pass on the first 4 rows to make some intelligent
            guesses on the set. Guessed delimiters are in this pass counted.

            Auto detecting delimiters
                - If we meet a quoted string, the next symbol afterwards
                  (that's not \s, \t) is the delimiter
                - If we meet a date, the next symbol afterwards is the delimiter

            Date formats
                - If we meet a column with date formats, check all of them to
                  see if one of the potential months crossing 12. If it does,
                  we now know the format

            It would make things easier to guess the delimiter before
            doing the actual parsing.

            General rules:
                - Quoting is allowed, e.g: "Col 1",123,321
                - Quoting is optional, e.g.: Col1,123,321
                - Doubble quoting is escaping, e.g. "Col ""Hello world""",123
                - Spaces are considered part of the data: Col1 ,123
                - New line is always the row delimiter
                - Potential column delimiters are , ; \t
                - First row may optionally contain headers
                - The last row may or may not have a row delimiter
                - Comments are optionally supported, in which case the comment
                  must start at the first column, and the rest of the line will
                  be ignored
        */

        // Parse a single row
        function parseRow(columnStr, rowNumber, noAdd, callbacks) {
            var i = 0,
                c = '',
                cl = '',
                cn = '',
                token = '',
                actualColumn = 0,
                column = 0;

            function read(j) {
                c = columnStr[j];
                cl = columnStr[j - 1];
                cn = columnStr[j + 1];
            }

            function pushType(type) {
                if (dataTypes.length < column + 1) {
                    dataTypes.push([type]);
                }
                if (dataTypes[column][dataTypes[column].length - 1] !== type) {
                    dataTypes[column].push(type);
                }
            }

            function push() {
                if (startColumn > actualColumn || actualColumn > endColumn) {
                    // Skip this column, but increment the column count (#7272)
                    ++actualColumn;
                    token = '';
                    return;
                }

                if (!isNaN(parseFloat(token)) && isFinite(token)) {
                    token = parseFloat(token);
                    pushType('number');
                } else if (!isNaN(Date.parse(token))) {
                    token = token.replace(/\//g, '-');
                    pushType('date');
                } else {
                    pushType('string');
                }


                if (columns.length < column + 1) {
                    columns.push([]);
                }

                if (!noAdd) {
                    // Don't push - if there's a varrying amount of columns
                    // for each row, pushing will skew everything down n slots
                    columns[column][rowNumber] = token;
                }

                token = '';
                ++column;
                ++actualColumn;
            }

            if (!columnStr.trim().length) {
                return;
            }

            if (columnStr.trim()[0] === '#') {
                return;
            }

            for (; i < columnStr.length; i++) {
                read(i);

                // Quoted string
                if (c === '#') {
                    // The rest of the row is a comment
                    push();
                    return;
                } else if (c === '"') {
                    read(++i);

                    while (i < columnStr.length) {
                        if (c === '"' && cl !== '"' && cn !== '"') {
                            break;
                        }

                        if (c !== '"' || (c === '"' && cl !== '"')) {
                            token += c;
                        }

                        read(++i);
                    }

                // Perform "plugin" handling
                } else if (callbacks && callbacks[c]) {
                    if (callbacks[c](c, token)) {
                        push();
                    }

                // Delimiter - push current token
                } else if (c === itemDelimiter) {
                    push();

                // Actual column data
                } else {
                    token += c;
                }
            }

            push();

        }

        // Attempt to guess the delimiter
        // We do a separate parse pass here because we need
        // to count potential delimiters softly without making any assumptions.
        function guessDelimiter(lines) {
            var points = 0,
                commas = 0,
                guessed = false;

            some(lines, function (columnStr, i) {
                var inStr = false,
                    c,
                    cn,
                    cl,
                    token = ''
                    ;


                // We should be able to detect dateformats within 13 rows
                if (i > 13) {
                    return true;
                }

                for (var j = 0; j < columnStr.length; j++) {
                    c = columnStr[j];
                    cn = columnStr[j + 1];
                    cl = columnStr[j - 1];

                    if (c === '#') {
                        // Skip the rest of the line - it's a comment
                        return;
                    } else if (c === '"') {
                        if (inStr) {
                            if (cl !== '"' && cn !== '"') {
                                while (cn === ' ' && j < columnStr.length) {
                                    cn = columnStr[++j];
                                }

                                // After parsing a string, the next non-blank
                                // should be a delimiter if the CSV is properly
                                // formed.

                                if (typeof potDelimiters[cn] !== 'undefined') {
                                    potDelimiters[cn]++;
                                }

                                inStr = false;
                            }
                        } else {
                            inStr = true;
                        }
                    } else if (typeof potDelimiters[c] !== 'undefined') {

                        token = token.trim();

                        if (!isNaN(Date.parse(token))) {
                            potDelimiters[c]++;
                        } else if (isNaN(token) || !isFinite(token)) {
                            potDelimiters[c]++;
                        }

                        token = '';

                    } else {
                        token += c;
                    }

                    if (c === ',') {
                        commas++;
                    }

                    if (c === '.') {
                        points++;
                    }
                }
            });

            // Count the potential delimiters.
            // This could be improved by checking if the number of delimiters
            // equals the number of columns - 1

            if (potDelimiters[';'] > potDelimiters[',']) {
                guessed = ';';
            } else if (potDelimiters[','] > potDelimiters[';']) {
                guessed = ',';
            } else {
                // No good guess could be made..
                guessed = ',';
            }

            // Try to deduce the decimal point if it's not explicitly set.
            // If both commas or points is > 0 there is likely an issue
            if (!options.decimalPoint) {
                if (points > commas) {
                    options.decimalPoint = '.';
                } else {
                    options.decimalPoint = ',';
                }

                // Apply a new decimal regex based on the presumed decimal sep.
                self.decimalRegex = new RegExp( // eslint-disable-line security/detect-non-literal-regexp
                    '^(-?[0-9]+)' +
                    options.decimalPoint +
                    '([0-9]+)$'
                );
            }

            return guessed;
        }

        /* Tries to guess the date format
         *    - Check if either month candidate exceeds 12
         *  - Check if year is missing (use current year)
         *  - Check if a shortened year format is used (e.g. 1/1/99)
         *  - If no guess can be made, the user must be prompted
         * data is the data to deduce a format based on
         */
        function deduceDateFormat(data, limit) {
            var format = 'YYYY/mm/dd',
                thing,
                guessedFormat,
                calculatedFormat,
                i = 0,
                madeDeduction = false,
                // candidates = {},
                stable = [],
                max = [],
                j;

            if (!limit || limit > data.length) {
                limit = data.length;
            }

            for (; i < limit; i++) {
                if (
                    typeof data[i] !== 'undefined' &&
                    data[i] && data[i].length
                ) {
                    thing = data[i]
                            .trim()
                            .replace(/\//g, ' ')
                            .replace(/\-/g, ' ')
                            .split(' ');

                    guessedFormat = [
                        '',
                        '',
                        ''
                    ];


                    for (j = 0; j < thing.length; j++) {
                        if (j < guessedFormat.length) {
                            thing[j] = parseInt(thing[j], 10);

                            if (thing[j]) {

                                max[j] = (!max[j] || max[j] < thing[j]) ?
                                    thing[j] :
                                    max[j];

                                if (typeof stable[j] !== 'undefined') {
                                    if (stable[j] !== thing[j]) {
                                        stable[j] = false;
                                    }
                                } else {
                                    stable[j] = thing[j];
                                }

                                if (thing[j] > 31) {
                                    if (thing[j] < 100) {
                                        guessedFormat[j] = 'YY';
                                    } else {
                                        guessedFormat[j] = 'YYYY';
                                    }
                                    // madeDeduction = true;
                                } else if (thing[j] > 12 && thing[j] <= 31) {
                                    guessedFormat[j] = 'dd';
                                    madeDeduction = true;
                                } else if (!guessedFormat[j].length) {
                                    guessedFormat[j] = 'mm';
                                }
                            }
                        }
                    }
                }
            }

            if (madeDeduction) {

                // This handles a few edge cases with hard to guess dates
                for (j = 0; j < stable.length; j++) {
                    if (stable[j] !== false) {
                        if (
                            max[j] > 12 &&
                            guessedFormat[j] !== 'YY' &&
                            guessedFormat[j] !== 'YYYY'
                        ) {
                            guessedFormat[j] = 'YY';
                        }
                    } else if (max[j] > 12 && guessedFormat[j] === 'mm') {
                        guessedFormat[j] = 'dd';
                    }
                }

                // If the middle one is dd, and the last one is dd,
                // the last should likely be year.
                if (guessedFormat.length === 3 &&
                    guessedFormat[1] === 'dd' &&
                    guessedFormat[2] === 'dd') {
                    guessedFormat[2] = 'YY';
                }

                calculatedFormat = guessedFormat.join('/');

                // If the caculated format is not valid, we need to present an
                // error.

                if (
                    !(options.dateFormats || self.dateFormats)[calculatedFormat]
                ) {
                    // This should emit an event instead
                    fireEvent('deduceDateFailed');
                    return format;
                }

                return calculatedFormat;
            }

            return format;
        }

        /* Figure out the best axis types for the data
         * - If the first column is a number, we're good
         * - If the first column is a date, set to date/time
         * - If the first column is a string, set to categories
         */
        function deduceAxisTypes() {

        }

        if (csv && options.beforeParse) {
            csv = options.beforeParse.call(this, csv);
        }

        if (csv) {

            lines = csv
                .replace(/\r\n/g, '\n') // Unix
                .replace(/\r/g, '\n') // Mac
                .split(options.lineDelimiter || '\n');

            if (!startRow || startRow < 0) {
                startRow = 0;
            }

            if (!endRow || endRow >= lines.length) {
                endRow = lines.length - 1;
            }

            if (options.itemDelimiter) {
                itemDelimiter = options.itemDelimiter;
            } else {
                itemDelimiter = null;
                itemDelimiter = guessDelimiter(lines);
            }

            var offset = 0;

            for (rowIt = startRow; rowIt <= endRow; rowIt++) {
                if (lines[rowIt][0] === '#') {
                    offset++;
                } else {
                    parseRow(lines[rowIt], rowIt - startRow - offset);
                }
            }

            // //Make sure that there's header columns for everything
            // each(columns, function (col) {

            // });

            deduceAxisTypes();

            if ((!options.columnTypes || options.columnTypes.length === 0) &&
                dataTypes.length &&
                dataTypes[0].length &&
                dataTypes[0][1] === 'date' &&
                !options.dateFormat) {
                options.dateFormat = deduceDateFormat(columns[0]);
            }


            // each(lines, function (line, rowNo) {
            //    var trimmed = self.trim(line),
            //        isComment = trimmed.indexOf('#') === 0,
            //        isBlank = trimmed === '',
            //        items;

            //    if (
            //        rowNo >= startRow &&
            //        rowNo <= endRow &&
            //        !isComment && !isBlank
            //    ) {
            //        items = line.split(itemDelimiter);
            //        each(items, function (item, colNo) {
            //            if (colNo >= startColumn && colNo <= endColumn) {
            //                if (!columns[colNo - startColumn]) {
            //                    columns[colNo - startColumn] = [];
            //                }

            //                columns[colNo - startColumn][activeRowNo] = item;
            //            }
            //        });
            //        activeRowNo += 1;
            //    }
            // });
            //

            this.dataFound();
        }

        return columns;
    },

    /**
     * Parse a HTML table
     */
    parseTable: function () {
        var options = this.options,
            table = options.table,
            columns = this.columns,
            startRow = options.startRow || 0,
            endRow = options.endRow || Number.MAX_VALUE,
            startColumn = options.startColumn || 0,
            endColumn = options.endColumn || Number.MAX_VALUE;

        if (table) {

            if (typeof table === 'string') {
                table = doc.getElementById(table);
            }

            each(table.getElementsByTagName('tr'), function (tr, rowNo) {
                if (rowNo >= startRow && rowNo <= endRow) {
                    each(tr.children, function (item, colNo) {
                        if (
                            (item.tagName === 'TD' || item.tagName === 'TH') &&
                            colNo >= startColumn &&
                            colNo <= endColumn
                        ) {
                            if (!columns[colNo - startColumn]) {
                                columns[colNo - startColumn] = [];
                            }

                            columns[colNo - startColumn][rowNo - startRow] =
                                item.innerHTML;
                        }
                    });
                }
            });

            this.dataFound(); // continue
        }
        return columns;
    },


    /**
     * Fetch or refetch live data
     */
    fetchLiveData: function () {
        var chart = this.chart,
            options = this.options,
            maxRetries = 3,
            currentRetries = 0,
            pollingEnabled = options.enablePolling,
            updateIntervalMs = (options.dataRefreshRate || 2) * 1000,
            originalOptions = merge(options);

        if (!options ||
            (!options.csvURL && !options.rowsURL && !options.columnsURL)
        ) {
            return false;
        }

        // Do not allow polling more than once a second
        if (updateIntervalMs < 1000) {
            updateIntervalMs = 1000;
        }

        delete options.csvURL;
        delete options.rowsURL;
        delete options.columnsURL;

        function performFetch(initialFetch) {

            // Helper function for doing the data fetch + polling
            function request(url, done, tp) {
                if (!url || url.indexOf('http') !== 0) {
                    if (url && options.error) {
                        options.error('Invalid URL');
                    }
                    return false;
                }

                if (initialFetch) {
                    clearTimeout(chart.liveDataTimeout);
                    chart.liveDataURL = url;
                }

                function poll() {
                    // Poll
                    if (pollingEnabled && chart.liveDataURL === url) {
                        // We need to stop doing this if the URL has changed
                        chart.liveDataTimeout =
                            setTimeout(performFetch, updateIntervalMs);
                    }
                }

                Highcharts.ajax({
                    url: url,
                    dataType: tp || 'json',
                    success: function (res) {
                        if (chart && chart.series) {
                            done(res);
                        }

                        poll();

                    },
                    error: function (xhr, text) {
                        if (++currentRetries < maxRetries) {
                            poll();
                        }

                        return options.error && options.error(text, xhr);
                    }
                });

                return true;
            }

            if (!request(originalOptions.csvURL, function (res) {
                chart.update({
                    data: {
                        csv: res
                    }
                });
            }, 'text')) {
                if (!request(originalOptions.rowsURL, function (res) {
                    chart.update({
                        data: {
                            rows: res
                        }
                    });
                })) {
                    request(originalOptions.columnsURL, function (res) {
                        chart.update({
                            data: {
                                columns: res
                            }
                        });
                    });
                }
            }
        }

        performFetch(true);

        return (options &&
            (options.csvURL || options.rowsURL || options.columnsURL)
        );
    },


    /**
     * Parse a Google spreadsheet.
     */
    parseGoogleSpreadsheet: function () {
        var data = this,
            options = this.options,
            googleSpreadsheetKey = options.googleSpreadsheetKey,
            chart = this.chart,
            // use sheet 1 as the default rather than od6
            // as the latter sometimes cause issues (it looks like it can
            // be renamed in some cases, ref. a fogbugz case).
            worksheet = options.googleSpreadsheetWorksheet || 1,
            startRow = options.startRow || 0,
            endRow = options.endRow || Number.MAX_VALUE,
            startColumn = options.startColumn || 0,
            endColumn = options.endColumn || Number.MAX_VALUE,
            refreshRate = (options.dataRefreshRate || 2) * 1000;

        if (refreshRate < 4000) {
            refreshRate = 4000;
        }

        /*
         * Fetch the actual spreadsheet using XMLHttpRequest
         */
        function fetchSheet(fn) {
            var url = [
                'https://spreadsheets.google.com/feeds/cells',
                googleSpreadsheetKey,
                worksheet,
                'public/values?alt=json'
            ].join('/');

            Highcharts.ajax({
                url: url,
                dataType: 'json',
                success: function (json) {
                    fn(json);

                    if (options.enablePolling) {
                        setTimeout(function () {
                            fetchSheet(fn);
                        }, options.dataRefreshRate);
                    }
                },
                error: function (xhr, text) {
                    return options.error && options.error(text, xhr);
                }
            });
        }

        if (googleSpreadsheetKey) {

            delete options.googleSpreadsheetKey;

            fetchSheet(function (json) {
                // Prepare the data from the spreadsheat
                var columns = [],
                    cells = json.feed.entry,
                    cell,
                    cellCount = (cells || []).length,
                    colCount = 0,
                    rowCount = 0,
                    val,
                    gr,
                    gc,
                    cellInner,
                    i;

                if (!cells || cells.length === 0) {
                    return false;
                }

                // First, find the total number of columns and rows that
                // are actually filled with data
                for (i = 0; i < cellCount; i++) {
                    cell = cells[i];
                    colCount = Math.max(colCount, cell.gs$cell.col);
                    rowCount = Math.max(rowCount, cell.gs$cell.row);
                }

                // Set up arrays containing the column data
                for (i = 0; i < colCount; i++) {
                    if (i >= startColumn && i <= endColumn) {
                        // Create new columns with the length of either
                        // end-start or rowCount
                        columns[i - startColumn] = [];
                    }
                }

                // Loop over the cells and assign the value to the right
                // place in the column arrays
                for (i = 0; i < cellCount; i++) {
                    cell = cells[i];
                    gr = cell.gs$cell.row - 1; // rows start at 1
                    gc = cell.gs$cell.col - 1; // columns start at 1

                    // If both row and col falls inside start and end set the
                    // transposed cell value in the newly created columns
                    if (gc >= startColumn && gc <= endColumn &&
                        gr >= startRow && gr <= endRow) {

                        cellInner = cell.gs$cell || cell.content;

                        val = null;

                        if (cellInner.numericValue) {
                            if (cellInner.$t.indexOf('/') >= 0 ||
                                cellInner.$t.indexOf('-') >= 0) {
                                // This is a date - for future reference.
                                val = cellInner.$t;
                            } else if (cellInner.$t.indexOf('%') > 0) {
                                // Percentage
                                val = parseFloat(cellInner.numericValue) * 100;
                            } else {
                                val = parseFloat(cellInner.numericValue);
                            }
                        } else if (cellInner.$t && cellInner.$t.length) {
                            val = cellInner.$t;
                        }

                        columns[gc - startColumn][gr - startRow] = val;
                    }
                }

                // Insert null for empty spreadsheet cells (#5298)
                each(columns, function (column) {
                    for (i = 0; i < column.length; i++) {
                        if (column[i] === undefined) {
                            column[i] = null;
                        }
                    }
                });

                if (chart && chart.series) {
                    chart.update({
                        data: {
                            columns: columns
                        }
                    });
                } else { // #8245
                    data.columns = columns;
                    data.dataFound();
                }
            });
        }

        // This is an intermediate fetch, so always return false.
        return false;
    },

    /**
     * Trim a string from whitespace
     */
    trim: function (str, inside) {
        if (typeof str === 'string') {
            str = str.replace(/^\s+|\s+$/g, '');

            // Clear white space insdie the string, like thousands separators
            if (inside && /^[0-9\s]+$/.test(str)) {
                str = str.replace(/\s/g, '');
            }

            if (this.decimalRegex) {
                str = str.replace(this.decimalRegex, '$1.$2');
            }
        }
        return str;
    },

    /**
     * Parse numeric cells in to number types and date types in to true dates.
     */
    parseTypes: function () {
        var columns = this.columns,
            col = columns.length;

        while (col--) {
            this.parseColumn(columns[col], col);
        }

    },

    /**
     * Parse a single column. Set properties like .isDatetime and .isNumeric.
     */
    parseColumn: function (column, col) {
        var rawColumns = this.rawColumns,
            columns = this.columns,
            row = column.length,
            val,
            floatVal,
            trimVal,
            trimInsideVal,
            firstRowAsNames = this.firstRowAsNames,
            isXColumn = inArray(col, this.valueCount.xColumns) !== -1,
            dateVal,
            backup = [],
            diff,
            chartOptions = this.chartOptions,
            descending,
            columnTypes = this.options.columnTypes || [],
            columnType = columnTypes[col],
            forceCategory = isXColumn && ((
                chartOptions &&
                chartOptions.xAxis &&
                splat(chartOptions.xAxis)[0].type === 'category'
            ) || columnType === 'string');

        if (!rawColumns[col]) {
            rawColumns[col] = [];
        }
        while (row--) {
            val = backup[row] || column[row];

            trimVal = this.trim(val);
            trimInsideVal = this.trim(val, true);
            floatVal = parseFloat(trimInsideVal);

            // Set it the first time
            if (rawColumns[col][row] === undefined) {
                rawColumns[col][row] = trimVal;
            }

            // Disable number or date parsing by setting the X axis type to
            // category
            if (forceCategory || (row === 0 && firstRowAsNames)) {
                column[row] = '' + trimVal;

            } else if (+trimInsideVal === floatVal) { // is numeric

                column[row] = floatVal;

                // If the number is greater than milliseconds in a year, assume
                // datetime
                if (
                    floatVal > 365 * 24 * 3600 * 1000 &&
                    columnType !== 'float'
                ) {
                    column.isDatetime = true;
                } else {
                    column.isNumeric = true;
                }

                if (column[row + 1] !== undefined) {
                    descending = floatVal > column[row + 1];
                }

            // String, continue to determine if it is a date string or really a
            // string
            } else {
                if (trimVal && trimVal.length) {
                    dateVal = this.parseDate(val);
                }

                // Only allow parsing of dates if this column is an x-column
                if (isXColumn && isNumber(dateVal) && columnType !== 'float') {
                    backup[row] = val;
                    column[row] = dateVal;
                    column.isDatetime = true;

                    // Check if the dates are uniformly descending or ascending.
                    // If they are not, chances are that they are a different
                    // time format, so check for alternative.
                    if (column[row + 1] !== undefined) {
                        diff = dateVal > column[row + 1];
                        if (diff !== descending && descending !== undefined) {
                            if (this.alternativeFormat) {
                                this.dateFormat = this.alternativeFormat;
                                row = column.length;
                                this.alternativeFormat =
                                    this.dateFormats[this.dateFormat]
                                        .alternative;
                            } else {
                                column.unsorted = true;
                            }
                        }
                        descending = diff;
                    }

                } else { // string
                    column[row] = trimVal === '' ? null : trimVal;
                    if (row !== 0 && (column.isDatetime || column.isNumeric)) {
                        column.mixed = true;
                    }
                }
            }
        }

        // If strings are intermixed with numbers or dates in a parsed column,
        // it is an indication that parsing went wrong or the data was not
        // intended to display as numbers or dates and parsing is too
        // aggressive. Fall back to categories. Demonstrated in the
        // highcharts/demo/column-drilldown sample.
        if (isXColumn && column.mixed) {
            columns[col] = rawColumns[col];
        }

        // If the 0 column is date or number and descending, reverse all
        // columns.
        if (isXColumn && descending && this.options.sort) {
            for (col = 0; col < columns.length; col++) {
                columns[col].reverse();
                if (firstRowAsNames) {
                    columns[col].unshift(columns[col].pop());
                }
            }
        }
    },

    /**
     * A collection of available date formats, extendable from the outside to
     * support custom date formats.
     */
    dateFormats: {
        'YYYY/mm/dd': {
            regex: /^([0-9]{4})[\-\/\.]([0-9]{1,2})[\-\/\.]([0-9]{1,2})$/,
            parser: function (match) {
                return Date.UTC(+match[1], match[2] - 1, +match[3]);
            }
        },
        'dd/mm/YYYY': {
            regex: /^([0-9]{1,2})[\-\/\.]([0-9]{1,2})[\-\/\.]([0-9]{4})$/,
            parser: function (match) {
                return Date.UTC(+match[3], match[2] - 1, +match[1]);
            },
            alternative: 'mm/dd/YYYY' // different format with the same regex
        },
        'mm/dd/YYYY': {
            regex: /^([0-9]{1,2})[\-\/\.]([0-9]{1,2})[\-\/\.]([0-9]{4})$/,
            parser: function (match) {
                return Date.UTC(+match[3], match[1] - 1, +match[2]);
            }
        },
        'dd/mm/YY': {
            regex: /^([0-9]{1,2})[\-\/\.]([0-9]{1,2})[\-\/\.]([0-9]{2})$/,
            parser: function (match) {
                var year = +match[3],
                    d = new Date()
                ;

                if (year > (d.getFullYear() - 2000)) {
                    year += 1900;
                } else {
                    year += 2000;
                }

                return Date.UTC(year, match[2] - 1, +match[1]);
            },
            alternative: 'mm/dd/YY' // different format with the same regex
        },
        'mm/dd/YY': {
            regex: /^([0-9]{1,2})[\-\/\.]([0-9]{1,2})[\-\/\.]([0-9]{2})$/,
            parser: function (match) {
                return Date.UTC(+match[3] + 2000, match[1] - 1, +match[2]);
            }
        }
    },

    /**
     * Parse a date and return it as a number. Overridable through
     * `options.parseDate`.
     */
    parseDate: function (val) {
        var parseDate = this.options.parseDate,
            ret,
            key,
            format,
            dateFormat = this.options.dateFormat || this.dateFormat,
            match;

        if (parseDate) {
            ret = parseDate(val);

        } else if (typeof val === 'string') {
            // Auto-detect the date format the first time
            if (!dateFormat) {
                for (key in this.dateFormats) {
                    format = this.dateFormats[key];
                    match = val.match(format.regex);
                    if (match) {
                        this.dateFormat = dateFormat = key;
                        this.alternativeFormat = format.alternative;
                        ret = format.parser(match);
                        break;
                    }
                }
            // Next time, use the one previously found
            } else {
                format = this.dateFormats[dateFormat];


                if (!format) {
                    // The selected format is invalid
                    format = this.dateFormats['YYYY/mm/dd'];
                }

                match = val.match(format.regex);
                if (match) {
                    ret = format.parser(match);
                }

            }
            // Fall back to Date.parse
            if (!match) {
                match = Date.parse(val);
                // External tools like Date.js and MooTools extend Date object
                // and returns a date.
                if (
                    typeof match === 'object' &&
                    match !== null &&
                    match.getTime
                ) {
                    ret = match.getTime() - match.getTimezoneOffset() * 60000;

                // Timestamp
                } else if (isNumber(match)) {
                    ret = match - (new Date(match)).getTimezoneOffset() * 60000;
                }
            }
        }
        return ret;
    },

    /**
     * Reorganize rows into columns
     */
    rowsToColumns: function (rows) {
        var row,
            rowsLength,
            col,
            colsLength,
            columns;

        if (rows) {
            columns = [];
            rowsLength = rows.length;
            for (row = 0; row < rowsLength; row++) {
                colsLength = rows[row].length;
                for (col = 0; col < colsLength; col++) {
                    if (!columns[col]) {
                        columns[col] = [];
                    }
                    columns[col][row] = rows[row][col];
                }
            }
        }
        return columns;
    },

    /**
     * A hook for working directly on the parsed columns
     */
    parsed: function () {
        if (this.options.parsed) {
            return this.options.parsed.call(this, this.columns);
        }
    },

    getFreeIndexes: function (numberOfColumns, seriesBuilders) {
        var s,
            i,
            freeIndexes = [],
            freeIndexValues = [],
            referencedIndexes;

        // Add all columns as free
        for (i = 0; i < numberOfColumns; i = i + 1) {
            freeIndexes.push(true);
        }

        // Loop all defined builders and remove their referenced columns
        for (s = 0; s < seriesBuilders.length; s = s + 1) {
            referencedIndexes = seriesBuilders[s].getReferencedColumnIndexes();

            for (i = 0; i < referencedIndexes.length; i = i + 1) {
                freeIndexes[referencedIndexes[i]] = false;
            }
        }

        // Collect the values for the free indexes
        for (i = 0; i < freeIndexes.length; i = i + 1) {
            if (freeIndexes[i]) {
                freeIndexValues.push(i);
            }
        }

        return freeIndexValues;
    },

    /**
     * If a complete callback function is provided in the options, interpret the
     * columns into a Highcharts options object.
     */
    complete: function () {

        var columns = this.columns,
            xColumns = [],
            type,
            options = this.options,
            series,
            data,
            i,
            j,
            r,
            seriesIndex,
            chartOptions,
            allSeriesBuilders = [],
            builder,
            freeIndexes,
            typeCol,
            index;

        xColumns.length = columns.length;
        if (options.complete || options.afterComplete) {

            // Get the names and shift the top row
            if (this.firstRowAsNames) {
                for (i = 0; i < columns.length; i++) {
                    columns[i].name = columns[i].shift();
                }
            }

            // Use the next columns for series
            series = [];
            freeIndexes = this.getFreeIndexes(
                columns.length,
                this.valueCount.seriesBuilders
            );

            // Populate defined series
            for (
                seriesIndex = 0;
                seriesIndex < this.valueCount.seriesBuilders.length;
                seriesIndex++
            ) {
                builder = this.valueCount.seriesBuilders[seriesIndex];

                // If the builder can be populated with remaining columns, then
                // add it to allBuilders
                if (builder.populateColumns(freeIndexes)) {
                    allSeriesBuilders.push(builder);
                }
            }

            // Populate dynamic series
            while (freeIndexes.length > 0) {
                builder = new SeriesBuilder();
                builder.addColumnReader(0, 'x');

                // Mark index as used (not free)
                index = inArray(0, freeIndexes);
                if (index !== -1) {
                    freeIndexes.splice(index, 1);
                }

                for (i = 0; i < this.valueCount.global; i++) {
                    // Create and add a column reader for the next free column
                    // index
                    builder.addColumnReader(
                        undefined,
                        this.valueCount.globalPointArrayMap[i]
                    );
                }

                // If the builder can be populated with remaining columns, then
                // add it to allBuilders
                if (builder.populateColumns(freeIndexes)) {
                    allSeriesBuilders.push(builder);
                }
            }

            // Get the data-type from the first series x column
            if (
                allSeriesBuilders.length > 0 &&
                allSeriesBuilders[0].readers.length > 0
            ) {
                typeCol = columns[allSeriesBuilders[0].readers[0].columnIndex];
                if (typeCol !== undefined) {
                    if (typeCol.isDatetime) {
                        type = 'datetime';
                    } else if (!typeCol.isNumeric) {
                        type = 'category';
                    }
                }
            }
            // Axis type is category, then the "x" column should be called
            // "name"
            if (type === 'category') {
                for (
                    seriesIndex = 0;
                    seriesIndex < allSeriesBuilders.length;
                    seriesIndex++
                ) {
                    builder = allSeriesBuilders[seriesIndex];
                    for (r = 0; r < builder.readers.length; r++) {
                        if (builder.readers[r].configName === 'x') {
                            builder.readers[r].configName = 'name';
                        }
                    }
                }
            }

            // Read data for all builders
            for (
                seriesIndex = 0;
                seriesIndex < allSeriesBuilders.length;
                seriesIndex++
            ) {
                builder = allSeriesBuilders[seriesIndex];

                // Iterate down the cells of each column and add data to the
                // series
                data = [];
                for (j = 0; j < columns[0].length; j++) {
                    data[j] = builder.read(columns, j);
                }

                // Add the series
                series[seriesIndex] = {
                    data: data
                };
                if (builder.name) {
                    series[seriesIndex].name = builder.name;
                }
                if (type === 'category') {
                    series[seriesIndex].turboThreshold = 0;
                }
            }



            // Do the callback
            chartOptions = {
                series: series
            };
            if (type) {
                chartOptions.xAxis = {
                    type: type
                };
                if (type === 'category') {
                    chartOptions.xAxis.uniqueNames = false;
                }
            }

            if (options.complete) {
                options.complete(chartOptions);
            }

            // The afterComplete hook is used internally to avoid conflict with
            // the externally available complete option.
            if (options.afterComplete) {
                options.afterComplete(chartOptions);
            }
        }

    },

    update: function (options, redraw) {
        var chart = this.chart;
        if (options) {
            // Set the complete handler
            options.afterComplete = function (dataOptions) {
                // Avoid setting axis options unless the type changes. Running
                // Axis.update will cause the whole structure to be destroyed
                // and rebuilt, and animation is lost.
                if (
                    dataOptions.xAxis &&
                    chart.xAxis[0] &&
                    dataOptions.xAxis.type === chart.xAxis[0].options.type
                ) {
                    delete dataOptions.xAxis;
                }

                chart.update(dataOptions, redraw, true);
            };
            // Apply it
            merge(true, this.options, options);
            this.init(this.options);
        }
    }
});

// Register the Data prototype and data function on Highcharts
Highcharts.Data = Data;
Highcharts.data = function (options, chartOptions) {
    return new Data(options, chartOptions);
};

// Extend Chart.init so that the Chart constructor accepts a new configuration
// option group, data.
addEvent(
    Chart,
    'init',
    function (e) {
        var chart = this,
            userOptions = e.args[0],
            callback = e.args[1];

        if (userOptions && userOptions.data && !chart.hasDataDef) {
            chart.hasDataDef = true;
            chart.data = new Data(Highcharts.extend(userOptions.data, {

                afterComplete: function (dataOptions) {
                    var i, series;

                    // Merge series configs
                    if (userOptions.hasOwnProperty('series')) {
                        if (typeof userOptions.series === 'object') {
                            i = Math.max(
                                userOptions.series.length,
                                dataOptions && dataOptions.series ?
                                    dataOptions.series.length :
                                    0
                            );
                            while (i--) {
                                series = userOptions.series[i] || {};
                                userOptions.series[i] = merge(
                                    series,
                                    dataOptions && dataOptions.series ?
                                        dataOptions.series[i] :
                                        {}
                                );
                            }
                        } else { // Allow merging in dataOptions.series (#2856)
                            delete userOptions.series;
                        }
                    }

                    // Do the merge
                    userOptions = merge(dataOptions, userOptions);

                    // Run chart.init again
                    chart.init(userOptions, callback);
                }
            }), userOptions, chart);

            e.preventDefault();
        }
    }
);

/**
 * Creates a new SeriesBuilder. A SeriesBuilder consists of a number
 * of ColumnReaders that reads columns and give them a name.
 * Ex: A series builder can be constructed to read column 3 as 'x' and
 * column 7 and 8 as 'y1' and 'y2'.
 * The output would then be points/rows of the form {x: 11, y1: 22, y2: 33}
 *
 * The name of the builder is taken from the second column. In the above
 * example it would be the column with index 7.
 * @constructor
 */
SeriesBuilder = function () {
    this.readers = [];
    this.pointIsArray = true;
};

/**
 * Populates readers with column indexes. A reader can be added without
 * a specific index and for those readers the index is taken sequentially
 * from the free columns (this is handled by the ColumnCursor instance).
 * @returns {boolean}
 */
SeriesBuilder.prototype.populateColumns = function (freeIndexes) {
    var builder = this,
        enoughColumns = true;

    // Loop each reader and give it an index if its missing.
    // The freeIndexes.shift() will return undefined if there
    // are no more columns.
    each(builder.readers, function (reader) {
        if (reader.columnIndex === undefined) {
            reader.columnIndex = freeIndexes.shift();
        }
    });

    // Now, all readers should have columns mapped. If not
    // then return false to signal that this series should
    // not be added.
    each(builder.readers, function (reader) {
        if (reader.columnIndex === undefined) {
            enoughColumns = false;
        }
    });

    return enoughColumns;
};

/**
 * Reads a row from the dataset and returns a point or array depending
 * on the names of the readers.
 * @param columns
 * @param rowIndex
 * @returns {Array | Object}
 */
SeriesBuilder.prototype.read = function (columns, rowIndex) {
    var builder = this,
        pointIsArray = builder.pointIsArray,
        point = pointIsArray ? [] : {},
        columnIndexes;

    // Loop each reader and ask it to read its value.
    // Then, build an array or point based on the readers names.
    each(builder.readers, function (reader) {
        var value = columns[reader.columnIndex][rowIndex];
        if (pointIsArray) {
            point.push(value);
        } else {
            if (reader.configName.indexOf('.') > 0) {
                // Handle nested property names
                Highcharts.Point.prototype.setNestedProperty(
                    point, value, reader.configName
                );
            } else {
                point[reader.configName] = value;
            }
        }
    });

    // The name comes from the first column (excluding the x column)
    if (this.name === undefined && builder.readers.length >= 2) {
        columnIndexes = builder.getReferencedColumnIndexes();
        if (columnIndexes.length >= 2) {
            // remove the first one (x col)
            columnIndexes.shift();

            // Sort the remaining
            columnIndexes.sort(function (a, b) {
                return a - b;
            });

            // Now use the lowest index as name column
            this.name = columns[columnIndexes.shift()].name;
        }
    }

    return point;
};

/**
 * Creates and adds ColumnReader from the given columnIndex and configName.
 * ColumnIndex can be undefined and in that case the reader will be given
 * an index when columns are populated.
 * @param columnIndex {Number | undefined}
 * @param configName
 */
SeriesBuilder.prototype.addColumnReader = function (columnIndex, configName) {
    this.readers.push({
        columnIndex: columnIndex,
        configName: configName
    });

    if (
        !(configName === 'x' || configName === 'y' || configName === undefined)
    ) {
        this.pointIsArray = false;
    }
};

/**
 * Returns an array of column indexes that the builder will use when
 * reading data.
 * @returns {Array}
 */
SeriesBuilder.prototype.getReferencedColumnIndexes = function () {
    var i,
        referencedColumnIndexes = [],
        columnReader;

    for (i = 0; i < this.readers.length; i = i + 1) {
        columnReader = this.readers[i];
        if (columnReader.columnIndex !== undefined) {
            referencedColumnIndexes.push(columnReader.columnIndex);
        }
    }

    return referencedColumnIndexes;
};

/**
 * Returns true if the builder has a reader for the given configName.
 * @param configName
 * @returns {boolean}
 */
SeriesBuilder.prototype.hasReader = function (configName) {
    var i, columnReader;
    for (i = 0; i < this.readers.length; i = i + 1) {
        columnReader = this.readers[i];
        if (columnReader.configName === configName) {
            return true;
        }
    }
    // Else return undefined
};