Code coverage report for api/import/Import.js

Statements: 56.1% (625 / 1114)      Branches: 51.44% (322 / 626)      Functions: 62.4% (78 / 125)      Lines: 56.1% (625 / 1114)      Ignored: none     

All files » api/import/ » Import.js
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 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630  1 1 1 1 1 1 1   1 1 1 1 1   1 1 1   1 1 1 1         1     1 1           1                                             1 3   3 10 2   8 5 5     3                                 1 33 31   33 33 33 33 33                       33 33     1                                                                                             2     2             1             1 1   1   11 11                   1 1 1     1                       11     11     11       11 11 11   11           11 11 11   11 11   11               11           12   12     12 12       12 12 12   12 12 12   12       12 12 12 12                                                   12 12   11 11     1 1     12   12             12 12                       12 12     12 12 12                   12                           6     6 1 1       1     5 1 1       1     4 4     4 4 3         4   4 4 4 4 2   4           4   4     4 4   4 1 1 1 1       1 6     6 6 6   6             4       4 4 207 101   106     4 27 27   27 27 27             27   27 27                 4           4 4 27           4       4 178   178 3 3   175 175 175 175 1761   175 175 175 24     24 151         151     151   175       175 175 1593 1593 1593 152 152     1441     1441 1718 1718       1441   1441       175 170           170 170 170 170     5     4   4 4 4                                                                                                                                                                                                                                                                                                                                                                                                                                             4                     12     12 12 12     12 12 1     12 12 12       12 11     12 12     12 12     12   12 12 12         12       12 12 12             12           35 8 6 5   1   2 2     35     35                               31 31 31   31   31 29   2                                                                                                                                                               6     2                     317 33         284     39     39 3 3   36 36 36 36           955 33 33   922 922     37     37 2 2   35 35   35 35 35   35   35   35   35                     36 36 10           36 36     2     2                                                       34 1                               1670     1   1669     18     18           52     8           15     8     8 181 1612         1612 1612       1612 1329   1612 1329 1329 26 26   1303 1303   126 126                     1612       8                               3     3 3             3 3   3       3 171               171             3 3 3 3     3             3   3 3                                           174 174 174 174 174 10                       174   174       174   174 1610     174   174   174 1610 14 14 14 14   14     1610     174   174 1610 1596 1596   1596   1596 1596     174           2 2   2 2 2 2 2 2   2 1   1       1   2           1 1 1 1   1             1 1   1     1 1 5                     5 5   5     5 5 23                     23 23   23     23 23 3   23 23 155                       155 155   155 78   77 77 57 236 236   20 20 20   77 2 7 7   75 1 1   77 77 264                     264   264 264 263 1 1     264     264   264 705 705     705 705 705   705 2161     2161 2161     2161 669     669   1492 80       80   1412         705       705 705 705 705     705 705 669 669 669 669 669     705 705 705 705             1 7       1 1 1 705 705 4935   705     1           1     1 1 1                                                                                                                                                                                                                                                                                                                                                                                                   1     1 1 1           1 1 1 1   1     1 1 1 1             1   5 1 1 1 1   4   4 3 3 3 3     1 1             1 1 1 1   1 4 4 4           1   1     1 1 1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             1       1 1 1     1 1         1           1 1 1                                                 1 3     3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3         1 1 1     1   1 1 1 3   3 27 27 19     8       3   2   1     1       1 1   1                                                   1 1                                                                                                                                     2       2 2       2   2 2 2   2 2 4 4 4 4   4 4                           2     2   2 2 4 4                       2                   2     2 2 2 1     1 1   1 1 1 1                                                         2               7 7     7                                                                                         7 1 1 1                                                   6 5 5   5 1 4 2   2 2 2 2 2       7 7   7 7 56     56 13       7 7 7                   1  
/* globals window, escape, $, FileReader, FormData, unescape, Blob */
var FieldDBImage = require("./../image/Image").Image;
var AudioVideo = require("./../audio_video/AudioVideo").AudioVideo;
var AudioVideos = require("./../audio_video/AudioVideos").AudioVideos;
var Collection = require("./../Collection").Collection;
var CORS = require("./../CORS").CORS;
var Corpus = require("./../corpus/Corpus").Corpus;
var Image = require("./../image/Image").Image;
// var DataList = require("./../data_list/DataList").DataList;
var Participant = require("./../user/Participant").Participant;
var Datum = require("./../datum/Datum").Datum;
var DatumField = require("./../datum/DatumField").DatumField;
var DatumFields = require("./../datum/DatumFields").DatumFields;
var FieldDBObject = require("./../FieldDBObject").FieldDBObject;
// var FileReader = {};
var Session = require("./../datum/Session").Session;
var TextGrid = require("textgrid").TextGrid;
var Q = require("q");
 
var ATOB;
var X2JS;
try {
  if (!window.atob) {
    console.log("ATOB is not defined, loading from npm");
  }
  ATOB = window.atob;
} catch (e) {
  ATOB = require("atob");
}
 
Eif (typeof window === "undefined") {
  X2JS = require("x2js");
} else {
  X2JS = window.X2JS;
}
 
//http://stackoverflow.com/questions/4998908/convert-data-uri-to-file-then-append-to-formdata
var dataURItoBlob = function(dataURI) {
  // convert base64/URLEncoded data component to raw binary data held in a string
  var byteString;
  if (dataURI.split(",")[0].indexOf("base64") >= 0) {
    byteString = ATOB(dataURI.split(",")[1]);
  } else {
    byteString = unescape(dataURI.split(",")[1]);
  }
 
  // separate out the mime component
  var mimeString = dataURI.split(",")[0].split(":")[1].split(";")[0];
 
  // write the bytes of the string to a typed array
  var ia = new Uint8Array(byteString.length);
  for (var i = 0; i < byteString.length; i++) {
    ia[i] = byteString.charCodeAt(i);
  }
 
  return new Blob([ia], {
    type: mimeString
  });
};
 
var getUnique = function(arrayObj) {
  var u = {},
    a = [];
  for (var i = 0, l = arrayObj.length; i < l; ++i) {
    if (u.hasOwnProperty(arrayObj[i])) {
      continue;
    }
    if (arrayObj[i]) {
      a.push(arrayObj[i]);
      u[arrayObj[i]] = 1;
    }
  }
  return a;
};
 
/**
 * @class The import class helps import csv, xml and raw text data into a corpus, or create a new corpus.
 *
 * @property {FileList} files These are the file(s) that were dragged in.
 * @property {String} dbname This is the corpusid wherej the data should be imported
 * @property {DatumFields} fields The fields array contains titles of the data columns.
 * @property {DataList} datalist The datalist imported, to hold the data before it is saved.
 * @property {Event} event The drag/drop event.
 *
 * @description The initialize serves to bind import to all drag and drop events.
 *
 * @extends FieldDBObject
 * @tutorial tests/CorpusTest.js
 */
var Import = function Import(options) {
  if (!this._fieldDBtype) {
    this._fieldDBtype = "Import";
  }
  this.debug(" new import ", options);
  FieldDBObject.apply(this, arguments);
  options = options || {};
  var sessionOptions = options.session || {};
  sessionOptions.datalist = options.datalist || {
    title: {
      default: "Imported Data"
    },
    docs: {
      id: "tempdatalist",
      collection: [],
      primaryKey: "tempId"
    },
    // confidential: self.corpus.confidential,
    // debugMode: true
  };
  this.session = sessionOptions;
  this.session.goal = "Goal from file import";
};
 
Import.prototype = Object.create(FieldDBObject.prototype, /** @lends Import.prototype */ {
  constructor: {
    value: Import
  },
 
  fillWithDefaults: {
    value: function() {
      if (!this.datumFields) {
        this.datumFields = this.corpus.datumFields.clone();
      }
    }
  },
 
  defaults: {
    get: function() {
      return {
        status: "",
        showImportFirstStep: true,
        showImportSecondStep: false,
        showImportThirdStep: false,
        progress: {
          total: 0,
          completed: 0
        },
        datalist: {},
        session: {},
        dbname: "",
        files: [],
        asFieldMatrix: [],
        asCSV: []
      };
    },
    set: function() {}
  },
 
  INTERNAL_MODELS: {
    value: {
      progress: {},
      // datalist: DataList,
      datumFields: DatumFields,
      session: Session,
      corpus: Corpus
    }
  },
 
  showImportSecondStep: {
    get: function() {
      Iif (this.dontShowSecondStep) {
        return false;
      }
      return this.asCSV && this.asCSV.length > 0;
    },
    set: function() {}
  },
 
  showImportThirdStep: {
    get: function() {
      return this.datalist && this.datalist.docs && this.datalist.docs.length > 0;
    },
    set: function() {}
  },
 
  addFileUris: {
    value: function(options) {
      var deferred = Q.defer();
      var self = this;
 
      var promises = options.fileList.map(function(file) {
        // var id = file.replace("imported_corpora/", "");
        self.debug("adding file ", file);
        return self.addFileUri({
          // id: id,
          uri: file,
          readOptions: options.readOptions,
          preprocessOptions: options.preprocessOptions,
          importOptions: options.importOptions,
          dbname: options.dbname
        });
      });
 
      Q.allSettled(promises).then(function(results) {
        self.debug("done with promises " + results.length);
        deferred.resolve(options);
      });
 
      return deferred.promise;
    }
  },
 
  addFileUrl: {
    value: function() {
      this.warn("addFileUrl is deprecated, use addFileUri");
    }
  },
 
  addFileUri: {
    value: function(options) {
      var deferred = Q.defer(),
        self = this;
 
      Iif (!options) {
        throw new Error("Options must be specified {}");
      }
      Iif (!options.uri) {
        throw new Error("Uri must be specified in the options in order to import it" + JSON.stringify(options));
      }
 
      Q.nextTick(function() {
        self.debug("addFileUri", options);
        self.readUri(options)
          .then(function() {
            return self.preprocess.apply(self, arguments);
          })
          // .then(function() {
          //   return self.import.apply(self, arguments);
          // })
          .then(function(result) {
            self.debug("Preprocess is finished");
            self.debug("result.datum.length: " + result.datum.length);
            self.datalist.add(result.datum);
 
            result.fileName = result.fileName || options.uri.replace(new RegExp(".*" + options.dbname + "/"), "");
            self.files.add(result);
 
            deferred.resolve(result);
          })
          .fail(function(reason) {
            console.error(reason.stack);
            deferred.reject(reason);
          });
      });
 
      return deferred.promise;
    }
  },
 
  readUri: {
    value: function(options) {
      this.debug("readUri", options);
 
      var deferred = Q.defer(),
        self = this;
 
      Q.nextTick(function() {
        Iif (!options) {
          throw new Error("Options must be specified {}");
        }
 
        self.debug("readUri");
        var pipeline = function(optionsWithADatum) {
          self.debug("pipeline", optionsWithADatum.uri);
 
          Eif (optionsWithADatum.readOptions) {
            try {
              return optionsWithADatum.readOptions
                .readFileFunction(optionsWithADatum, function(err, data) {
                  Iif (err) {
                    self.debug("read file", err);
                    deferred.reject(err);
                  } else {
                    self.debug("rawText", data.length);
                    self.debug("done rawText");
                    optionsWithADatum.rawText = data;
                    deferred.resolve(optionsWithADatum);
                  }
                });
            } catch (err) {
              deferred.reject(err);
            }
          }
 
          self.warn("TODO reading url in browser");
          CORS.makeCORSRequest({
            type: "GET",
            dataType: "json",
            uri: optionsWithADatum.uri
          }).then(function(data) {
            self.debug(data);
            optionsWithADatum.rawText = data;
            deferred.resolve(optionsWithADatum);
          }, function(reason) {
            self.debug(reason);
            deferred.reject(reason);
          }).fail(function(error) {
            console.error(error.stack, self);
            deferred.reject(error);
          });
        };
 
        var whenFound;
        if (self.corpus.url && self.corpus.url.indexOf(".git") > -1) {
          // Dont try a fetch on a .git url
          whenFound = Q.fcall(function () {
            return [];
          });
        } else {
          self.debug("find " + options.uri);
          whenFound = self.corpus.find(options.uri);
        }
 
        whenFound
          .then(function(similarData) {
            Iif (similarData && similarData._id) {
              self.debug("similarData", similarData._id, similarData._rev);
              options.datum = self.corpus.newDatum(similarData);
              options.datum.session = options.datum.session || self.session;
              return pipeline(options);
            }
 
            self.debug("similarData", similarData.length);
            Iif (Array.isArray(similarData) && similarData.length === 1) {
              options.datum = self.corpus.newDatum(similarData[0]);
              options.datum.session = options.datum.session || self.session;
 
              // try {
              //   pipeline(options);
              // } catch (e) {
              //   console.log('caught an err', e);
              // }
              return pipeline(options);
            }
 
            self.debug("readUri newDatumAsync");
            self.corpus.newDatumAsync()
              .then(function(datum) {
                // self.debug("datum", datum);
                options.datum = datum;
                options.datum.session = options.datum.session || self.session;
                pipeline(options);
              });
          })
          .fail(function(reason) {
            self.debug("corpus.find fail", reason);
 
            deferred.reject(reason);
          });
 
      });
      return deferred.promise;
 
    }
  },
 
  convertTableIntoDataList: {
    value: function(options) {
      this.warn("convertTableIntoDataList is deprecated, use convertMatrixIntoDataList");
      return this.convertMatrixIntoDataList(options);
    }
  },
 
  convertMatrixIntoDataList: {
    value: function() {
      var self = this,
        deferred = Q.defer();
 
      if (this.importType === "participants" && (!this.corpus || !this.corpus.confidential || !this.corpus.confidential.secretkey)) {
        Q.nextTick(function() {
          deferred.reject({
            userFriendlyErrors: ["Cannot create encrypted participants at this time", "Corpus's encrypter isn't available right now, maybe the app is still loading?"]
          });
        });
        return deferred.promise;
      }
 
      if (!this.asFieldMatrix || this.asFieldMatrix.length === 0) {
        Q.nextTick(function() {
          deferred.reject({
            userFriendlyErrors: ["There was nothing to import. Are you sure you ran step 1?"]
          });
        });
        return deferred.promise;
      }
 
      Q.nextTick(function() {
        deferred.resolve(self.datalist);
      });
 
      try {
        if (!self.progress) {
          self.progress = {
            total: 0,
            completed: 0
          };
        }
        self.progress.total = self.asFieldMatrix.length;
 
        var filename = " typing/copy paste into text area";
        var descript = "This is the data list which results from the import of the text typed/pasted in the import text area.";
        try {
          filename = self.files.map(function(file) {
            return file.name;
          }).join(", ");
          descript = "This is the data list which results from the import of these file(s). " + self.fileDetails;
        } catch (e) {
          self.todo("turn the copy pasted text into a File to upload");
        }
        // self.render();
 
        self.session.consultants = [];
        /* put metadata in the session goals */
        Iif (self.metadataLines) {
          self.session.goal = self.metadataLines.join("\n") + "\n" + self.session.goal;
        }
        self.render("session");
        self.datalist.description = descript;
 
        if (!self.extractedHeaderObjects) {
          self.warn("There was no extracted header.");
          Eif (self.asFieldMatrix && self.asFieldMatrix.length > 0 && self.asFieldMatrix[0].concat) {
            self.warn("Using the first row as the extracted header.");
            self.extractedHeaderObjects = self.asFieldMatrix[0].concat([]);
            // self.extractedHeaderObjects = JSON.parse(JSON.stringify(self.asFieldMatrix[0]));
            // self.extractedHeaderObjects = self.asFieldMatrix.shift();
 
            self.extractedHeaderObjects = self.extractedHeaderObjects.map(function(object) {
              Iif (object === "" || object === undefined || object === null) {
                return;
              }
              Eif (object && !object.id && object.value !== undefined && object.value !== null) {
                object.id = object.value;
                object.value = "";
              }
              return object;
            });
          } else {
            return deferred.promise;
          }
        }
 
        var fieldLabelFromExtractedHeader,
          correspondingDatumField,
          columnIndex;
 
        try {
          var getColumnHeadings = function(obj) {
            if (obj && obj.id && obj.id !== "columnplaceholder") {
              return "";
            }
            return obj.id;
          };
          // this.debugMode = true;
          for (columnIndex = 0; columnIndex < self.extractedHeaderObjects.length; columnIndex++) {
            fieldLabelFromExtractedHeader = self.extractedHeaderObjects[columnIndex].id || self.extractedHeaderObjects[columnIndex];
            correspondingDatumField = self.normalizeImportFieldWithExistingCorpusFields(fieldLabelFromExtractedHeader);
 
            Eif (correspondingDatumField && correspondingDatumField.id) {
              var fields = self.extractedHeaderObjects.map(getColumnHeadings);
              Iif (fields.indexOf(correspondingDatumField.id) >= 0) {
                self.bug("You seem to have some column labels '" + correspondingDatumField.id + "' that are duplicated" +
                  " (the same label on two columns). This will result in a strange " +
                  "import where only the second of the two will be used in the import. " +
                  "Is this really what you want?.");
              }
            }
            self.debug(columnIndex + " correspondingDatumField", correspondingDatumField);
 
            self.debug("setting extractedHeaderObjects was once problematic", self.extractedHeaderObjects[columnIndex], correspondingDatumField);
            self.extractedHeaderObjects[columnIndex] = correspondingDatumField;
          }
          // this.debugMode = false;
        } catch (e) {
          this.warn(e);
          this.warn(e.stack);
          throw new Error(" problem in extractedHeaderObjects ");
        }
 
        Iif (self.debugMode) {
          // self.debug("  these are the extracted header cells ", self.extractedHeaderObjects.map(function(field) {
          //   return field.id;
          // }));
        }
 
        self.debug("JSON.stringify(self.extractedHeaderObjects, null, 2)");
        self.extractedHeaderObjects.map(function(headerField) {
          self.debug("headerField", headerField);
        });
 
        /*
         * Cycle through all the rows in table and create a datum with the matching fields.
         */
        var testForEmptyness,
          cellIndex,
          cell;
 
        self.asFieldMatrix.map(function(row) {
          self.progress.completed = self.progress.completed + 1;
 
          if (!row || row.length < 1) {
            self.debug("Skipping empty row");
            return;
          }
          self.debug("Working on row ", row);
          var docToSave;
          self.debug("Cloning fields ", self.extractedHeaderObjects.length);
          var fields = self.extractedHeaderObjects.map(function(headerField) {
            return headerField.toJSON();
          });
          self.debug("Cloned fields ", fields.length);
          self.debug("fields[0] equals extractedHeaderObjects[0]", fields[0] === self.extractedHeaderObjects[0]);
          if (self.importType === "participants") {
            docToSave = new Participant({
              fields: fields
            });
            self.debug("Creating a participant.", row);
          } else Iif (self.importType === "audioVideo") {
            docToSave = new AudioVideo();
            docToSave.description = self.rawText; //TODO look into the textgrid import
            self.debug("Creating a audioVideo.", docToSave.description);
          } else {
            docToSave = new Datum({
              fields: fields
            });
            self.debug("Creating a datum.", row);
          }
          docToSave.confidential = self.corpus.confidential;
          // docToSave.decryptedMode = true;
 
          // return;
          testForEmptyness = "";
          for (cellIndex = 0; cellIndex < row.length; cellIndex++) {
            cell = row[cellIndex];
            self.debug("working on cell ", cell);
            if (!cell || cellIndex > self.extractedHeaderObjects.length || self.extractedHeaderObjects[cellIndex].id === "columnplaceholder") {
              self.debug("Skipping column " + cellIndex + " :", cell);
              continue;
            }
 
            Iif (self.importType === "audioVideo") {
              self.debug("this is an audioVideo but we arent doing anything with the self.importFields");
            } else {
              for (var attrib in cell) {
                Eif (cell.hasOwnProperty(attrib)) {
                  docToSave.fields._collection[cellIndex][attrib] = cell[attrib];
                }
              }
              /* user can edit the matrix and it will show in the data list */
              row[cellIndex] = docToSave.fields._collection[cellIndex];
            }
            testForEmptyness += cell.value;
          }
 
          //if the table row has more than 2 non-white space characters, enter it as data
          if (testForEmptyness.replace(/[ \t\n]/g, "").length >= 2) {
            Iif (self.debugMode) {
              // self.debug("new doc", docToSave.fields.map(function(field) {
              //   return field.value
              // }));
            }
            // docToSave.tempId = docToSave.id = FieldDBObject.uuidGenerator();
            Eif (docToSave) {
              docToSave.tempId = FieldDBObject.uuidGenerator();
              docToSave.dbname = self.corpus.dbname;
              self.datalist.add(docToSave);
            }
          } else {
            self.debug("Didn't add row with only blank cells:" + testForEmptyness + ": ");
          }
        });
        self.debug("Finished building the data list");
 
        self.showImportThirdStep = true;
        self.render();
        self.progress.total = self.progress.completed = self.datalist.length;
 
        //   /*
        //    * after building an array of datumobjects, turn them into backbone objects
        //    */
        //   var eachFileDetails = function(fileDetails) {
        //     var details = JSON.parse(JSON.stringify(fileDetails));
        //     delete details.textgrid;
        //     audioFileDescriptionsKeyedByFilename[fileDetails.fileBaseName + ".mp3"] = details;
        //   };
 
        //   var forEachRow = function(index, value) {
        //     if (index === "" || index === undefined) {
        //       //do nothing
        //     }
        //     /* TODO removing old tag code for */
        //     //          else if (index === "datumTags") {
        //     //            var tags = value.split(" ");
        //     //            for(g in tags){
        //     //              var t = new DatumTag({
        //     //                "tag" : tags[g]
        //     //              });
        //     //              d.get("datumTags").add(t);
        //     //            }
        //     //          }
        //     /* turn the CheckedWithConsultant and ToBeCheckedWithConsultantinto columns into a status, with that string as the person */
        //     else if (index.toLowerCase().indexOf("checkedwithconsultant") > -1) {
        //       var consultants = [];
        //       if (value.indexOf(",") > -1) {
        //         consultants = value.split(",");
        //       } else if (value.indexOf(";") > -1) {
        //         consultants = value.split(";");
        //       } else {
        //         consultants = value.split(" ");
        //       }
        //       var validationStati = [];
        //       for (var g in consultants) {
        //         var consultantusername = consultants[g].toLowerCase();
        //         self.consultants.push(consultantusername);
        //         if (!consultantusername) {
        //           continue;
        //         }
        //         var validationType = "CheckedWith";
        //         var validationColor = "success";
        //         if (index.toLowerCase().indexOf("ToBeChecked") > -1) {
        //           validationType = "ToBeCheckedWith";
        //           validationColor = "warning";
        //         }
 
        //         var validationString = validationType + consultants[g].replace(/[- _.]/g, "");
        //         validationStati.push(validationString);
        //         var n = fields.where({
        //           label: "validationStatus"
        //         })[0];
        //         /* add to any exisitng validation states */
        //         var validationStatus = n.get("mask") || "";
        //         validationStatus = validationStatus + " ";
        //         validationStatus = validationStatus + validationStati.join(" ");
        //         var uniqueStati = _.unique(validationStatus.trim().split(" "));
        //         n.set("mask", uniqueStati.join(" "));
 
        //         //              ROUGH DRAFT of adding CONSULTANTS logic TODO do self in the angular app, dont bother with the backbone app
        //         //              /* get the initials from the data */
        //         //              var consultantCode = consultants[g].replace(/[a-z -]/g,"");
        //         //              if(consultantusername.length === 2){
        //         //                consultantCode = consultantusername;
        //         //              }
        //         //              if(consultantCode.length < 2){
        //         //                consultantCode = consultantCode+"C";
        //         //              }
        //         //              var c = new Consultant("username", consultantCode);
        //         //              /* use the value in the cell for the checked with state, but don't keep the spaces */
        //         //              var validationType = "CheckedWith";
        //         //              if(index.toLowerCase().indexOf("ToBeChecked") > -1){
        //         //                validationType = "ToBeCheckedWith";
        //         //              }
        //         //              /*
        //         //               * This function uses the consultant code to create a new validation status
        //         //               */
        //         //              var onceWeGetTheConsultant = function(){
        //         //                var validationString = validationType+consultants[g].replace(/ /g,"");
        //         //                validationStati.push(validationString);
        //         //                var n = fields.where({label: "validationStatus"})[0];
        //         //                if(n !== undefined){
        //         //                  /* add to any exisitng validation states */
        //         //                  var validationStatus = n.get("mask") || "";
        //         //                  validationStatus = validationStatus + " ";
        //         //                  validationStatus = validationStatus + validationStati.join(" ");
        //         //                  var uniqueStati = _.unique(validationStatus.trim().split(" "));
        //         //                  n.set("mask", uniqueStati.join(" "));
        //         //                }
        //         //              };
        //         //              /*
        //         //               * This function creates a consultant code and then calls
        //         //               * onceWeGetTheConsultant to create a new validation status
        //         //               */
        //         //              var callIfItsANewConsultant = function(){
        //         //                var dialect =  "";
        //         //                var language =  "";
        //         //                try{
        //         //                  dialect = fields.where({label: "dialect"})[0] || "";
        //         //                  language = fields.where({label: "language"})[0] || "";
        //         //                }catch(e){
        //         //                  self.debug("Couldn't get self consultant's dialect or language");
        //         //                }
        //         //                c = new Consultant({filledWithDefaults: true});
        //         //                c.set("username", Date.now());
        //         //                if(dialect)
        //         //                  c.set("dialect", dialect);
        //         //                if(dialect)
        //         //                  c.set("language", language);
        //         //
        //         //                onceWeGetTheConsultant();
        //         //              };
        //         //              c.fetch({
        //         //                success : function(model, response, options) {
        //         //                  onceWeGetTheConsultant();
        //         //                },
        //         //                error : function(model, xhr, options) {
        //         //                  callIfItsANewConsultant();
        //         //                }
        //         //              });
 
        //       }
        //     } else if (index === "validationStatus") {
        //       var eachValidationStatus = fields.where({
        //         label: index
        //       })[0];
        //       if (eachValidationStatus !== undefined) {
        //         /* add to any exisitng validation states */
        //         var selfValidationStatus = eachValidationStatus.get("mask") || "";
        //         selfValidationStatus = selfValidationStatus + " ";
        //         selfValidationStatus = selfValidationStatus + value;
        //         var selfUniqueStati = _.unique(selfValidationStatus.trim().split(" "));
        //         eachValidationStatus.set("mask", selfUniqueStati.join(" "));
        //       }
        //     } else if (index === "audioFileName") {
        //       if (!audioVideo) {
        //         audioVideo = new AudioVideo();
        //       }
        //       audioVideo.set("filename", value);
        //       audioVideo.set("orginalFilename", audioFileDescriptionsKeyedByFilename[value] ? audioFileDescriptionsKeyedByFilename[value].name : "");
        //       audioVideo.set("URL", self.audioUrl + "/" + window.app.get("corpus").dbname + "/" + value);
        //       audioVideo.set("description", audioFileDescriptionsKeyedByFilename[value] ? audioFileDescriptionsKeyedByFilename[value].description : "");
        //       audioVideo.set("details", audioFileDescriptionsKeyedByFilename[value]);
        //     } else if (index === "startTime") {
        //       if (!audioVideo) {
        //         audioVideo = new AudioVideo();
        //       }
        //       audioVideo.set("startTime", value);
        //     } else if (index === "endTime") {
        //       if (!audioVideo) {
        //         audioVideo = new AudioVideo();
        //       }
        //       audioVideo.set("endTime", value);
        //     } else {
        //       var knownlowercasefields = "utterance,gloss,morphemes,translation".split();
        //       if (knownlowercasefields.indexOf(index.toLowerCase()) > -1) {
        //         index = index.toLowerCase();
        //       }
        //       var igtField = fields.where({
        //         label: index
        //       })[0];
        //       if (igtField !== undefined) {
        //         igtField.set("mask", value);
        //       }
        //     }
        //   };
        //   for (var a in array) {
        //     var d = new Datum({
        //       filledWithDefaults: true,
        //       dbname: self.dbname
        //     });
        //     //copy the corpus"s datum fields and empty them.
        //     var datumfields = self.importFields.clone();
        //     for (var x in datumfields) {
        //       datumfields[x].mask = "";
        //       datumfields[x].value = "";
        //     }
        //     var fields = new DatumFields(datumfields);
        //     var audioVideo = null;
        //     var audioFileDescriptionsKeyedByFilename = {};
        //     if (self.files && self.files.map) {
        //       self.files.map(eachFileDetails);
        //     }
 
        //     $.each(array[a], forEachRow);
        //     d.set("fields", fields);
        //     if (audioVideo) {
        //       d.audioVideo.add(audioVideo);
        //       if (self.debugMode) {
        //         self.debug(JSON.stringify(audioVideo.toJSON()) + JSON.stringify(fields.toJSON()));
        //       }
        //     }
        //     // var states = window.app.get("corpus").get("datumStates").clone();
        //     // d.set("datumStates", states);
        //     d.set("session", self.get("session"));
        //     //these are temp datums, dont save them until the user saves the data list
        //     self.importPaginatedDataListDatumsView.collection.add(d);
        //     //        self.dataListView.model.get("datumIds").push(d.id); the datum has no id, cannot put in datumIds
        //     d.lookForSimilarDatum();
        //     self.get("files").push(d);
        //   }
        //   self.set("consultants", _.unique(self.consultants).join(","));
        //   self.importPaginatedDataListDatumsView.renderUpdatedPaginationControl();
 
        //   $(".approve-save").removeAttr("disabled");
        //   $(".approve-save").removeClass("disabled");
 
      } catch (e) {
        self.warn("There was a problem while converting the matrix into a data list.", e);
        self.warn(e.stack);
        deferred.reject("There was a problem while converting the matrix into a data list.");
      }
 
      return deferred.promise;
    }
  },
  // savedcount : 0,
  // savedindex : [],
  // savefailedcount : 0,
  // savefailedindex : [],
  // nextsavedatum : 0,
 
  preprocess: {
    value: function(options) {
      var deferred = Q.defer(),
        self = this;
 
      this.verbose("In the preprocess", this);
      Q.nextTick(function() {
        self.debug("Preprocessing  ");
 
        // self.debug('options.datum', options.datum);
        options.datum.fields.orthography.value = options.rawText;
        if (options.datum.fields.utterance) {
          options.datum.fields.utterance.value = options.rawText;
        }
 
        options.datum.id = options.datum.tempId = options.id || options.uri.replace(new RegExp(".*" + options.dbname + "/"), "");
        Eif (options.datum.id.lastIndexOf("/") > -1) {
          options.datum.id = options.datum.tempId = options.datum.id.substring(options.datum.id.lastIndexOf("/") + 1, options.datum.id.lastIndexOf("."));
        }
 
        // let the application customize the preprocess function
        if (typeof options.preprocessOptions.preprocessFunction === "function") {
          options.preprocessOptions.preprocessFunction(options.datum);
        }
 
        self.debug("running write for preprocessed");
        Iif (!options.preprocessOptions || !options.preprocessOptions.writePreprocessedFileFunction) {
          return deferred.resolve(options);
        }
        var extension = ".fielddb";
        Iif (self.application && self.application.brandLowerCase) {
          extension = "." + self.application.brandLowerCase;
        }
        options.preprocessedUri = options.uri + extension;
        // options.preprocessedUri = "." + options.uri.substring(0, options.uri.lastIndexOf(".")) + ".preprocessed";
        var preprocessResult = JSON.stringify(options.datum.toJSON(false, "removeempty"), null, 2);
        try {
          options.preprocessOptions.writePreprocessedFileFunction({
              preprocessedUri: options.preprocessedUri,
              body: preprocessResult
            },
            function(err, data) {
              Iif (err) {
                self.debug("Couldnt write " + options.preprocessedUri, err);
                return deferred.reject(err);
              }
              self.debug("Wrote " + options.preprocessedUri, data);
              self.debug("Preprocesing success");
              deferred.resolve(options);
            });
        } catch (err) {
          deferred.reject(err);
        }
      });
 
      return deferred.promise;
    }
  },
 
  importFields: {
    get: function() {
      if (!this._importFields || this._importFields.length === 0) {
        if (this.importType === "participants") {
          if (this.corpus && this.corpus.participantFields) {
            this._importFields = new DatumFields(this.corpus.participantFields.clone());
          } else {
            this._importFields = new DatumFields(this.corpus.defaults_psycholinguistics.participantFields);
          }
        } else Eif (this.corpus && this.corpus.datumFields) {
          this._importFields = new DatumFields(this.corpus.datumFields.clone());
        }
      }
      Iif (!this._importFields) {
        this._importFields = new DatumFields();
      }
      return this._importFields;
    },
    set: function(fields) {
      this._importFields = fields;
    }
  },
 
  /**
   *  This function looks for the field's details from the import fields, if they exist it returns those values.
   *
   * If the field isnt in the importFields, it looks for fields which this field should map to (eg, if the field is codepermanent it can be mapped to anonymouscode)
   * @param  {String/Object} field A datumField to look for, or the label/id of a datum field to look for.
   * @return {DatumField}       A datum field with details filled in from the corresponding field in the corpus, or from a template.
   */
  normalizeImportFieldWithExistingCorpusFields: {
    value: function(field) {
      var correspondingDatumField;
      Eif (this.corpus && this.corpus.normalizeFieldWithExistingCorpusFields) {
        correspondingDatumField = this.corpus.normalizeFieldWithExistingCorpusFields(field, this.importFields);
      }
      this.debug("correspondingDatumField ", correspondingDatumField);
 
      if (correspondingDatumField) {
        return correspondingDatumField;
      } else {
        return new DatumField({
          id: "columnplaceholder",
          value: ""
        });
      }
    }
  },
 
  /**
   * Executes the final import if the options indicate that it should be executed, by default it only produces a dry run.
   *
   * @type {Object}
   */
  import: {
    value: function(options) {
      var deferred = Q.defer(),
        self = this;
      this.todo("TODO test the import");
 
      var savePromises = [];
      var docsToSave = [];
      if (this.datalist.docs && this.datalist.docs._collection) {
        docsToSave = this.datalist.docs._collection;
      } else {
        this.warn("There were no docs prepared for import, this is odd.");
      }
      self.progress = self.progress || {};
      docsToSave.map(function(builtDoc) {
        if (self.importType === "audioVideo") {
          self.debug("not doing any save for an audio video import");
        } else {
          self.bug("test the save on the new docs from import");
          if (self.importType === "participant") {
            builtDoc.id = builtDoc.anonymousCode || Date.now();
          }
          builtDoc.session = self.session;
          self.debug(" saving", builtDoc.id);
          self.progress.total++;
          // self.datalist.docs.add(builtDoc);
 
          var promise = builtDoc.save();
 
          promise.then(function(success) {
            self.debug(success);
            self.progress.completed++;
          }, function(error) {
            self.debug(error);
            self.progress.completed++;
          }).fail(function(error) {
            console.error(error.stack, self);
            deferred.reject(error);
          });
 
          savePromises.push(promise);
        }
      });
 
      Q.allSettled(savePromises).then(function(results) {
        self.debug(results);
        deferred.resolve(results);
        self.progress.completed++;
        self.render();
        return options;
      }, function(results) {
        self.debug(results);
        deferred.resolve(results);
        self.progress.completed++;
        self.render();
        return options;
      }).fail(function(error) {
        console.error(error.stack, self);
        deferred.reject(error);
      });
 
      return deferred.promise;
    }
  },
 
  fileDetails: {
    get: function() {
      return this._fileDetails || FieldDBObject.DEFAULT_STRING;
    },
    set: function(value) {
      this._fileDetails = value;
    }
  },
 
  /**
   * Holds meta data about the imported data list and references to the datum ids
   *
   * @type {Object}
   */
  datalist: {
    get: function() {
      if (!this.session || !this.session.datalist) {
        return;
        // this.debug("creating a default data list");
        //   this.session.datalist = new DataList();
        //   console.log("this.session.datalist", this.session.datalist);
      }
      return this.session.datalist;
    },
    set: function(value) {
      Iif (this._session && value === this._session.datalist) {
        return this;
      }
      if (!value || !value.docs || !value.docs.primaryKey || value.docs.primaryKey !== "tempId") {
        this.warn("  not setting the datalist, its missing some stuff ", value);
        return this;
      }
      this.debug("  setting the _session.datalist", value.docs.primaryKey);
      delete this._session._datalist;
      this._session.initializeDatalist(value);
      return this;
    }
  },
 
  session: {
    get: function() {
      if (!this._session) {
        this.debug("There's no session!");
        return;
      }
      this.debug("getting the _session " + this._session.fields.length);
      return this._session;
    },
    set: function(value) {
      Iif (value === this._session) {
        return;
      }
      if (!value || !value.datalist || !value.datalist.docs) {
        this.warn("  not setting the session on import, its missing some stuff ", value);
        return;
      }
      value.datalist.docs.primaryKey = "tempId";
      var datalist = value.datalist;
 
      this.debug("  setting the _session", value);
      Eif (!(value instanceof Session)) {
        value = new Session(value);
      }
      this.debug("  setting the _session's datalist", datalist);
 
      this._session = value;
      // this._session.initializeDatalist(datalist);
      this.datalist = datalist;
 
      return;
    }
  },
 
  /**
   * Holds the files themselves while the import is in process
   *
   * @type {Object}
   */
  files: {
    get: function() {
      this.debug("Getting Datum collection");
      if (!this._files) {
        this._files = new Collection({
          id: "importfiles",
          inverted: false,
          primaryKey: "fileName"
        });
      }
      this.debug("Returning a collection");
      return this._files;
    },
    set: function(value) {
      Iif (value === this._files) {
        return;
      }
      this._files = value;
    }
  },
 
  /**
   * Saves the import's state to file to be resumed or reviewed later
   *
   * @type {Object}
   */
  pause: {
    value: function() {
      return this;
    }
  },
 
  /**
   * Resumes a previous import from a json object, or a uri containing json
   *
   * @type {Object}
   */
  resume: {
    value: function() {
      return this;
    }
  },
 
  id: {
    get: function() {
      if (this.datalist) {
        return this.datalist.id;
      }
    },
    set: function(value) {
      if (this.datalist) {
        this.datalist.id = value;
      }
    }
  },
 
  url: {
    value: "/datalists"
  },
 
  corpus: {
    get: function() {
      if (!this._corpus) {
        // throw new Error("Import\"s corpus is undefined");
        // this.warn("Import\"s corpus is undefined");
        return;
      }
      return this._corpus;
    },
    set: function(value) {
      Iif (value === this._corpus) {
        return;
      }
      this._corpus = value;
    }
  },
 
  asFieldMatrix: {
    get: function() {
      return this._asFieldMatrix;
    },
    set: function(value) {
      this._asFieldMatrix = value;
    }
  },
 
  asCSV: {
    get: function() {
      return this.asFieldMatrix;
    },
    set: function(value) {
      var tryAsNumber,
        tryAsDate;
 
      value = value.map(function(row) {
        return row.map(function(cell) {
          Iif (cell === undefined || cell === null) {
            cell = {
              value: ""
            };
          }
          Eif (typeof cell !== "object") {
            cell = {
              value: cell
            };
          }
          if (cell && cell.value && typeof cell.value.trim === "function") {
            cell.value = cell.value.trim();
          }
          if (cell.value !== "") {
            tryAsNumber = Number(cell.value);
            if (!isNaN(tryAsNumber)) {
              cell.value = tryAsNumber;
              cell.type = "number";
            } else {
              tryAsDate = new Date(cell.value);
              if (!isNaN(tryAsDate.getDate() && tryAsDate.getYear() > 70)) {
                // cell.value = tryAsDate;
                cell.type = "date";
                cell.json = {
                  "date": tryAsDate,
                  "timestamp": {
                    // "start": tryAsDate,
                    "end": tryAsDate.getTime(),
                    // "accuracy": null
                  }
                };
              }
            }
          }
          return cell;
        });
      });
 
      this.asFieldMatrix = value;
    }
  },
 
  /**
   * This function tries to guess if you have \n or \r as line endings
   * and then tries to determine if you have "surounding your text".
   *
   * CSV is a common export format for Filemaker, Microsoft Excel and
   * OpenOffice Spreadsheets, and could be a good format to export
   * from these sources and import into FieldDB.
   *
   * @param text to be imported
   */
  importCSV: {
    value: function(text, callback) {
      Iif (!text) {
        return;
      }
      var rows = text.split("\n");
      Iif (rows.length < 3) {
        var macrows = text.split("\r");
        if (macrows.length > rows.length) {
          rows = macrows;
          this.status = this.status + " Detected a \r line ending.";
        }
      }
      var firstrow = rows[0];
      var hasQuotes = false;
      //If it looks like it already has quotes:
      Iif (rows[0].split("", "").length > 2 && rows[5].split("", "").length > 2) {
        hasQuotes = true;
        this.status = this.status + " Detected text was already surrounded in quotes.";
      }
      for (var l in rows) {
        Iif (hasQuotes) {
          rows[l] = rows[l].trim().replace(/^"/, "").replace(/"$/, "").split("", "");
          //          var withoutQuotes = [];
          //          _.each(rows[l],function(d){
          //            withoutQuotes.push(d.replace(/"/g,""));
          //          });
          //          rows[l] = withoutQuotes;
        } else {
          rows[l] = this.parseLineCSV(rows[l]);
          /* This was a fix for alan's data but it breaks other data. */
          //          var rowWithoutQuotes = rows[l].replace(/"/g,"");
          //          rows[l] = this.parseLineCSV(rowWithoutQuotes);
        }
      }
      /* get the first line and set it to be the header by default */
      var header = [];
      Eif (rows.length > 1) {
        firstrow = firstrow;
        Iif (hasQuotes) {
          header = firstrow.trim().replace(/^"/, "").replace(/"$/, "").split("", "");
        } else {
          header = this.parseLineCSV(firstrow);
        }
      } else if (rows.length === 1) {
        header = rows[0].map(function() {
          return "";
        });
      }
      this.extractedHeaderObjects = header;
 
      this.asCSV = rows;
      Iif (typeof callback === "function") {
        callback();
      }
    }
  },
 
  /**
   * http://purbayubudi.wordpress.com/2008/11/09/csv-parser-using-javascript/
   * -- CSV PARSER --
   * author  : Purbayu, 30Sep2008
   * email   : purbayubudi@gmail.com
   *
   * description :
   *  This jscript code describes how to load csv file and parse it into fields.
   *  Additionally, a function to display html table as result is added.
   *
   * disclamer:
   *  To use this code freely, you must put author's name in it.
   */
  parseLineCSV: {
    value: function(lineCSV) {
      // parse csv line by line into array
      var CSV = [];
      var csvCharacter = ",";
      this.debug(lineCSV, typeof lineCSV);
      var matches = lineCSV.split(csvCharacter);
      if (matches.length < 2) {
        csvCharacter = ";";
      }
      // Insert space before character ",". This is to anticipate
      // "split" in IE
      // try this:
      //
      // var a=",,,a,,b,,c,,,,d";
      // a=a.split(/\,/g);
      // document.write(a.length);
      //
      // You will see unexpected result!
      //
      lineCSV = lineCSV.replace(new RegExp(csvCharacter, "g"), " " + csvCharacter);
 
      lineCSV = lineCSV.split(new RegExp(csvCharacter, "g"));
 
      // This is continuing of "split" issue in IE
      // remove all trailing space in each field
      var i,
        j;
      for (i = 0; i < lineCSV.length; i++) {
        lineCSV[i] = lineCSV[i].replace(/\s*$/g, "");
      }
 
      lineCSV[lineCSV.length - 1] = lineCSV[lineCSV.length - 1]
        .replace(/^\s*|\s*$/g, "");
      var fstart = -1;
 
      for (i = 0; i < lineCSV.length; i++) {
        if (lineCSV[i].match(/"$/)) {
          Eif (fstart >= 0) {
            for (j = fstart + 1; j <= i; j++) {
              lineCSV[fstart] = lineCSV[fstart] + csvCharacter + lineCSV[j];
              lineCSV[j] = "-DELETED-";
            }
            fstart = -1;
          }
        }
        fstart = (lineCSV[i].match(/^"/)) ? i : fstart;
      }
 
      j = 0;
 
      for (i = 0; i < lineCSV.length; i++) {
        if (lineCSV[i] !== "-DELETED-") {
          CSV[j] = lineCSV[i];
          CSV[j] = CSV[j].replace(/^\s*|\s*$/g, ""); // remove leading & trailing
          // space
          CSV[j] = CSV[j].replace(/^"|"$/g, ""); // remove " on the beginning
          // and end
          CSV[j] = CSV[j].replace(/""/g, "\""); // replace "" with "
          j++;
        }
      }
      return CSV;
    }
  },
 
  importXML: {
    value: function(text) {
      var deferred = Q.defer();
      var self = this;
 
      Q.nextTick(function() {
        try {
          self.extractedHeaderObjects = [];
          self.asCSV = [];
          var xmlParser = new X2JS();
          var jsonObj = xmlParser.xml_str2json ? xmlParser.xml_str2json(text) : xmlParser.xml2js(text);
 
          if (jsonObj && jsonObj.lessonset) {
            return deferred.resolve(self.importLessonset(jsonObj.lessonset));
          }
          self.warn("The app thinks this might be a XML file, but its not one we recognize. You can vote for it in our bug tracker, or add an importer for your kind of XML https://github.com/FieldDB/FieldDB/blob/master/api/import/Import.js");
        } catch (err) {
          deferred.reject(err);
        }
        deferred.resolve(self.datalist);
      });
      return deferred.promise;
    }
  },
 
  importLessonset: {
    value: function(lessonSet) {
      var self = this;
      var detectedDatum = [];
      var detectedFieldLabels = {};
      var DataList = self.session.datalist.constructor;
 
      var languageLessonsDatalist = new DataList({
        title: lessonSet.title,
        dbname: self.corpus.dbname,
        audioVideo: [],
        unsaved: true,
        docs: []
      });
      self.languageLessonsDatalist = languageLessonsDatalist;
      self.debug("title: " + languageLessonsDatalist.title);
 
      Iif (!lessonSet.section) {
        return languageLessonsDatalist;
      }
      self.debug(" " + lessonSet.section.length + " sections");
      lessonSet.section.forEach(function(section) {
        var sectionDatalist = new DataList({
          id: FieldDBObject.uuidGenerator(),
          dbname: self.corpus.dbname,
          title: section.title,
          audioVideo: [],
          unsaved: true,
          type: "LanguageLearningSection",
          description: Array.isArray(section.note) ? section.note.join(" ") : section.note,
          designNote: Array.isArray(section.designnote) ? section.designnote.join(" ") : section.designnote,
          docs: []
        });
        self.debug("section: " + sectionDatalist.title);
        languageLessonsDatalist.docs.add(sectionDatalist);
 
        Iif (!section.unit) {
          return;
        }
        self.debug("   " + section.unit.length + " units");
        section.unit.forEach(function(unit) {
          var unitDatalist = new DataList({
            id: FieldDBObject.uuidGenerator(),
            dbname: self.corpus.dbname,
            title: unit.title,
            audioVideo: [],
            unsaved: true,
            type: "LanguageLearningUnit",
            description: Array.isArray(unit.note) ? unit.note.join(" ") : unit.note,
            designNote: Array.isArray(unit.designnote) ? unit.designnote.join(" ") : unit.designnote,
            docs: []
          });
          self.debug("  unit: " + unitDatalist.title);
          sectionDatalist.docs.add(unitDatalist);
 
          Iif (!unit.lesson) {
            return;
          }
          var lessons = unit.lesson;
          if (!Array.isArray(lessons)) {
            lessons = [unit.lesson];
          }
          self.debug("     " + lessons.length + " lessons");
          lessons.forEach(function(lesson) {
            var lessonDatalist = new DataList({
              id: FieldDBObject.uuidGenerator(),
              dbname: self.corpus.dbname,
              title: lesson.title,
              audioVideo: [],
              unsaved: true,
              type: "LanguageLesson",
              description: Array.isArray(lesson.note) ? lesson.note.join(" ") : lesson.note,
              designNote: Array.isArray(lesson.designnote) ? lesson.designnote.join(" ") : lesson.designnote,
              explanation: Array.isArray(lesson.explnote) ? lesson.explnote.join(" ") : lesson.explnote,
              docs: []
            });
            self.debug("    lesson: " + lessonDatalist.title);
            unitDatalist.docs.add(lessonDatalist);
 
            if (!lesson.dialog) {
              return;
            }
            var dialogs = [];
            if (Array.isArray(lesson.dialog)) {
              dialogs = dialogs.concat(lesson.dialog.map(function(item) {
                item.type = "Dialog";
                return item;
              }));
            } else Eif (lesson.dialog) {
              lesson.dialog.type = "Dialog";
              dialogs.push(lesson.dialog);
            }
            if (Array.isArray(lesson.vocab)) {
              dialogs = dialogs.concat(lesson.vocab.map(function(item) {
                item.type = "Vocab";
                return item;
              }));
            } else if (lesson.vocab) {
              lesson.vocab.type = "Vocab";
              dialogs.push(lesson.vocab);
            }
            self.debug("       " + dialogs.length + " dialogs ");
            dialogs.forEach(function(dialog) {
              var dialogDatalist = new DataList({
                id: FieldDBObject.uuidGenerator(),
                dbname: self.corpus.dbname,
                title: dialog.title || lesson.title + " " + dialog.type + " " + (lessonDatalist.docs.length + 1),
                audioVideo: [],
                unsaved: true,
                type: dialog.type,
                description: Array.isArray(dialog.note) ? dialog.note.join(" ") : dialog.note,
                discussion: Array.isArray(dialog.designnote) ? dialog.designnote.join(" ") : dialog.designnote,
                docs: []
              });
              lessonDatalist.docs.add(dialogDatalist);
 
              var lines = [];
              if (Array.isArray(dialog.line)) {
                lines = lines.concat(dialog.line);
              } else Eif (dialog.line) {
                lines.push(dialog.line);
              }
 
              Iif (!lines.length) {
                return;
              }
              self.debug("         " + lines.length + " lines ");
              // Dont create datum yet, let the user edit the fields
              lines.forEach(function(line) {
                var datum = self.corpus.newDatum();
                Iif (line.notes) {
                  datum.comments = Array.isArray(line.notes) ? line.notes : [];
                }
                datum.tempId = FieldDBObject.uuidGenerator();
                datum.id = datum.tempId;
                detectedFieldLabels.id = "id";
 
                Object.keys(line).forEach(function(key) {
                  Iif (["toString"].indexOf(key) > -1) {
                    return;
                  }
                  Eif (key && key.indexOf("_asArray") === -1) {
                    detectedFieldLabels[key] = key;
                  }
 
                  if (key === "soundfile") {
                    datum.audioVideo.add(new AudioVideo({
                      filename: line[key] + ".mp3"
                    }));
                    return;
                  }
                  if (key === "img") {
                    datum.images.add(new Image({
                      filename: line[key]
                    }));
                    // self.debug("datum", datum.toJSON());
                    return;
                  }
                  datum.fields.add({
                    id: key,
                    value: line[key]
                  });
                });
                dialogDatalist.docs.add(datum);
 
                // Adding datum to the parent datalists
                // so that the datum show in the prototype app
                lessonDatalist.docs.add(datum);
                unitDatalist.docs.add(datum);
                sectionDatalist.docs.add(datum);
                languageLessonsDatalist.docs.add(datum);
 
                // TODO add audio, video, images to the parent datalists?
                var audioVideoItem = datum.audioVideo._collection[0];
                if (audioVideoItem) {
                  dialogDatalist.audioVideo.add(datum.audioVideo._collection[0]);
                  lessonDatalist.audioVideo.add(datum.audioVideo._collection[0]);
                  unitDatalist.audioVideo.add(datum.audioVideo._collection[0]);
                  sectionDatalist.audioVideo.add(datum.audioVideo._collection[0]);
                  languageLessonsDatalist.audioVideo.add(datum.audioVideo._collection[0]);
                }
 
                delete datum.tempId;
                line.id = datum.id;
                line.soundfile = line.soundfile ? line.soundfile + ".mp3" : "";
                detectedDatum.push(line);
              });
            });
          });
        });
      });
 
      var extractedHeaderObjects = Object.keys(detectedFieldLabels).map(function(label) {
        return {
          value: label
        };
      });
      self.debug("extractedHeaderObjects", extractedHeaderObjects, detectedFieldLabels);
      self.extractedHeaderObjects = extractedHeaderObjects;
      self._asFieldMatrix = detectedDatum.map(function(item) {
        var onlyFields = {};
        Object.keys(detectedFieldLabels).forEach(function(label) {
          onlyFields[label] = item[label];
        });
        return onlyFields;
      });
 
      return self.languageLessonsDatalist;
    }
  },
 
  importElanXML: {
    value: function(text, callback) {
      Iif (!text) {
        return;
      }
      this.todo("import xml parsers to turn xml import back on");
      Eif (true) {
        return;
      }
      //alert("The app thinks this might be a XML file, but we haven't implemented this kind of import yet. You can vote for it in our bug tracker.");
      var xmlParser = new X2JS();
      window.text = text;
      var jsonObj = xmlParser.xml_str2json(text);
 
      this.debug(jsonObj);
 
      //add the header to the session
      //    HEADER can be put in the session and in the datalist
      var annotationDetails = JSON.stringify(jsonObj.ANNOTATION_DOCUMENT.HEADER).replace(/,/g, "\n").replace(/[\[\]{}]/g, "").replace(/:/g, " : ").replace(/"/g, "").replace(/\n/g, "").replace(/file : /g, "file:").replace(/ : \//g, ":/").trim();
      //TODO turn these into session fields
      this.status = this.status + "\n" + annotationDetails;
 
      var header = [];
      var tierinfo = [];
      //    TIER has tiers of each, create datum  it says who the informant is and who the data entry person is. can turn the objects in the tier into a datum
      //for tier, add rows containing
      //    _ANNOTATOR
      tierinfo.push("_ANNOTATOR");
      //    _DEFAULT_LOCALE
      tierinfo.push("_DEFAULT_LOCALE");
      //    _LINGUISTIC_TYPE_REF
      tierinfo.push("_LINGUISTIC_TYPE_REF");
      //    _PARTICIPANT
      tierinfo.push("_PARTICIPANT");
      //    _TIER_ID
      tierinfo.push("_TIER_ID");
      //    __cnt
      tierinfo.push("__cnt");
 
      var annotationinfo = [];
      //    ANNOTATION.ALIGNABLE_ANNOTATION.ANNOTATION_VALUE.__cnt
      //      annotationinfo.push({"FieldDBDatumFieldName" : "ANNOTATION.ALIGNABLE_ANNOTATION.ANNOTATION_VALUE", "elanALIGNABLE_ANNOTATION": "ANNOTATION_VALUE"});
      //    ANNOTATION.ALIGNABLE_ANNOTATION._ANNOTATION_ID
      annotationinfo.push({
        "FieldDBDatumFieldName": "ANNOTATION.ALIGNABLE_ANNOTATION._ANNOTATION_ID",
        "elanALIGNABLE_ANNOTATION": "_ANNOTATION_ID"
      });
      //    ANNOTATION.ALIGNABLE_ANNOTATION._TIME_SLOT_REF1
      annotationinfo.push({
        "FieldDBDatumFieldName": "ANNOTATION.ALIGNABLE_ANNOTATION._TIME_SLOT_REF1",
        "elanALIGNABLE_ANNOTATION": "_TIME_SLOT_REF1"
      });
      //    ANNOTATION.ALIGNABLE_ANNOTATION._TIME_SLOT_REF2
      annotationinfo.push({
        "FieldDBDatumFieldName": "ANNOTATION.ALIGNABLE_ANNOTATION._TIME_SLOT_REF2",
        "elanALIGNABLE_ANNOTATION": "_TIME_SLOT_REF2"
      });
      //
      var refannotationinfo = [];
      //    ANNOTATION.REF_ANNOTATION.ANNOTATION_VALUE
      refannotationinfo.push({
        "FieldDBDatumFieldName": "ANNOTATION.REF_ANNOTATION.ANNOTATION_VALUE",
        "elanREF_ANNOTATION": "ANNOTATION_VALUE"
      });
      //    ANNOTATION.REF_ANNOTATION._ANNOTATION_ID
      refannotationinfo.push({
        "FieldDBDatumFieldName": "ANNOTATION.REF_ANNOTATION._ANNOTATION_ID",
        "elanREF_ANNOTATION": "_ANNOTATION_ID"
      });
      //    ANNOTATION.REF_ANNOTATION._ANNOTATION_REF
      refannotationinfo.push({
        "FieldDBDatumFieldName": "ANNOTATION.REF_ANNOTATION._ANNOTATION_REF",
        "elanREF_ANNOTATION": "_ANNOTATION_REF"
      });
 
      header.push("_ANNOTATOR");
      header.push("_DEFAULT_LOCALE");
      header.push("_LINGUISTIC_TYPE_REF");
      header.push("_PARTICIPANT");
      header.push("_TIER_ID");
      header.push("__cnt");
 
      header.push("ANNOTATION.ALIGNABLE_ANNOTATION.ANNOTATION_VALUE");
 
      header.push("ANNOTATION.ALIGNABLE_ANNOTATION._ANNOTATION_ID");
      header.push("ANNOTATION.ALIGNABLE_ANNOTATION._TIME_SLOT_REF1");
      header.push("ANNOTATION.ALIGNABLE_ANNOTATION._TIME_SLOT_REF2");
 
      header.push("ANNOTATION.REF_ANNOTATION.ANNOTATION_VALUE");
      header.push("ANNOTATION.REF_ANNOTATION._ANNOTATION_ID");
      header.push("ANNOTATION.REF_ANNOTATION._ANNOTATION_REF");
 
      //similar to toolbox
      var matrix = [];
      var TIER = jsonObj.ANNOTATION_DOCUMENT.TIER;
 
      var l,
        annotation,
        cell;
      //there are normally 8ish tiers, with different participants
      for (l in TIER) {
        //in those tiers are various amounts of annotations per participant
        for (annotation in TIER[l].ANNOTATION) {
          matrix[annotation] = [];
 
          for (cell in tierinfo) {
            matrix[annotation][tierinfo[cell]] = jsonObj.ANNOTATION_DOCUMENT.TIER[l][tierinfo[cell]];
          }
 
          try {
            matrix[annotation]["ANNOTATION.ALIGNABLE_ANNOTATION.ANNOTATION_VALUE.__cnt"] = TIER[l].ANNOTATION[annotation].ALIGNABLE_ANNOTATION.ANNOTATION_VALUE.__cnt;
            for (cell in annotationinfo) {
              matrix[annotation][annotationinfo[cell].FieldDBDatumFieldName] = TIER[l].ANNOTATION[annotation].ALIGNABLE_ANNOTATION[annotationinfo[cell].elanALIGNABLE_ANNOTATION];
            }
          } catch (e) {
            this.debug("TIER " + l + " doesnt seem to have a ALIGNABLE_ANNOTATION object. We don't really knwo waht the elan file format is, or why some lines ahve ALIGNABLE_ANNOTATION and some dont. So we are just skipping them for this datum.");
          }
 
          try {
            for (cell in refannotationinfo) {
              matrix[annotation][refannotationinfo[cell].FieldDBDatumFieldName] = TIER[l].ANNOTATION[annotation].REF_ANNOTATION[refannotationinfo[cell].elanREF_ANNOTATION];
            }
          } catch (e) {
            this.debug("TIER " + l + " doesnt seem to have a REF_ANNOTATION object. We don't really knwo waht the elan file format is, or why some lines ahve REF_ANNOTATION and some dont. So we are just skipping them for this datum.");
          }
 
        }
      }
      var rows = [];
      for (var d in matrix) {
        var cells = [];
        //loop through all the column headings, find the data for that header and put it into a row of cells
        for (var h in header) {
          cell = matrix[d][header[h]];
          if (cell) {
            cells.push(cell);
          } else {
            //fill the cell with a blank if that datum didn't have a header
            cells.push("");
          }
        }
        rows.push(cells);
      }
      if (rows === []) {
        rows.push("");
      }
      this.extractedHeaderObjects = header;
      this.asCSV = rows;
      if (typeof callback === "function") {
        callback();
      }
    }
  },
  /**
   * This function accepts text which uses \t tabs between columns. If
   * you have your data in ELAN or in Microsoft Excel or OpenOffice
   * spreadsheets, this will most likely be a good format to export
   * your data, and import into FieldDB. This function is triggered if
   * your file has more than 100 tabs in it, FieldDB guesses that it
   * should try this function.
   *
   * @param text to be imported
   */
  importTabbed: {
    value: function(text, callback) {
      if (!text) {
        return;
      }
      var rows = text.split("\n"),
        l;
      if (rows.length < 3) {
        rows = text.split("\r");
        this.status = this.status + " Detected a \n line ending.";
      }
      for (l in rows) {
        rows[l] = rows[l].split("\t");
      }
 
      this.asCSV = rows;
      if (typeof callback === "function") {
        callback();
      }
    }
  },
 
  metadataLines: [],
 
  /**
   * This function takes in a text block, splits it on lines and then
   * takes the first word with a \firstword as the data type/column
   * heading and then walks through the file looking for lines that
   * start with \ge and creates a new datum each time it finds \ge
   * This works for verb lexicons but would be \ref if an interlinear
   * gloss. TODO figure out how Toolbox knows when one data entry
   * stops and another starts. It doesn't appear to be double spaces...
   *
   * @param text
   * @param callback
   */
  importToolbox: {
    value: function(text, callback) {
      Iif (!text) {
        return;
      }
      var lines = text.split("\n");
      var macLineEndings = false;
      Iif (lines.length < 3) {
        lines = text.split("\r");
        macLineEndings = true;
        this.status = this.status + " Detected a \r line ending.";
      }
 
      var matrix = [];
      var currentDatum = -1;
      var header = [];
      var columnhead = "";
 
      var firstToolboxField = "";
 
      /* Looks for the first line of the toolbox data */
      while (!firstToolboxField && lines.length > 0) {
        var potentialToolBoxFieldMatches = lines[0].match(/^\\[a-zA-Z]+\b/);
        Eif (potentialToolBoxFieldMatches && potentialToolBoxFieldMatches.length > 0) {
          firstToolboxField = potentialToolBoxFieldMatches[0];
        } else {
          /* remove the line, and put it into the metadata lines */
          this.metadataLines.push(lines.shift());
        }
      }
 
      for (var l in lines) {
        //Its a new row
        if (lines[l].indexOf(firstToolboxField) === 0) {
          currentDatum += 1;
          matrix[currentDatum] = {};
          matrix[currentDatum][firstToolboxField.replace(/\\/g, "")] = lines[l].replace(firstToolboxField, "").trim();
          header.push(firstToolboxField.replace(/\\/g, ""));
        } else {
          Eif (currentDatum >= 0) {
            //If the line starts with \ its a column
            if (lines[l].match(/^\\/)) {
              var pieces = lines[l].split(/ +/);
              columnhead = pieces[0].replace("\\", "");
              matrix[currentDatum][columnhead] = lines[l].replace(pieces[0], "");
              header.push(columnhead);
            } else {
              //add it to the current column head in the current datum, its just another line.
              Eif (lines[1].trim() !== "") {
                matrix[currentDatum][columnhead] += lines[l];
              }
            }
          }
        }
      }
      //only keep the unique headers
      header = getUnique(header);
      var rows = [];
      for (var d in matrix) {
        var cells = [];
        //loop through all the column headings, find the data for that header and put it into a row of cells
        for (var h in header) {
          var cell = matrix[d][header[h]];
          Eif (cell) {
            cells.push(cell);
          } else {
            //fill the cell with a blank if that datum didn't have a header
            cells.push("");
          }
        }
        rows.push(cells);
      }
      Iif (rows === []) {
        rows.push("");
      }
      this.extractedHeaderObjects = header;
      this.asCSV = rows;
      Iif (typeof callback === "function") {
        callback();
      }
    }
  },
 
  importMorphChallengeSegmentation: {
    value: function(text, self, callback) {
      var rows = text.trim().split("\n");
      if (rows.length < 3) {
        rows = text.split("\r");
        self.status = self.status + " Detected a \n line ending.";
      }
      var row,
        original,
        twoPieces,
        word,
        alternates,
        morphemes,
        gloss,
        source,
        l,
        filename = self.files[0].name;
      var header = ["orthography", "utterance", "morphemes", "gloss", "alternatesAnalyses", "alternates", "original", "source"];
      var convertFlatIGTtoObject = function(alternateParse) {
        morphemes = alternateParse.trim().split(" ");
        // self.debug("working on alternateParse", morphemes);
        return morphemes.map(function(morpheme) {
          return {
            morphemes: morpheme.split(":")[0],
            gloss: morpheme.split(":")[1]
          };
        });
      };
      var extractMorphemesFromIGT = function(alternate) {
        return alternate.morphemes.replace("+", "");
      };
      var extractGlossFromIGT = function(alternate) {
        return alternate.gloss.replace("+", "");
      };
      for (l in rows) {
        row = original = rows[l] + "";
        source = filename + ":line:" + l;
        twoPieces = row.split(/\t/);
        word = twoPieces[0];
        if (!twoPieces || !twoPieces[1]) {
          continue;
        }
        alternates = twoPieces[1].split(",");
        alternates = alternates.map(convertFlatIGTtoObject);
        morphemes = alternates[0].map(extractMorphemesFromIGT).join("-");
        gloss = alternates[0].map(extractGlossFromIGT).join("-");
        alternates.shift();
        // get alternative morpheme analyses so they show in the app.
        var alternateMorphemes = [];
        for (var alternateIndex = 0; alternateIndex < alternates; alternateIndex++) {
          alternateMorphemes.push(alternates[alternateIndex].map(extractMorphemesFromIGT).join("-"));
        }
        rows[l] = [word, word, morphemes, gloss, twoPieces[1], alternateMorphemes.join(","), original + "", source];
      }
      self.extractedHeaderObjects = header;
      self.asCSV = rows;
 
      if (typeof callback === "function") {
        callback();
      }
    }
  },
 
  uploadFiles: {
    value: function(files) {
      var deferred = Q.defer(),
        self = this;
 
      self.error = "";
      self.status = "";
 
      Q.nextTick(function() {
        var uploadUrl = new AudioVideo().BASE_SPEECH_URL + "/upload/extract/utterances";
        // var data = {
        //   files: files,
        //   token: self.token,
        //   dbname: self.dbname,
        //   username: self.username,
        //   returnTextGrid: self.returnTextGrid
        // };
        //
        var data = new FormData();
        // for (var ?fileIndex = 0; fileIndex > files.length; fileIndex++) {
        // data.append("file" + fileIndex, files[fileIndex]);
        // }
        // data.files = files;
        self.todo("use the files passed instead of jquery ", files);
        // http://stackoverflow.com/questions/24626177/how-to-create-an-image-file-from-a-dataurl
        if (files.indexOf("data") === 0) {
          // data.append("data", files); //test new split
 
          // var base64 = files.split("base64,")[1];
          var blob = dataURItoBlob(files);
          // blob.name = "file_" + Date.now() + "." + blob.type.split("/")[1];
          // blob.lastModfied = Date.now();
          // blob.lastModifiedDate = new Date(blob.lastModfied);
          // fd.append("canvasImage", blob);
 
          //http://www.nczonline.net/blog/2012/06/05/working-with-files-in-javascript-part-5-blobs/
          // var reconstructedFile =  new File("file_" + Date.now() + ".mp3", blob, "audio/mpeg");
 
          //http://stackoverflow.com/questions/8390855/how-to-instantiate-a-file-object-in-javascript
          files = [blob];
 
        }
        self.rawText = "";
        $.each(files, function(i, file) {
          data.append(i, file);
          if (file.name) {
            self.rawText = self.rawText + " " + file.name;
          }
        });
        if (self.rawText && self.rawText.trim()) {
          // window.alert("rendering import");
          self.rawText = self.rawText.trim();
          self.render();
        }
        if (!self.dbname && self.parent && self.parent.dbname) {
          self.dbname = self.parent.dbname;
        }
 
        // data.append("files", files);
        data.append("token", self.uploadtoken || "uploadingfromspreadsheet");
        data.append("pouchname", self.dbname);
        data.append("dbname", self.dbname);
        data.append("username", self.application.authentication.user.username);
        data.append("returnTextGrid", self.returnTextGrid || true);
 
        self.audioVideo = null;
        // this.model.audioVideo.reset();
        $.ajax({
          url: uploadUrl,
          type: "post",
          // dataType: 'json',
          cache: false,
          // withCredentials: false,
          contentType: false,
          processData: false,
          data: data,
          success: function(results) {
            if (results && results.status === 200) {
              self.uploadDetails = results;
              self.files = results.files;
              self.status = "File(s) uploaded and utterances were extracted.";
              var messages = [];
              self.rawText = "";
              /* Check for any textgrids which failed */
              for (var fileIndex = 0; fileIndex < results.files.length; fileIndex++) {
                if (results.files[fileIndex].textGridStatus >= 400) {
                  self.debug(results.files[fileIndex]);
                  var instructions = results.files[fileIndex].textGridInfo;
                  if (results.files[fileIndex].textGridStatus >= 500) {
                    instructions = " Please report this error.";
                  }
                  messages.push("Generating the textgrid for " + results.files[fileIndex].fileBaseName + " seems to have failed. " + instructions);
                  results.files[fileIndex].filename = results.files[fileIndex].name;
                  if (results.files[fileIndex].type && (results.files[fileIndex].type.indexOf("audio") > -1 || results.files[fileIndex].type.indexOf("video") > -1)) {
                    results.files[fileIndex].filename = results.files[fileIndex].fileBaseName + ".mp3";
                  }
                  results.files[fileIndex].URL = new AudioVideo().BASE_SPEECH_URL + "/" + self.corpus.dbname + "/" + results.files[fileIndex].filename;
                  results.files[fileIndex].description = results.files[fileIndex].description || "File from import";
                  self.addAudioVideoFile(results.files[fileIndex]);
                } else {
                  self.downloadTextGrid(results.files[fileIndex]);
                }
              }
              if (messages.length > 0) {
                self.status = messages.join(", ");
                deferred.resolve(self.status);
                // $(self.el).find(".status").html(self.get("status"));
                // if(window && window.appView && typeof window.appView.toastUser === "function") window.appView.toastUser(messages.join(", "), "alert-danger", "Import:");
              }
            } else {
              self.debug(results);
              var message = "Upload might have failed to complete processing on your file(s). Please report this error.";
              self.status = message + ": " + JSON.stringify(results);
              deferred.reject(message);
 
              // if(window && window.appView && typeof window.appView.toastUser === "function") window.appView.toastUser(message, "alert-danger", "Import:");
            }
            // $(self.el).find(".status").html(self.get("status"));
          },
          error: function(response) {
            var reason = {};
            if (response && response.responseJSON) {
              reason = response.responseJSON;
            } else {
              var message = "Error contacting the server. ";
              if (response.status >= 500) {
                message = message + " Please report this error.";
              } else if (response.status === 413) {
                message = message + " Your file is too big for upload, please try using FFMpeg to convert it to an mp3 for upload (you can still use your original video/audio in the app when the utterance chunking is done on an mp3.) ";
              } else {
                message = message + " Are you offline? If you are online and you still recieve this error, please report it to us: ";
              }
              reason = {
                status: response.status,
                userFriendlyErrors: [message + response.status]
              };
            }
            self.debug(reason);
            if (reason && reason.userFriendlyErrors) {
              self.status = "";
              self.error = "Upload error: " + reason.userFriendlyErrors.join(" ");
              self.bug(self.error);
              // if(window && window.appView && typeof window.appView.toastUser === "function") window.appView.toastUser(reason.userFriendlyErrors.join(" "), "alert-danger", "Import:");
              // $(self.el).find(".status").html(self.get("status"));
            }
            deferred.reject(self.error);
          }
        });
        self.status = "Contacting server...";
        // $(this.el).find(".status").html(this.model.get("status"));
 
      });
      return deferred.promise;
    }
  },
 
  downloadTextGrid: {
    value: function(fileDetails) {
      var self = this;
      var textridUrl = new AudioVideo().BASE_SPEECH_URL + "/" + this.corpus.dbname + "/" + fileDetails.fileBaseName + ".TextGrid";
      CORS.makeCORSRequest({
        url: textridUrl,
        type: "GET",
        withCredentials: false
      }).then(function(results) {
        if (results) {
          fileDetails.textgrid = results;
          var syllables = "unknown";
          if (fileDetails.syllablesAndUtterances && fileDetails.syllablesAndUtterances.syllableCount) {
            syllables = fileDetails.syllablesAndUtterances.syllableCount;
          }
          var pauses = "unknown";
          if (fileDetails.syllablesAndUtterances && fileDetails.syllablesAndUtterances.pauseCount) {
            pauses = parseInt(fileDetails.syllablesAndUtterances.pauseCount, 10);
          }
          var utteranceCount = 1;
          if (pauses > 0) {
            utteranceCount = pauses + 2;
          }
          var message = " Downloaded Praat TextGrid which contained a count of roughly " + syllables + " syllables and auto detected utterances for " + fileDetails.fileBaseName + " The utterances were not automatically transcribed for you, you can either save the textgrid and transcribe them using Praat, or continue to import them and transcribe them after.";
          fileDetails.description = message;
          self.status = self.status + "<br/>" + message;
          self.fileDetails = self.status + message;
          if (window && window.appView && typeof window.appView.toastUser === "function") {
            window.appView.toastUser(message, "alert-info", "Import:");
          }
          self.rawText = self.rawText.trim() + "\n\n\nFile name = " + fileDetails.fileBaseName + ".mp3\n" + results;
          if (!self.parent) {
            self.importTextGrid(self.rawText, null);
          } else {
            self.debug("Not showing second import step, this looks like its audio import only.");
          }
          fileDetails.filename = fileDetails.fileBaseName + ".mp3";
          fileDetails.URL = new AudioVideo().BASE_SPEECH_URL + "/" + self.corpus.dbname + "/" + fileDetails.fileBaseName + ".mp3";
          self.addAudioVideoFile(fileDetails);
          self.rawText = self.rawText.trim();
 
        } else {
          self.debug(results);
          fileDetails.textgrid = "Error result was empty. " + results;
        }
      }, function(response) {
        var reason = {};
        if (response && response.responseJSON) {
          reason = response.responseJSON;
        } else {
          var message = "Error contacting the server. ";
          if (response.status >= 500) {
            message = message + " Please report this error.";
          } else {
            message = message + " Are you offline? If you are online and you still recieve this error, please report it to us: ";
          }
          reason = {
            status: response.status,
            userFriendlyErrors: [message + response.status]
          };
        }
        self.debug(reason);
        if (reason && reason.userFriendlyErrors) {
          self.status = fileDetails.fileBaseName + "import error: " + reason.userFriendlyErrors.join(" ");
          if (window && window.appView && typeof window.appView.toastUser === "function") {
            window.appView.toastUser(reason.userFriendlyErrors.join(" "), "alert-danger", "Import:");
          }
        }
      }).fail(function(error) {
        console.error(error.stack, self);
      });
    }
  },
 
  addAudioVideoFile: {
    value: function(details) {
      if (!details) {
        this.warn("No details were provided to add be added to any file collection.");
        return;
      }
      var fileCollection = "relatedData";
      if (details.type.indexOf("image") > -1) {
        fileCollection = "images";
        details = new FieldDBImage(details);
      } else if (details.type.indexOf("audio") > -1 || details.type.indexOf("video") > -1) {
        fileCollection = "audioVideo";
      }
      if (!this[fileCollection]) {
        this[fileCollection] = new AudioVideos();
      }
      this[fileCollection].add(details);
      if (this.parent) {
        if (typeof this.parent.markAsNeedsToBeSaved === "function") {
          this.parent.markAsNeedsToBeSaved();
        }
        if (typeof this.parent.addFile === "function") {
          this.parent.addFile(details);
        } else if (this.parent.audioVideo && typeof this.parent.audioVideo.push === "function") {
          this.parent.audioVideo.push(details);
        } else {
          this.bug("There was a problem attaching this file. Please report this.");
        }
        this.render();
        // this.asCSV = [];
      }
    }
  },
 
  importTextGrid: {
    value: function(text, callback) {
      Iif (!text) {
        return;
      }
      // alert("The app thinks this might be a Praat TextGrid file, but we haven't implemented this kind of import yet. You can vote for it in our bug tracker.");
      var textgrid = TextGrid.textgridToIGT(text);
      var audioFileName = "copypastedtextgrid_unknownaudio";
      Iif (this.files && this.files[0] && this.files[0].name) {
        audioFileName = this.files[0].name;
      }
      audioFileName = audioFileName.replace(/\.textgrid/i, "");
      Iif (!textgrid || !textgrid.intervalsByXmin) {
        if (typeof callback === "function") {
          callback();
        }
      }
      var matrix = [],
        h,
        itemIndex,
        intervalIndex,
        row,
        interval;
      var header = [];
      var consultants = [];
      Iif (textgrid.isIGTNestedOrAlignedOrBySpeaker.probablyAligned) {
        for (itemIndex in textgrid.intervalsByXmin) {
          if (!textgrid.intervalsByXmin.hasOwnProperty(itemIndex)) {
            continue;
          }
          if (textgrid.intervalsByXmin[itemIndex]) {
            row = {};
            for (intervalIndex = 0; intervalIndex < textgrid.intervalsByXmin[itemIndex].length; intervalIndex++) {
              interval = textgrid.intervalsByXmin[itemIndex][intervalIndex];
              row.startTime = row.startTime ? row.startTime : interval.xmin;
              row.endTime = row.endTime ? row.endTime : interval.xmax;
              row.utterance = row.utterance ? row.utterance : interval.text.trim();
              row.modality = "spoken";
              row.tier = interval.tierName;
              row.speakers = interval.speaker;
              row.audioFileName = interval.fileName || audioFileName;
              row.CheckedWithConsultant = interval.speaker;
              consultants.push(row.speakers);
              row[interval.tierName] = interval.text;
              header.push(interval.tierName);
            }
            matrix.push(row);
          }
        }
      } else {
        for (itemIndex in textgrid.intervalsByXmin) {
          Iif (!textgrid.intervalsByXmin.hasOwnProperty(itemIndex)) {
            continue;
          }
          Eif (textgrid.intervalsByXmin[itemIndex]) {
            for (intervalIndex = 0; intervalIndex < textgrid.intervalsByXmin[itemIndex].length; intervalIndex++) {
              row = {};
              interval = textgrid.intervalsByXmin[itemIndex][intervalIndex];
              row.startTime = row.startTime ? row.startTime : interval.xmin;
              row.endTime = row.endTime ? row.endTime : interval.xmax;
              row.utterance = row.utterance ? row.utterance : interval.text.trim();
              row.modality = "spoken";
              row.tier = interval.tierName;
              row.speakers = interval.speaker;
              row.audioFileName = interval.fileName || audioFileName;
              row.CheckedWithConsultant = interval.speaker;
              consultants.push(row.speakers);
              row[interval.tierName] = interval.text;
              header.push(interval.tierName);
              matrix.push(row);
            }
          }
        }
      }
      header = getUnique(header);
      consultants = getUnique(consultants);
      Iif (consultants.length > 0) {
        this.consultants = consultants.join(",");
      } else {
        this.consultants = "Unknown";
      }
      header = header.concat(["utterance", "tier", "speakers", "CheckedWithConsultant", "startTime", "endTime", "modality", "audioFileName"]);
      var rows = [];
      for (var d in matrix) {
        var cells = [];
        //loop through all the column headings, find the data for that header and put it into a row of cells
        for (h in header) {
          var cell = matrix[d][header[h]];
          if (cell) {
            cells.push(cell);
          } else {
            //fill the cell with a blank if that datum didn't have a that column
            cells.push("");
          }
        }
        //if the datum has any text, add it to the table
        if (cells.length >= 8 && cells.slice(0, cells.length - 8).join("").replace(/[0-9.]/g, "").length > 0 && cells[cells.length - 8] !== "silent") {
          // cells.push(audioFileName);
          rows.push(cells);
        } else {
          this.debug("This row has only the default columns, not text or anything interesting.", cells);
        }
      }
      Iif (rows === []) {
        rows.push("");
      }
      // header.push("audioFileName");
      this.extractedHeaderObjects = header;
      this.asCSV = rows;
 
      Iif (typeof callback === "function") {
        callback();
      }
    }
  },
  importLatex: {
    value: function() {
      throw new Error("The app thinks this might be a LaTeX file, but we haven't implemented this kind of import yet. You can vote for it in our bug tracker.");
      // if (typeof callback === "function") {
      //   callback();
      // }
    }
  },
  /**
   * This function accepts text using double (or triple etc) spaces to indicate
   * separate datum. Each line in the block is treated as a column in
   * the table.
   *
   * If you have your data in Microsoft word or OpenOffice or plain
   * text, then this will be the easiest format for you to import your
   * data in.
   *
   * @param text
   */
  importTextIGT: {
    value: function(text, callback) {
      Eif (!text) {
        return;
      }
      var rows = text.split(/\n\n+/),
        l;
 
      var macLineEndings = false;
      if (rows.length < 3) {
        var macrows = text.split("\r\r");
        if (macrows.length > rows.length) {
          this.status = this.status + " Detected a MAC line ending.";
          macLineEndings = true;
          rows = macrows;
        }
      }
      for (l in rows) {
        if (macLineEndings) {
          rows[l] = rows[l].replace(/  +/g, " ").split("\r");
        } else {
          rows[l] = rows[l].replace(/  +/g, " ").split("\n");
        }
      }
      this.asCSV = rows;
      this.extractedHeaderObjects = rows[0];
      if (typeof callback === "function") {
        callback();
      }
    }
  },
  /**
   * This function accepts text using double (or triple etc) spaces to indicate
   * separate datum. Each line in the block is treated as a column in
   * the table.
   *
   * If you have your data in Microsoft word or OpenOffice or plain
   * text, then this will be the easiest format for you to import your
   * data in.
   *
   * @param text
   */
  importRawText: {
    value: function(text) {
      if (this.ignoreLineBreaksInRawText) {
        text.replace(/\n+/g, " ").replace(/\r+/g, " ");
      }
      this.datalist.add(new Datum({
        fields: [{
          id: "orthography",
          value: text
        }]
      }));
      this.debug("added a datum to the collection");
    }
  },
 
  /**
   * Reads the import's array of files using a supplied readOptions or using
   * the readFileIntoRawText function which uses the browsers FileReader API.
   * It can read only part of a file if start and stop are passed in the options.
   *
   * @param  Object options Options can be specified to pass start and stop bytes
   * for the files to be read.
   *
   * @return Promise Returns a promise which will have an array of results
   * for each file which was requested to be read
   */
  readFiles: {
    value: function(options) {
      var deferred = Q.defer(),
        self = this,
        promisses = [];
 
      options = options || {};
      this.progress = {
        total: 0,
        completed: 0
      };
      Q.nextTick(function() {
 
        var fileDetails = [];
        var files = self.files;
        var filesToUpload = [];
 
        self.progress.total = files.length;
        for (var i = 0, file; file = files[i]; i++) {
          var details = [escape(file.name), file.type || "n/a", "-", file.size, "bytes, last modified:", file.lastModifiedDate ? file.lastModifiedDate.toLocaleDateString() : "n/a"].join(" ");
          self.status = self.status + "; " + details;
          fileDetails.push(JSON.parse(JSON.stringify(file)));
          Iif (file.type && (file.type.indexOf("audio") > -1 || file.type.indexOf("video") > -1 || file.type.indexOf("image") > -1)) {
            filesToUpload.push(file);
          } else Eif (options.readOptions) {
            promisses.push(options.readOptions.readFileFunction.apply(self, [{
              file: file.name,
              start: options.start,
              stop: options.stop
            }]));
          } else {
            promisses.push(self.readFileIntoRawText({
              file: file,
              start: options.start,
              stop: options.stop
            }));
          }
        }
 
        Iif (filesToUpload.length > 0) {
          promisses.push(self.uploadFiles(self.files));
        }
        self.fileDetails = fileDetails;
 
        Q.allSettled(promisses).then(function(results) {
          deferred.resolve(results.map(function(result) {
            self.progress.completed += 1;
            return result.value;
          }));
        }, function(results) {
          self.error = "Error processing files";
          deferred.reject(results);
        }).fail(function(error) {
          console.error(error.stack, self);
          self.warn("There was an error when importing these options ", error, options);
          deferred.reject(error);
        });
 
      });
      return deferred.promise;
    }
  },
  /**
   * Reads a file using the FileReader API, can read only part of a file if start and stop are passed in the options.
   * @param  Object options Options can be specified to pass start and stop bytes for the file to be read.
   * @return Promise Returns a promise which will have an array of results for each file which was requested to be read
   */
  readFileIntoRawText: {
    value: function(options) {
      var deferred = Q.defer(),
        self = this;
 
      this.debug("readFileIntoRawText", options);
      Q.nextTick(function() {
        if (!options) {
          options = {
            error: "Options must be defined for readFileIntoRawText"
          };
          deferred.reject(options);
          return;
        }
        Eif (!options.file) {
          options.error = "Options: file must be defined for readFileIntoRawText";
          deferred.reject(options);
          return;
        }
        options.start = options.start ? parseInt(options.start, 10) : 0;
        options.stop = options.stop ? parseInt(options.stop, 10) : options.file.size - 1;
        var reader = new FileReader();
 
        // If we use onloadend, we need to check the readyState.
        reader.onloadend = function(evt) {
          if (evt.target.readyState === FileReader.DONE) { // DONE === 2
            options.rawText = evt.target.result;
            self.rawText = self.rawText + options.rawText;
            // self.showImportSecondStep = true;
            deferred.resolve(options);
          }
        };
 
        var blob = "";
        if (options.file.slice) {
          blob = options.file.slice(options.start, options.stop + 1);
        } else if (options.file.mozSlice) {
          blob = options.file.mozSlice(options.start, options.stop + 1);
        } else if (options.file.webkitSlice) {
          blob = options.file.webkitSlice(options.start, options.stop + 1);
        }
        // reader.readAsBinaryString(blob);
        // reader.readAsText(blob, "UTF-8");
        reader.readAsText(blob);
 
      });
      return deferred.promise;
    }
  },
  /**
   * This function attempts to guess the format of the file/textarea, and calls the appropriate import handler.
   */
  guessFormatAndPreviewImport: {
    value: function(fileIndex) {
      Eif (!fileIndex) {
        fileIndex = 0;
      }
 
      var importTypeConfidenceMeasures = {
        handout: {
          confidence: 0,
          id: "handout",
          importFunction: this.importTextIGT
        },
        csv: {
          confidence: 0,
          id: "csv",
          importFunction: this.importCSV
        },
        tabbed: {
          confidence: 0,
          id: "tabbed",
          importFunction: this.importTabbed
        },
        xml: {
          confidence: 0,
          id: "xml",
          importFunction: this.importXML
        },
        toolbox: {
          confidence: 0,
          id: "toolbox",
          importFunction: this.importToolbox
        },
        elanXML: {
          confidence: 0,
          id: "elanXML",
          importFunction: this.importElanXML
        },
        praatTextgrid: {
          confidence: 0,
          id: "praatTextgrid",
          importFunction: this.importTextGrid
        },
        latex: {
          confidence: 0,
          id: "latex",
          importFunction: this.importLatex
        }
 
      };
 
      //if the user is just typing, try raw text
      if (this.files && this.files[fileIndex]) {
        var fileExtension = this.files[fileIndex].name.split(".").pop().toLowerCase();
        Eif (fileExtension === "csv") {
          importTypeConfidenceMeasures.csv.confidence++;
        } else if (fileExtension === "txt") {
          //If there are more than 20 tabs in the file, try tabbed.
          if (this.rawText.split("\t").length > 20) {
            importTypeConfidenceMeasures.tabbed.confidence++;
          } else {
            importTypeConfidenceMeasures.handout.confidence++;
          }
        } else if (fileExtension === "eaf") {
          importTypeConfidenceMeasures.elanXML.confidence++;
        } else if (fileExtension === "xml") {
          importTypeConfidenceMeasures.xml.confidence++;
        } else if (fileExtension === "sf") {
          importTypeConfidenceMeasures.toolbox.confidence++;
        } else if (fileExtension === "tex") {
          importTypeConfidenceMeasures.latex.confidence++;
        } else if (fileExtension === "textgrid") {
          importTypeConfidenceMeasures.praatTextgrid.confidence++;
        } else if (fileExtension === "mov") {
          importTypeConfidenceMeasures.praatTextgrid.confidence++;
        } else if (fileExtension === "wav") {
          importTypeConfidenceMeasures.praatTextgrid.confidence++;
        } else if (fileExtension === "mp3") {
          importTypeConfidenceMeasures.praatTextgrid.confidence++;
        }
      } else {
        if (this.rawText && this.rawText.length) {
          var textLength = this.rawText.length;
          Iif (this.rawText.indexOf("\\gll") > -1 || this.rawText.indexOf("\\begin{") > -1 || this.rawText.indexOf("\\ex") > -1) {
            importTypeConfidenceMeasures.latex.confidence = 100;
          } else if (this.rawText.indexOf("mpi.nl/tools/elan/EAF") > -1) {
            importTypeConfidenceMeasures.elanXML.confidence = 100;
          } else if (this.rawText.indexOf("<?xml") > -1) {
            importTypeConfidenceMeasures.xml.confidence = 100;
          } else {
            importTypeConfidenceMeasures.csv.confidence = this.rawText.split(",").length / textLength;
            importTypeConfidenceMeasures.tabbed.confidence = this.rawText.split("\t").length / textLength;
            importTypeConfidenceMeasures.handout.confidence = this.rawText.split(/\n\n+/).length / textLength;
            importTypeConfidenceMeasures.toolbox.confidence = this.rawText.split(/\n\\/).length / textLength;
            importTypeConfidenceMeasures.praatTextgrid.confidence = this.rawText.split("intervals").length / textLength;
          }
        }
      }
      this.importTypeConfidenceMeasures = importTypeConfidenceMeasures;
      this.debug("importTypeConfidenceMeasures", importTypeConfidenceMeasures);
 
      var mostLikelyImport;
      for (var importType in importTypeConfidenceMeasures) {
        Iif (!importTypeConfidenceMeasures.hasOwnProperty(importType)) {
          continue;
        }
        if (!mostLikelyImport || mostLikelyImport.confidence < importTypeConfidenceMeasures[importType].confidence) {
          mostLikelyImport = importTypeConfidenceMeasures[importType];
        }
      }
 
      this.importTypeConfidenceMeasures.mostLikely = mostLikelyImport;
      this.status = "";
      return mostLikelyImport.importFunction.apply(this, [this.rawText, null]); //no callback
    }
  },
  readBlob: {
    value: function(file, callback, opt_startByte, opt_stopByte) {
      this.warn("Read blob is deprecated", file, callback, opt_startByte, opt_stopByte);
    }
  }
});
 
exports.Import = Import;