Code coverage report for api/FieldDBObject.js

Statements: 77.47% (822 / 1061)      Branches: 76.32% (651 / 853)      Functions: 82.2% (97 / 118)      Lines: 77.47% (822 / 1061)      Ignored: none     

All files » api/ » FieldDBObject.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      1 1 1 1 1                                                                                                                                                   1 141854 2 2         141852 120904   141852 379     379   141852         141852 60   141852 1052   141852 141852   141852 141852 1880052 551   1879501 1879501             4118     1875383   1879501 1879501         141852 141026   141852   141852 12523       1                                                                       1                           1 4632767     4632767 659497     1 1   1 1 1 1 1 1   1 44     1                                             1 1 23266 23266           23266 349 349   349 56   349 2   349 1         1 27 27 27 2   27     27         1                     1 24 24   24     24   24     1 306   306 306 13   306     306         1 28     28 27   27 9 9   18 18                                     18 18     27 7   27 8           19               28     1 6     6 5   5 2 2   3 3   3 3       5 2           3               6                     1 1367 10936   1367     1 3023       1                                               1 14733     14733 14733 14733 3 3   14733 14733 14733     14733 14728 30 30     14698   14698   14698 6 14692 366       14733 14733     1   134032     134032 13 13             13   13 11 2   2   2 2             134019   134019 155 133864 14 133850 1 133849 31       133818     9419     124399 124399 124399 14733 14733 14733   124399   124399 124308 212   124096     19 19     72 72 72 72       72   124187       1               847322     110280 22                         7097735 7096964   771       18     18       18         8442795 352           365893 365893                                   365893             87 74 56 56   18   13     31 31                                         27 8   19       38     38 1 1   37         28 9   19   28   28         6     6   6   6         305 101   204   305 305           56           514 95     419     30 1   29                 45 45           14462 14462         14462   14462 357   14105 104 104     14001           7514 7514         14001 922     14001 14001           34     474           16 5 5     11 11   11 11 3 3   8   11           11   11   11   11   11 11 11                                             11 11 11 11   11 11 11 11 11 11 11 11 11 11 11 11             11 11       11 11 1 10                 11         11       11   11               11 8 8 8   8 8   8 8 8 8 8 8   8 8       3   3 3   3 1   3                 3 3 3 3 2 2   3 3 3 3     11 5 5 1 4     5 1 1 1 1   1 1 1       11     11               17     17             17               17 4   13   13 4 4 4 4   4     13 1 1 1 1         1     12 1 1 1 1         1   11 1     11   11                       11 11 11                       11 11 11 11 11               11                   11   11 11   11 11   11 11 11                         11           2           2 2 2         2           1 1 1       1           1   1 1 1 1   1           33201 556947 147635 147635   409312 15     409297 20 9 9     9     409277 377169     32108 32004   104 42 42     42   62 62 62     62       33073 32920 16464 16464 16464 13     13       33060 33060 33060           588                     588         588     588 570 570 570 18 18 18 18           588 19 569       588 1 1 1   587 3 1 1 2             587 4110     2951   1159       587 3687     3067   620       587   587 22 22 22 1   22 22       4       4 4   4   4   17 17           22 22     587   3133         3133       3133 185 10 6 6 6     4 4   4   175 171 171 158   13 13         3133 20       3133 1921 1921     1921                       1212 1 1 1   1     1211 40 40 40 40     1171 65 65 65 1   65       1106 6 6     6   6 26 8           6 6       1100 1026 1022   4   1026 1026 1026 1026 1026       1026     74 74 74 22   74 58   1   57 42   57   57     16                                                         587           3     3 2 2 2   2     1                   1 1 1               1 1                     1           12     12         12 2 2 2         2     10 10   10 10 10 2 2             2     2 2   2       2 2             2 2   8 8 8 8 8           10                                   1395             160   160 21 21 139 107 107 32 9 9     23 23   23 23                       160 23     160     24       24 24           399289     6932 9   6923       6923 6923               6923           278     20     20       20 20   20           293518     5766 48   5718 1   5717 5344 5344   373 373   373           94 94     209 209           19 19       11           249158     358450 239105   119345     119345 119345   119345           6     9     9       9 7 7 7 7         9     9 9 9             3 3     20 20           108     12969 4   12965   6   12959 28 28 28 28         12959       12959           3 3     20 20           5     57 3   54 6 6   48 37 37 37 37         48                                         51     65     65       65 3     65           41462   41462           259134 259134           259134             259134       259134 238277   20857     259134 248481   259134 259134 259134 4067965 3557860 3557860 238593   3557860 3536894 9598   3527296             259134 237305 1662473 1187059 158   1186901           259134 3117   259134 238277     259134 259070   259134 189 189     259134 8551422 8551422 8551422       259134 259134 259134       259134 7724     259134 259134     259134 10593   259134                         1 1   1 1         1 1                   288     288 288                     288 3888 3888 22       288 288 8 8   8     8   8 8           8             288 288 288 288 288   288           219 212                             229829 229829     229829 229739   229829 229810 229810   229810 229810 229810 19 19                 109609 109609     109609 109596   109609 109609 109596             109596     109596 109596 18   109596   109596           1 1  
/* globals alert, confirm, prompt, navigator, Android, FieldDB */
"use strict";
 
var Diacritics = require("diacritics");
var Q = require("q");
var packageJson;
try {
  packageJson = require("./../package.json");
} catch (e) {
  console.log("failed to load package.json", e);
  packageJson = {
    version: "x.x.x"
  };
}
// var FieldDBDate = function FieldDBDate(options) {
//   // this.debug("In FieldDBDate ", options);
//   Object.apply(this, arguments);
//   if (options) {
//     this.timestamp = options;
//   }
// };
 
// FieldDBDate.prototype = Object.create(Object.prototype, /** @lends FieldDBDate.prototype */ {
//   constructor: {
//     value: FieldDBDate
//   },
 
//   timestamp: {
//     get: function() {
//       return this._timestamp || 0;
//     },
//     set: function(value) {
//       if (value === this._timestamp) {
//         return;
//       }
//       if (!value) {
//         delete this._timestamp;
//         return;
//       }
//       if (value.replace) {
//         try {
//           value = value.replace(/["\\]/g, "");
//           value = new Date(value);
//           /* Use date modified as a timestamp if it isnt one already */
//           value = value.getTime();
//         } catch (e) {
//           this.warn("Upgraded timestamp" + value);
//         }
//       }
//       this._timestamp = value;
//     }
//   },
 
//   toJSON: {
//     value: function(includeEvenEmptyAttributes, removeEmptyAttributes) {
//       var result = this._timestamp;
 
//       if (includeEvenEmptyAttributes) {
//         result = this._timestamp || 0;
//       }
 
//       if (removeEmptyAttributes && !this._timestamp) {
//         result = 0;
//       }
//       return result;
//     }
//   }
// });
 
/**
 * @class An extendable object which can recieve new parameters on creation.
 *
 * @param {Object} options Optional json initialization object
 * @property {String} dbname This is the identifier of the corpus, it is set when
 *           a corpus is created. It must be a file save name, and be a permitted
 *           name in CouchDB which means it is [a-z] with no uppercase letters or
 *           symbols, by convention it cannot contain -, but _ is acceptable.
 
 * @extends Object
 * @tutorial tests/FieldDBObjectTest.js
 */
var FieldDBObject = function FieldDBObject(json) {
  if (json && (json instanceof this.constructor || json.constructor.toString() === this.constructor.toString())) {
    json.debug("This was already the right type, not converting it.");
    return json;
  }
  // if (!this._fieldDBtype) {
  //   this._fieldDBtype = "FieldDBObject";
  // }
  if (json && json.id) {
    this.useIdNotUnderscore = true;
  }
  if (json && json.api && this.api) {
    Iif (json.api !== this.api) {
      console.log("Using " + this.api + " when the api of the incoming model was " + json.api);
    }
    delete json.api;
  }
  this.verbose("In parent an json", json);
  // Set the confidential first, so the rest of the fields can be encrypted
  // if (json && json.corpus) {
  //   this.corpus = json.corpus;
  // }
  if (json && json.confidential && this.INTERNAL_MODELS["confidential"]) {
    this.confidential = new this.INTERNAL_MODELS["confidential"](json.confidential);
  }
  if (json && json.fields && this.INTERNAL_MODELS["fields"]) {
    this.fields = new this.INTERNAL_MODELS["fields"](json.fields);
  }
  Eif (this.INTERNAL_MODELS) {
    this.debug("parsing with ", this.INTERNAL_MODELS);
  }
  var simpleModels = [];
  for (var member in json) {
    if (!json.hasOwnProperty(member)) {
      continue;
    }
    this.debug("JSON: " + member);
    if (json[member] &&
      this.INTERNAL_MODELS &&
      this.INTERNAL_MODELS[member] &&
      typeof this.INTERNAL_MODELS[member] === "function" &&
      !(json[member] instanceof this.INTERNAL_MODELS[member]) &&
      !(this.INTERNAL_MODELS[member].compatibleWithSimpleStrings && typeof json[member] === "string")) {
 
      json[member] = new this.INTERNAL_MODELS[member](json[member]);
 
    } else {
      simpleModels.push(member);
    }
    try {
      this[member] = json[member];
    } catch (e) {
      this.warn(e.stack);
    }
  }
  if (simpleModels.length > 0) {
    this.debug("simpleModels", simpleModels.join(", "));
  }
  Object.apply(this, arguments);
  // if (!this._rev) {
  if (!this.id && !this._dateCreated) {
    this.dateCreated = Date.now();
  }
 
};
FieldDBObject.internalAttributesToNotJSONify = [
  "$$hashKey",
  "application",
  "bugMessage",
  "confirmMessage",
  "confirmMergePromises",
  "contextualizer",
  "corpus",
  "currentDoc",
  "currentSession",
  "datalist",
  "database",
  "db",
  "debugMessages",
  "decryptedMode",
  "dontRecurse",
  "fetching",
  "fieldsInColumns",
  "fossil",
  "loaded",
  "loading",
  "newDatum",
  "parent",
  "perObjectAlwaysConfirmOkay",
  "perObjectDebugMode",
  "promptMessage",
  "saved",
  "saving",
  "selected",
  "temp",
  "unsaved",
  "useIdNotUnderscore",
  "warnMessage",
  "whenReady"
];
 
FieldDBObject.internalAttributesToAutoMerge = FieldDBObject.internalAttributesToNotJSONify.concat([
  "appVersionWhenCreated",
  "authServerVersionWhenCreated",
  "created_at",
  "dateCreated",
  "dateModified",
  "fieldDBtype",
  "modifiedByUser",
  "rev",
  "roles",
  "updated_at",
  "version"
]);
 
FieldDBObject.ignore = function(property, ignorelist) {
  Iif (!ignorelist) {
    throw new Error("missing the list of ignores");
  }
  if (ignorelist.indexOf(property) > -1 || ignorelist.indexOf(property.replace(/^_/, "")) > -1) {
    return true;
  }
};
FieldDBObject.software = {};
FieldDBObject.hardware = {};
 
FieldDBObject.DEFAULT_STRING = "";
FieldDBObject.DEFAULT_OBJECT = {};
FieldDBObject.DEFAULT_ARRAY = [];
FieldDBObject.DEFAULT_COLLECTION = [];
FieldDBObject.DEFAULT_VERSION = "v" + packageJson.version;
FieldDBObject.DEFAULT_DATE = 0;
 
FieldDBObject.render = function(options) {
  this.debug("Rendering, but the render was not injected for this " + this.fieldDBtype, options);
};
 
FieldDBObject.verbose = function(message, message2, message3, message4) {
  try {
    if (navigator && navigator.appName === "Microsoft Internet Explorer") {
      return;
    }
  } catch (e) {
    //do nothing, we are in node or some non-friendly browser.
  }
  if (this.verboseMode) {
    var type = this.fieldDBtype || this._id || "UNKNOWNTYPE";
    console.log(type.toUpperCase() + " VERBOSE: " + message);
 
    if (message2) {
      console.log(message2);
    }
    if (message3) {
      console.log(message3);
    }
    if (message4) {
      console.log(message4);
    }
  }
};
FieldDBObject.debugMode = false;
FieldDBObject.debug = function(message, message2, message3, message4) {
  try {
    if (navigator && navigator.appName === "Microsoft Internet Explorer") {
      return;
    }
  } catch (e) {
    //do nothing, we are in node or some non-friendly browser.
  }
  if (this.debugMode) {
    var type = this.fieldDBtype || this._id || "UNKNOWNTYPE";
    console.log(type.toUpperCase() + " DEBUG: " + message);
 
    if (message2) {
      console.log(message2);
    }
    if (message3) {
      console.log(message3);
    }
    if (message4) {
      console.log(message4);
    }
  }
};
 
FieldDBObject.todo = function(message, message2, message3, message4) {
  var type = this.fieldDBtype || this._id || "UNKNOWNTYPE";
  console.warn(type.toUpperCase() + " TODO: " + message);
  if (message2) {
    console.warn(message2);
  }
  Iif (message3) {
    console.warn(message3);
  }
  Iif (message4) {
    console.warn(message4);
  }
};
 
FieldDBObject.popup = function(message) {
  try {
    alert(message);
  } catch (e) {
    this.warn(" Couldn't tell user about a popup: " + message);
    // console.log("Alert is not defined, this is strange.");
  }
  var type = this.fieldDBtype || this._id || "UNKNOWNTYPE";
  console.log(type.toUpperCase() + " POPUP: " + message);
};
 
FieldDBObject.bug = function(message) {
  try {
    alert(message);
  } catch (e) {
    this.warn(" Couldn't tell user about a bug: " + message);
    // console.log("Alert is not defined, this is strange.");
  }
  var type = this.fieldDBtype || this._id || "UNKNOWNTYPE";
  //outputing a stack trace
  console.error(type.toUpperCase() + " BUG: " + message);
};
 
FieldDBObject.warn = function(message, message2, message3, message4) {
  var type = this.fieldDBtype || this._id || "UNKNOWNTYPE";
  // putting out a stacktrace
  console.warn(type.toUpperCase() + " WARN: " + message);
  if (message2) {
    console.warn(message2);
  }
  Iif (message3) {
    console.warn(message3);
  }
  Iif (message4) {
    console.warn(message4);
  }
};
 
FieldDBObject.prompt = function(message, optionalLocale, providedInput) {
  var deferred = Q.defer(),
    self = this;
 
  Q.nextTick(function() {
    var response;
 
    if (self.alwaysReplyToPrompt !== undefined) {
      response = providedInput || self.alwaysReplyToPrompt;
      console.warn(self.fieldDBtype.toUpperCase() + " NOT PROMPTING USER: " + message + " \nThe code decided that they would probably reply `" + response + "` and it wasnt worth prompting.");
    } else {
      try {
        response = prompt(message, providedInput);
 
        // Let the user enter info, even JSON
        if (response === "yes") {
          response = providedInput;
        } else if (response !== null) {
          if (typeof providedInput !== "string" && typeof providedInput !== "number") {
            try {
              var parsed = JSON.parse(response);
              response = parsed;
            } catch (e) {
              FieldDB.FieldDBObject.bug("There was a problem parsing your input.").then(function() {
                FieldDB.FieldDBObject.prompt(message, optionalLocale, providedInput);
              });
            }
          }
        }
 
      } catch (e) {
        response = null;
        console.warn(self.fieldDBtype.toUpperCase() + " UNABLE TO PROMPT USER: " + message + " pretending they said `" + response + "`");
      }
    }
    if (response !== null && response !== undefined && typeof response.trim === "function") {
      response = response.trim();
    }
    if (response) {
      deferred.resolve({
        message: message,
        optionalLocale: optionalLocale,
        response: response
      });
    } else {
      deferred.reject({
        message: message,
        optionalLocale: optionalLocale,
        response: response
      });
    }
 
  });
  return deferred.promise;
};
 
FieldDBObject.confirm = function(message, optionalLocale) {
  var deferred = Q.defer(),
    self = this;
 
  Q.nextTick(function() {
    var response;
 
    if (self.alwaysConfirmOkay) {
      console.warn(self.fieldDBtype.toUpperCase() + " NOT ASKING USER: " + message + " \nThe code decided that they would probably yes and it wasnt worth asking.");
      response = self.alwaysConfirmOkay;
    } else {
      try {
        response = confirm(message);
      } catch (e) {
        console.warn(self.fieldDBtype.toUpperCase() + " UNABLE TO ASK USER: " + message + " pretending they said " + self.alwaysConfirmOkay);
        response = self.alwaysConfirmOkay;
      }
    }
 
    if (response) {
      deferred.resolve({
        message: message,
        optionalLocale: optionalLocale,
        response: response
      });
    } else {
      deferred.reject({
        message: message,
        optionalLocale: optionalLocale,
        response: response
      });
    }
 
  });
  return deferred.promise;
};
/* set the application if you want global state (ie for checking if a user is authorized) */
// FieldDBObject.application = {}
 
/**
 * The uuid generator uses a "GUID" like generation to create a unique string.
 *
 * @returns {String} a string which is likely unique, in the format of a
 *          Globally Unique ID (GUID)
 */
FieldDBObject.uuidGenerator = function() {
  var S4 = function() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
  };
  return Date.now() + (S4() + S4() + S4() + S4() + S4() + S4() + S4() + S4());
};
 
FieldDBObject.regExpEscape = function(s) {
  return String(s).replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, "\\$1").
  replace(/\x08/g, "\\x08");
};
 
FieldDBObject.getHumanReadableTimestamp = function() {
  var today = new Date();
  var year = today.getFullYear();
  var month = today.getMonth() + 1;
  var day = today.getDate();
  var hour = today.getHours();
  var minute = today.getMinutes();
 
  if (month < 10) {
    month = "0" + month;
  }
  if (day < 10) {
    day = "0" + day;
  }
  if (hour < 10) {
    hour = "0" + hour;
  }
  if (minute < 10) {
    minute = "0" + minute;
  }
 
  return year + "-" + month + "-" + day + "_" + hour + "." + minute;
};
 
FieldDBObject.guessType = function(doc) {
  Iif (!doc || JSON.stringify(doc) === {}) {
    return "FieldDBObject";
  }
  FieldDBObject.debug("Guessing type " + doc._id);
  var guessedType = doc.previousFieldDBtype || doc.jsonType || doc.collection || "FieldDBObject";
  if (doc.api && doc.api.length > 0) {
    FieldDBObject.debug("using api" + doc.api);
    guessedType = doc.api[0].toUpperCase() + doc.api.substring(1, doc.api.length);
  }
  guessedType = guessedType.replace(/s$/, "");
  guessedType = guessedType[0].toUpperCase() + guessedType.substring(1, guessedType.length);
  Iif (guessedType === "Datalist") {
    guessedType = "DataList";
  }
  if (guessedType === "FieldDBObject") {
    if (doc.session) {
      guessedType = "Datum";
      Iif (doc.fields && doc.fields[0] === "judgement") {
        guessedType = "LanguageDatum";
      }
    } else Iif (doc.datumFields && doc.sessionFields) {
      guessedType = "Corpus";
    } else Iif (doc.collection === "sessions" && doc.sessionFields) {
      guessedType = "Session";
    } else if (doc.text && doc.username && doc.timestamp && doc.gravatar) {
      guessedType = "Comment";
    } else if (doc.symbol && doc.tipa !== undefined) {
      guessedType = "UnicodeSymbol";
    }
  }
 
  FieldDBObject.debug("Guessed type " + doc._id + " is a " + guessedType);
  return guessedType;
};
 
FieldDBObject.convertDocIntoItsType = function(doc, clone) {
  // this.debugMode = true;
  var guessedType,
    typeofAnotherObjectsProperty = Object.prototype.toString.call(doc);
 
  if (clone) {
    var cloneDoc;
    Iif (typeof doc.clone === "function") {
      // if (doc instanceof FieldDBObject || typeof doc.fuzzyFind === "function") {
      // wasnt able to make it what it should be, but it was at least some extension of FieldDBObject or Collection
      cloneDoc = doc.clone();
      doc = new doc.constructor(cloneDoc);
    } else
    // Return a clone of simple types, or a new clone of the json of this object
    Iif (typeofAnotherObjectsProperty === "[object Boolean]") {
      return !!doc;
    } else if (typeofAnotherObjectsProperty === "[object String]") {
      return doc + "";
    } else Iif (typeofAnotherObjectsProperty === "[object Number]") {
      return doc + 0;
    } else Iif (typeofAnotherObjectsProperty === "[object Date]") {
      return new Date(doc);
    } else Eif (typeofAnotherObjectsProperty === "[object Array]") {
      return doc.concat([]);
    } else {
      clone = doc.toJSON ? doc.toJSON() : doc;
      doc = new doc.constructor(clone);
    }
  } else {
    // Return the doc if its a simple type
    Iif (typeofAnotherObjectsProperty === "[object Boolean]") {
      return doc;
    } else if (typeofAnotherObjectsProperty === "[object String]") {
      return doc;
    } else if (typeofAnotherObjectsProperty === "[object Number]") {
      return doc;
    } else if (typeofAnotherObjectsProperty === "[object Date]") {
      return doc;
    } else if (typeofAnotherObjectsProperty === "[object Array]") {
      return doc;
    }
  }
 
  if (typeof doc.debug === "function" && doc.constructor !== FieldDBObject) {
    // if (doc instanceof FieldDBObject || typeof doc.fuzzyFind === "function") {
    // wasnt able to make it what it should be, but it was at least some extension of FieldDBObject or Collection
    return doc;
  }
 
  try {
    guessedType = doc.fieldDBtype;
    if (!guessedType || guessedType === "FieldDBObject") {
      FieldDBObject.debug(" requesting guess type ");
      guessedType = FieldDBObject.guessType(doc);
      FieldDBObject.debug("request complete");
    }
    FieldDBObject.debug("Converting doc into type " + guessedType);
 
    if (FieldDB && FieldDB[guessedType]) {
      if (doc instanceof FieldDB[guessedType]) {
        return doc;
      }
      doc = new FieldDB[guessedType](doc);
      // FieldDBObject.warn("Converting doc into guessed type " + guessedType);
    } else {
      doc = new FieldDBObject(doc);
      FieldDBObject.debug("This doc does not have a type than is known to the FieldDB system. It might display oddly ", doc);
    }
  } catch (e) {
    FieldDBObject.debug("Couldn't convert this doc to its type " + guessedType + ", it will be a base FieldDBObject: " + JSON.stringify(doc));
    FieldDBObject.debug(" error: ", e);
    var checkPreviousTypeWithoutS = doc.previousFieldDBtype ? doc.previousFieldDBtype.replace(/s$/, "") : "";
    Iif (guessedType !== "FieldDBObject" && guessedType !== checkPreviousTypeWithoutS) {
      doc.previousFieldDBtype = doc.previousFieldDBtype || "";
      doc.previousFieldDBtype = doc.previousFieldDBtype + guessedType;
    }
    doc = new FieldDBObject(doc);
  }
  return doc;
};
 
/** @lends FieldDBObject.prototype */
FieldDBObject.prototype = Object.create(Object.prototype, {
  constructor: {
    value: FieldDBObject
  },
 
  fieldDBtype: {
    configurable: true,
    get: function() {
      return this._fieldDBtype || "FieldDBObject";
    },
    set: function(value) {
      if (value !== this.fieldDBtype) {
        this.debug("Using type " + this.fieldDBtype + " when the incoming object was " + value);
      }
    }
  },
 
  /**
   * Can be set to true to debug all objects, or false to debug no objects and true only on the instances of objects which
   * you want to debug.
   *
   * @type {Boolean}
   */
  debugMode: {
    get: function() {
      if (this.perObjectDebugMode === undefined) {
        return false;
      } else {
        return this.perObjectDebugMode;
      }
    },
    set: function(value) {
      Iif (value === this.perObjectDebugMode) {
        return;
      }
      Iif (value === null || value === undefined) {
        delete this.perObjectDebugMode;
        return;
      }
      this.perObjectDebugMode = value;
    }
  },
  debug: {
    value: function( /* message, message2, message3, message4 */ ) {
      if (this.debugMode) {
        FieldDBObject.debug.apply(this, arguments);
      }
    }
  },
  verboseMode: {
    get: function() {
      Eif (this.perObjectVerboseMode === undefined) {
        return false;
      } else {
        return this.perObjectVerboseMode;
      }
    },
    set: function(value) {
      if (value === this.perObjectVerboseMode) {
        return;
      }
      if (value === null || value === undefined) {
        delete this.perObjectVerboseMode;
        return;
      }
      this.perObjectVerboseMode = value;
    }
  },
  verbose: {
    value: function( /* message, message2, message3, message4 */ ) {
      Iif (this.verboseMode) {
        FieldDBObject.verbose.apply(this, arguments);
      }
    }
  },
  bug: {
    value: function(message) {
      if (this.bugMessage) {
        if (this.bugMessage.indexOf(message) > -1) {
          this.warn("Not repeating bug message: " + message);
          return;
        }
        this.bugMessage += ";;; ";
      } else {
        this.bugMessage = "";
      }
 
      this.bugMessage = this.bugMessage + message;
      FieldDBObject.bug.apply(this, arguments);
    }
  },
  popup: {
    value: function(message) {
      if (this.popupMessage) {
        if (this.popupMessage.indexOf(message) > -1) {
          this.warn("Not repeating popup message: " + message);
          return;
        }
        this.popupMessage += ";;; ";
      } else {
        this.popupMessage = "";
      }
 
      this.popupMessage = this.popupMessage + message;
      FieldDBObject.popup.apply(this, arguments);
    }
  },
  alwaysConfirmOkay: {
    get: function() {
      if (this.perObjectAlwaysConfirmOkay === undefined) {
        return false;
      } else {
        return this.perObjectAlwaysConfirmOkay;
      }
    },
    set: function(value) {
      Iif (value === this.perObjectAlwaysConfirmOkay) {
        return;
      }
      if (value === null || value === undefined) {
        delete this.perObjectAlwaysConfirmOkay;
        return;
      }
      this.perObjectAlwaysConfirmOkay = value;
    }
  },
  prompt: {
    value: function(message) {
      if (this.promptMessage) {
        this.promptMessage += "\n";
      } else {
        this.promptMessage = "";
      }
      this.promptMessage = this.promptMessage + message;
 
      return FieldDBObject.prompt.apply(this, arguments);
    }
  },
  confirm: {
    value: function(message) {
      Iif (this.confirmMessage) {
        this.confirmMessage += "\n";
      } else {
        this.confirmMessage = "";
      }
      this.confirmMessage = this.confirmMessage + message;
 
      return FieldDBObject.confirm.apply(this, arguments);
    }
  },
  warn: {
    value: function(message) {
      if (this.warnMessage) {
        this.warnMessage += ";;; ";
      } else {
        this.warnMessage = "";
      }
      this.warnMessage = this.warnMessage + message;
      FieldDBObject.warn.apply(this, arguments);
    }
  },
 
  todo: {
    value: function( /* message, message2, message3, message4 */ ) {
      FieldDBObject.todo.apply(this, arguments);
    }
  },
 
  decryptedMode: {
    get: function() {
      if (this.application) {
        return this.application.decryptedMode;
      }
      // if not running in an app, dont need to demonstrate a mask the data if its decryptable
      return this._decryptedMode;
    },
    set: function(value) {
      if (this.application) {
        this.application.decryptedMode = value;
      } else {
        this._decryptedMode = value;
      }
    }
  },
 
  render: {
    configurable: true,
    writable: true,
    value: function(options) {
      this.debug("Calling render with options", options);
      FieldDBObject.render.apply(this, arguments);
    }
  },
 
  ensureSetViaAppropriateType: {
    value: function(propertyname, value, optionalInnerPropertyName) {
      this.debug("ensureSetViaAppropriateType on " + propertyname, this.INTERNAL_MODELS);
      Iif (!propertyname) {
        console.error("Invalid call to ensureSetViaAppropriateType", value);
        throw new Error("Invalid call to ensureSetViaAppropriateType");
      }
 
      optionalInnerPropertyName = optionalInnerPropertyName || "_" + propertyname;
 
      if (value === this[optionalInnerPropertyName]) {
        return this[optionalInnerPropertyName];
      }
      if (!value) {
        delete this[optionalInnerPropertyName];
        return;
      }
 
      if (this.INTERNAL_MODELS &&
        this.INTERNAL_MODELS[propertyname] &&
        typeof this.INTERNAL_MODELS[propertyname] === "function" &&
        !(value instanceof this.INTERNAL_MODELS[propertyname]) &&
        !(this.INTERNAL_MODELS[propertyname].compatibleWithSimpleStrings && typeof value === "string")) {
 
        this.debug("Converting this into  type for " + propertyname, value.constructor.toString());
        value = new this.INTERNAL_MODELS[propertyname](value);
 
      }
 
      // This trims all strings in the system...
      if (typeof value.trim === "function") {
        value = value.trim();
      }
 
      this[optionalInnerPropertyName] = value;
      return this[optionalInnerPropertyName];
    }
  },
 
  unsaved: {
    get: function() {
      return this._unsaved;
    },
    set: function(value) {
      this._unsaved = !!value;
    }
  },
 
  calculateUnsaved: {
    value: function() {
      if (!this.fossil) {
        this._unsaved = true;
        return;
      }
 
      var previous = new this.constructor(this.fossil);
      var current = new this.constructor(this.toJSON());
 
      current.debugMode = this.debugMode;
      if (previous.equals(current)) {
        this.warn("The " + this.id + " didnt actually change. Not marking as edited");
        this._unsaved = false;
      } else {
        this._unsaved = true;
      }
      return this._unsaved;
    }
  },
 
  createSaveSnapshot: {
    value: function(selfOrSnapshot, optionalUserWhoSaved) {
      var self = this;
 
      selfOrSnapshot = this;
 
      this.debug("    Running snapshot...");
      //update to selfOrSnapshot version
      selfOrSnapshot.version = FieldDBObject.DEFAULT_VERSION;
 
      try {
        FieldDBObject.software = FieldDBObject.software || {};
        FieldDBObject.software.appCodeName = navigator.appCodeName;
        FieldDBObject.software.appName = navigator.appName;
        FieldDBObject.software.appVersion = navigator.appVersion;
        FieldDBObject.software.cookieEnabled = navigator.cookieEnabled;
        FieldDBObject.software.doNotTrack = navigator.doNotTrack;
        FieldDBObject.software.hardwareConcurrency = navigator.hardwareConcurrency;
        FieldDBObject.software.language = navigator.language;
        FieldDBObject.software.languages = navigator.languages;
        FieldDBObject.software.maxTouchPoints = navigator.maxTouchPoints;
        FieldDBObject.software.onLine = navigator.onLine;
        FieldDBObject.software.platform = navigator.platform;
        FieldDBObject.software.product = navigator.product;
        FieldDBObject.software.productSub = navigator.productSub;
        FieldDBObject.software.userAgent = navigator.userAgent;
        FieldDBObject.software.vendor = navigator.vendor;
        FieldDBObject.software.vendorSub = navigator.vendorSub;
        if (navigator && navigator.geolocation && typeof navigator.geolocation.getCurrentPosition === "function") {
          navigator.geolocation.getCurrentPosition(function(position) {
            self.debug("recieved position information");
            FieldDBObject.software.location = position.coords;
          });
        }
      } catch (e) {
        this.debug("Error loading software ", e);
        FieldDBObject.software = FieldDBObject.software || {};
        FieldDBObject.software.version = process.version;
        FieldDBObject.software.appVersion = "PhantomJS unknown";
 
        try {
          var avoidmontagerequire = require;
          var os = avoidmontagerequire("os");
          FieldDBObject.hardware = FieldDBObject.hardware || {};
          FieldDBObject.hardware.endianness = os.endianness();
          FieldDBObject.hardware.platform = os.platform();
          FieldDBObject.hardware.hostname = os.hostname();
          FieldDBObject.hardware.type = os.type();
          FieldDBObject.hardware.arch = os.arch();
          FieldDBObject.hardware.release = os.release();
          FieldDBObject.hardware.totalmem = os.totalmem();
          FieldDBObject.hardware.cpus = os.cpus().length;
        } catch (e) {
          this.debug(" hardware is unknown.", e);
          FieldDBObject.hardware = FieldDBObject.hardware || {};
          FieldDBObject.software.appVersion = "Device unknown";
        }
      }
      Eif (!optionalUserWhoSaved) {
        optionalUserWhoSaved = {
          name: "",
          username: "unknown"
        };
        try {
          if (this.corpus && this.corpus.connectionInfo && this.corpus.connectionInfo.userCtx) {
            optionalUserWhoSaved.username = this.corpus.connectionInfo.userCtx.name;
          } else Iif (FieldDBObject.application && FieldDBObject.application.user && FieldDBObject.application.user.username) {
            optionalUserWhoSaved.username = optionalUserWhoSaved.username || FieldDBObject.application.user.username;
            optionalUserWhoSaved.gravatar = optionalUserWhoSaved.gravatar || FieldDBObject.application.user.gravatar;
          }
        } catch (e) {
          this.warn("Can't get the corpus connection info to guess who saved this.", e);
        }
      }
      // optionalUserWhoSaved._name = optionalUserWhoSaved.name || optionalUserWhoSaved.username || optionalUserWhoSaved.browserVersion;
      Iif (typeof optionalUserWhoSaved.toJSON === "function") {
        var asJson = optionalUserWhoSaved.toJSON();
        asJson.name = optionalUserWhoSaved.name;
        optionalUserWhoSaved = asJson;
      } else {
        optionalUserWhoSaved.name = optionalUserWhoSaved.name;
      }
      // optionalUserWhoSaved.browser = browser;
 
      this.debug("    Calculating userWhoSaved...");
 
      var userWhoSaved = {
        username: optionalUserWhoSaved.username,
        name: optionalUserWhoSaved.name,
        lastname: optionalUserWhoSaved.lastname,
        firstname: optionalUserWhoSaved.firstname,
        gravatar: optionalUserWhoSaved.gravatar
      };
 
      if (!selfOrSnapshot._rev) {
        selfOrSnapshot._dateCreated = Date.now();
        var enteredByUser = selfOrSnapshot.enteredByUser || {};
        Iif (selfOrSnapshot.fields && selfOrSnapshot.fields.enteredbyuser) {
          enteredByUser = selfOrSnapshot.fields.enteredbyuser;
        } else Eif (!selfOrSnapshot.enteredByUser) {
          selfOrSnapshot.enteredByUser = enteredByUser;
        }
        enteredByUser.value = userWhoSaved.name || userWhoSaved.username;
        enteredByUser.json = enteredByUser.json || {};
        enteredByUser.json.user = userWhoSaved;
        enteredByUser.json.software = FieldDBObject.software;
        try {
          enteredByUser.json.hardware = Android ? Android.deviceDetails : FieldDBObject.hardware;
        } catch (e) {
          this.debug("Cannot detect the hardware used for selfOrSnapshot save.", e);
          enteredByUser.json.hardware = FieldDBObject.hardware;
        }
 
      } else {
        selfOrSnapshot._dateModified = Date.now();
 
        var modifiedByUser = selfOrSnapshot.modifiedByUser || {};
        Iif (selfOrSnapshot.fields && selfOrSnapshot.fields.modifiedbyuser) {
          modifiedByUser = selfOrSnapshot.fields.modifiedbyuser;
        } else if (!selfOrSnapshot.modifiedByUser) {
          selfOrSnapshot.modifiedByUser = modifiedByUser;
        }
        Iif (selfOrSnapshot.modifiedByUsers) {
          modifiedByUser = {
            json: {
              users: selfOrSnapshot.modifiedByUsers
            }
          };
          delete selfOrSnapshot.modifiedByUsers;
        }
 
        modifiedByUser.value = modifiedByUser.value ? modifiedByUser.value + ", " : "";
        modifiedByUser.value += userWhoSaved.name || userWhoSaved.username;
        modifiedByUser.json = modifiedByUser.json || {};
        if (modifiedByUser.users) {
          modifiedByUser.json.users = modifiedByUser.users;
          delete modifiedByUser.users;
        }
        modifiedByUser.json.users = modifiedByUser.json.users || [];
        userWhoSaved.software = FieldDBObject.software;
        userWhoSaved.hardware = FieldDBObject.hardware;
        modifiedByUser.json.users.push(userWhoSaved);
      }
 
      if (FieldDBObject.software && FieldDBObject.software.location) {
        var location;
        if (selfOrSnapshot.location) {
          location = selfOrSnapshot.location;
        } else Iif (selfOrSnapshot.fields && selfOrSnapshot.fields.location) {
          location = selfOrSnapshot.fields.location;
        }
        if (location) {
          location.json = location.json || {};
          location.json.previousLocations = location.json.previousLocations || [];
          Eif (location.json && location.json.location && location.json.location.latitude) {
            location.json.previousLocations.push(location.json.location);
          }
          this.debug("overwriting location ", location);
          location.json.location = FieldDBObject.software.location;
          location.value = location.json.location.latitude + "," + location.json.location.longitude;
        }
      }
 
      this.debug("    Serializing to send object to selfOrSnapshotbase...");
      // this.debug("snapshot   ", selfOrSnapshot);
 
      return selfOrSnapshot.toJSON();
 
      // return selfOrSnapshot.toJSON ? selfOrSnapshot.toJSON() : selfOrSnapshot;
    }
  },
 
  save: {
    value: function(optionalUserWhoSaved, saveEvenIfSeemsUnchanged, optionalUrl) {
      var deferred = Q.defer(),
        self = this;
 
      Iif (this.fetching) {
        self.warn("Fetching is in process, can't save right now...");
        Q.nextTick(function() {
          deferred.reject("Fetching is in process, can't save right now...");
        });
        return deferred.promise;
      }
      Iif (this.saving) {
        self.warn("Save was already in process...");
        Q.nextTick(function() {
          deferred.reject("Fetching is in process, can't save right now...");
        });
        return deferred.promise;
      }
 
      if (saveEvenIfSeemsUnchanged) {
        this.debug("Not calculating if this object has changed, assuming it needs to be saved anyway.");
      } else {
        self.debug("    Checking to see if item needs to be saved.", saveEvenIfSeemsUnchanged, this.unsaved);
 
        if (!this.unsaved && !this.calculateUnsaved()) {
          self.warn("Item hasn't really changed, no need to save...");
          Q.nextTick(function() {
            deferred.resolve(self);
            return self;
          });
          return deferred.promise;
        }
      }
      if (!this.corpus || typeof this.corpus.set !== "function") {
        self.warn("The corpus for this doc isnt acessible, this is probably a bug.", this);
        Q.nextTick(function() {
          self.saving = false;
          deferred.reject({
            status: 406,
            userFriendlyErrors: ["This application has errored. Please notify its developers: Cannot save data, database is not currently opened."]
          });
        });
        return deferred.promise;
      }
 
      if (this.corpus.dbname !== this.dbname) {
        this.warn("This item belongs in the " + this.dbname + "database, not in the " + this.corpus.dbname + " database.");
        Q.nextTick(function() {
          self.saving = false;
          deferred.reject({
            status: 406,
            userFriendlyErrors: ["This item belongs in the " + self.dbname + "database, not in the " + self.corpus.dbname + " database."]
          });
        });
        return deferred.promise;
      }
      if (optionalUrl) {
        this.todo("Url for save was specified, but it is not being used. optionalUrl", optionalUrl);
      }
 
      var data = this.createSaveSnapshot();
 
      Iif (!data) {
        this.warn(" Can't save " + this.id + " right now. The JSON isnt ready.");
        Q.nextTick(function() {
          self.saving = false;
          deferred.reject({
            status: 406,
            userFriendlyErrors: ["Can't save " + this.id + " right now. Please wait."]
          });
        });
        return deferred.promise;
      }
 
      self.debug("    Requesting corpus to run save...");
      this.saving = true;
      this.whenReady = deferred.promise;
 
      // if (!confirm("save this?")) {
      //   this.warn("Pretending we saved, so we can see if load production models works, without affecting them ");
      //   Q.nextTick(function() {
      //     self.saving = false;
      //     self.rev = Date.now() + "notacutallysaved";
      //     deferred.resolve(self);
      //   });
      //   return deferred.promise;
      // }
 
      this.corpus.set(data).then(function(result) {
          self.saving = false;
          self.debug("    Save completed...");
          self.debug("saved ", result);
          Iif (!result) {
            deferred.reject({
              status: 400,
              userFriendlyErrors: ["This application has errored. Please notify its developers: Cannot save data."]
            });
            return "self";
          }
 
          Iif (!result.id) {
            self.debug("    Rejecting promise, the id was not set by the database ..");
            deferred.reject({
              status: 500,
              userFriendlyErrors: ["This application has errored. Please notify its developers: Save operation returned abnormal results."],
              details: result
            });
            return self;
          }
 
          self.unsaved = false;
 
          self.id = result.id;
          self.rev = result.rev;
 
          self.debug("    Updating fossil...");
          self.fossil = self.toJSON();
 
          self.debug("    Resolving promise...", self);
          deferred.resolve(self);
          return self;
        },
        function(reason) {
          self.debug(reason);
          self.saving = false;
          deferred.reject(reason);
          return self;
        }).fail(
        function(error) {
          console.error(error.stack, self);
          deferred.reject(error);
        });
 
      return deferred.promise;
    }
  },
 
  delete: {
    value: function(reason) {
      return this.trash(reason);
    }
  },
 
  trash: {
    value: function(reason) {
      this.trashed = "deleted";
      Eif (reason) {
        this.trashedReason = reason;
      } else {
        this.todo("consider using a confirm to ask for a reason for deleting the item");
      }
 
      return this.save(null, "forcesavesinceweneedtopersistthischange");
    }
  },
 
  undelete: {
    value: function(reason) {
      this.trashed = "restored";
      Eif (reason) {
        this.untrashedReason = reason;
      } else {
        this.todo("consider using a confirm to ask for a reason for undeleting the item");
      }
      return this.save(null, "forcesavesinceweneedtopersistthischange");
    }
  },
 
  saveToGit: {
    value: function(commit, saveEvenIfSeemsUnchanged) {
      var deferred = Q.defer(),
        self = this;
      Q.nextTick(function() {
        self.todo("If in nodejs, write to file and do a git commit with optional user's email who modified the file and push ot a branch with that user's username", saveEvenIfSeemsUnchanged);
        self.debug("Commit to be used: ", commit);
        deferred.resolve(self);
      });
      return deferred.promise;
    }
  },
 
  equals: {
    value: function(anotherObject) {
      for (var aproperty in this) {
        if (!this.hasOwnProperty(aproperty) || typeof this[aproperty] === "function" || FieldDBObject.ignore(aproperty, FieldDBObject.internalAttributesToAutoMerge)) {
          this.debug("skipping equality of " + aproperty);
          continue;
        }
        if (!anotherObject) {
          return false;
        }
 
        if /* use fielddb equality function first */ (this[aproperty] && typeof this[aproperty].equals === "function") {
          if (!this[aproperty].equals(anotherObject[aproperty])) {
            this.debug("  " + aproperty + ": ", this[aproperty], " not equalivalent to ", anotherObject[aproperty]);
            Iif (this.debugMode) {
              console.error("objects are not equal stactrace");
            }
            return false;
          }
        } /* then try normal equality */
        else if (this[aproperty] === anotherObject[aproperty]) {
          this.debug(aproperty + ": " + this[aproperty] + " equals " + anotherObject[aproperty]);
          // return true;
        } /* then try stringification */
        else if (JSON.stringify(this[aproperty]) === JSON.stringify(anotherObject[aproperty])) {
          this.debug(aproperty + ": " + this[aproperty] + " equals " + anotherObject[aproperty]);
          // return true;
        } else if (anotherObject[aproperty] === undefined && (aproperty !== "_dateCreated" && aproperty !== "perObjectDebugMode")) {
          this.debug(aproperty + " is missing " + this[aproperty] + " on anotherObject " + anotherObject[aproperty]);
          Iif (this.debugMode) {
            console.error("objects are not equal stactrace");
          }
          return false;
        } else {
          Eif (aproperty !== "_dateCreated" && aproperty !== "perObjectDebugMode") {
            this.debug(aproperty + ": ", this[aproperty], " not equal ", anotherObject[aproperty]);
            Iif (this.debugMode) {
              console.error("objects are not equal stactrace");
            }
            return false;
          }
        }
      }
      if (typeof anotherObject.equals === "function") {
        if (this.dontRecurse === undefined) {
          this.dontRecurse = true;
          anotherObject.dontRecurse = true;
          if (!anotherObject.equals(this)) {
            Iif (this.debugMode) {
              console.error("objects are not equal stactrace");
            }
            return false;
          }
        }
      }
      delete this.dontRecurse;
      delete anotherObject.dontRecurse;
      return true;
    }
  },
 
  merge: {
    value: function(callOnSelf, anotherObject, optionalOverwriteOrAsk) {
      var anObject,
        resultObject,
        aproperty,
        targetPropertyIsEmpty,
        overwrite,
        localCallOnSelf,
        propertyList = {},
        json;
 
      // this.debugMode = true;
 
      Iif (arguments.length === 0) {
        this.warn("Invalid call to merge, there was no object provided to merge");
        return null;
      }
 
      Iif (!anotherObject && !optionalOverwriteOrAsk) {
        resultObject = anObject = this;
        anotherObject = FieldDBObject.convertDocIntoItsType(callOnSelf);
      } else if (callOnSelf === "self") {
        this.debug("Merging properties into myself. ");
        anObject = this;
        resultObject = anObject;
      } else Eif (callOnSelf && anotherObject) {
        anObject = FieldDBObject.convertDocIntoItsType(callOnSelf);
        anotherObject = FieldDBObject.convertDocIntoItsType(anotherObject);
        resultObject = this;
      } else {
        this.warn("Invalid call to merge, invalid arguments were provided to merge", arguments);
        return null;
      }
 
      if (!optionalOverwriteOrAsk) {
        optionalOverwriteOrAsk = "";
      } else Iif (optionalOverwriteOrAsk === true) {
        optionalOverwriteOrAsk = "overwrite";
      }
 
      if (anObject.id && anotherObject.id && anObject.id !== anotherObject.id) {
        this.warn("Refusing to merge these objects, they have different ids: " + anObject.id + "  and " + anotherObject.id);
        this.debug("Refusing to merge" + anObject.id + "  and " + anotherObject.id, anObject, anotherObject);
        return null;
      }
      if (anObject.dbname && anotherObject.dbname && anObject.dbname !== anotherObject.dbname) {
        if (optionalOverwriteOrAsk.indexOf("keepDBname") > -1) {
          this.warn("Permitting a merge of objects from different databases: " + anObject.dbname + "  and " + anotherObject.dbname);
          this.debug("Merging ", anObject, anotherObject);
        } else Iif (optionalOverwriteOrAsk.indexOf("changeDBname") === -1) {
          this.warn("Refusing to merge these objects, they come from different databases: " + anObject.dbname + "  and " + anotherObject.dbname);
          this.debug("Refusing to merge" + anObject.dbname + "  and " + anotherObject.dbname, anObject, anotherObject);
          return null;
        }
      }
 
      for (aproperty in anObject) {
        if (anObject.hasOwnProperty(aproperty) &&
          typeof anObject[aproperty] !== "function" &&
          !FieldDBObject.ignore(aproperty, FieldDBObject.internalAttributesToNotJSONify)) {
          propertyList[aproperty] = true;
        } else {
          this.debug("Not merging " + aproperty, "parent ", anObject.parent ? anObject.parent.length : "");
        }
      }
 
      for (aproperty in anotherObject) {
        if (anotherObject.hasOwnProperty(aproperty) &&
          typeof anotherObject[aproperty] !== "function" &&
          !FieldDBObject.ignore(aproperty, FieldDBObject.internalAttributesToNotJSONify)) {
          propertyList[aproperty] = true;
        } else {
          this.debug("Not merging " + aproperty, "parent ", anObject.parent ? anObject.parent.length : "");
        }
      }
 
      this.debug(" Merging properties: " + this.id, propertyList);
 
      var handleAsyncConfirmMerge = function(self, apropertylocal) {
        var deferred = Q.defer();
        var promptInputText = anotherObject[apropertylocal];
        if (typeof promptInputText === "object") {
          promptInputText = JSON.stringify(anotherObject[apropertylocal]);
        }
        var context = self.id || self._id || "";
        self.prompt(context + " I found a conflict for " + apropertylocal + ", Do you want to overwrite it from " + JSON.stringify(anObject[apropertylocal]) + " -> " + promptInputText, null, promptInputText)
          .then(function(reply) {
            // Let the user enter the value they would like
 
            Iif (apropertylocal === "_dbname" && optionalOverwriteOrAsk.indexOf("keepDBname") > -1) {
              // resultObject._dbname = self.dbname;
              self.warn(" Keeping _dbname of " + resultObject.dbname);
            } else {
              self.debug("Async Overwriting contents of " + apropertylocal + " (this may cause disconnection in listeners)");
              self.debug("Async Overwriting  ", anObject[apropertylocal], " ->", reply.response);
 
              resultObject[apropertylocal] = reply.response;
            }
            deferred.resolve(reply);
          }, function(reason) {
            resultObject[apropertylocal] = anObject[apropertylocal];
            deferred.reject(reason);
          }).fail(function(error) {
            console.error(error.stack, self);
            deferred.reject(error);
          });
 
        self.confirmMergePromises = self.confirmMergePromises || [];
        self.confirmMergePromises.push(deferred.promise);
      };
 
      for (aproperty in propertyList) {
 
        Iif (typeof anObject[aproperty] === "function" || typeof anotherObject[aproperty] === "function") {
          this.debug("  Ignoring ---" + aproperty + "----");
          continue;
        }
        // if (this.debugMode) {
        this.debug("  Merging ---" + aproperty + "--- \n   :::" + JSON.stringify(resultObject[aproperty]) + ":::\n   :::" + JSON.stringify(anObject[aproperty]) + ":::\n   :::" + JSON.stringify(anotherObject[aproperty]) + ":::");
        // }
 
        // if the result is missing the property, clone it from anObject or anotherObject
        if (resultObject[aproperty] === undefined || resultObject[aproperty] === null) {
          if (anObject[aproperty] !== undefined && anObject[aproperty] !== null) {
            if (typeof anObject[aproperty] !== "string" && typeof anObject[aproperty].constructor === "function") {
              json = anObject[aproperty].toJSON ? anObject[aproperty].toJSON() : anObject[aproperty];
              resultObject[aproperty] = new anObject[aproperty].constructor(json);
              this.debug(" " + aproperty + " resultObject will have anObject's Cloned contents because it was empty");
            } else {
              /* jshint eqeqeq:false */
              Eif (resultObject[aproperty] != anObject[aproperty]) {
                resultObject[aproperty] = anObject[aproperty];
              }
              this.debug(" " + aproperty + " resultObject will have anObject's contents because it was empty");
            }
          } else if (anotherObject[aproperty] !== undefined && anotherObject[aproperty] !== null) {
            this.debug("Using a constructor");
            if (callOnSelf === "self") {
              resultObject[aproperty] = FieldDBObject.convertDocIntoItsType(anotherObject[aproperty]);
            } else {
              this.debug("use clone only if not merging self.");
              resultObject[aproperty] = FieldDBObject.convertDocIntoItsType(anotherObject[aproperty], "clone");
            }
          }
          // dont continue, instead let the iffs run
        }
        if (this.debugMode) {
          this.debug("  Merging ---" + aproperty + "--- \n   :::" + JSON.stringify(resultObject[aproperty]) + ":::\n   :::" + JSON.stringify(anObject[aproperty]) + ":::\n   :::" + JSON.stringify(anotherObject[aproperty]) + ":::");
        }
 
        /* jshint eqeqeq:false */
        if (anObject[aproperty] == anotherObject[aproperty]) {
          this.debug(aproperty + " were equal or had no conflict.");
          Iif (resultObject[aproperty] != anObject[aproperty]) {
            resultObject[aproperty] = anObject[aproperty];
          }
          continue;
        }
 
        // Don't bother with equivalentcy, we will merge the internal elements recursively if they are not equivalent so this doesn't save time.
        // if (anObject[aproperty] && typeof anObject[aproperty].equals === "function" && anObject[aproperty].equals(anotherObject[aproperty])) {
        //   this.debug(aproperty + " were equivalent or had no conflict.");
        //   if (!anObject[aproperty].equals(resultObject[aproperty])) {
        //     if(resultObject[aproperty] != anObject[aproperty]){resultObject[aproperty] = anObject[aproperty];}
        //   }
        //   continue;
        // }
 
        if ((anotherObject[aproperty] === undefined || anotherObject[aproperty] === null) && resultObject[aproperty] != anObject[aproperty]) {
          this.debug(aproperty + " was missing in new object, using the original");
          Eif (resultObject[aproperty] != anObject[aproperty]) {
            resultObject[aproperty] = anObject[aproperty];
          }
          continue;
        }
 
        if (anotherObject[aproperty] && (anObject[aproperty] === undefined || anObject[aproperty] === null || anObject[aproperty] === [] || anObject[aproperty].length === 0 || anObject[aproperty] === {})) {
          targetPropertyIsEmpty = true;
          this.debug(aproperty + " was previously empty, taking the new value");
          resultObject[aproperty] = anotherObject[aproperty];
          continue;
        }
 
        if ((anObject[aproperty] !== undefined || anObject[aproperty] !== null) && (anotherObject[aproperty] === undefined || anotherObject[aproperty] === null || anotherObject[aproperty] === [] || anotherObject[aproperty].length === 0 || anotherObject[aproperty] === {})) {
          targetPropertyIsEmpty = true;
          this.debug(aproperty + " target is empty, taking the old value");
          if (resultObject[aproperty] != anObject[aproperty]) {
            resultObject[aproperty] = anObject[aproperty];
          }
          continue;
        }
 
        //  if two arrays: concat
        if (Object.prototype.toString.call(anObject[aproperty]) === "[object Array]" && Object.prototype.toString.call(anotherObject[aproperty]) === "[object Array]") {
          this.debug(aproperty + " was an array, concatinating with the new value", anObject[aproperty], " ->", anotherObject[aproperty]);
          resultObject[aproperty] = anObject[aproperty].concat([]);
 
          // only add the ones that were missing (dont remove any. merge wont remove stuff, only add.)
          try {
            /* jshint loopfunc:true */
            anotherObject[aproperty].map(function(item) {
              if (resultObject[aproperty].indexOf(item) === -1) {
                resultObject[aproperty].push(item);
              }
            });
          } catch (e) {
            console.warn("problem merging this array " + aproperty, e);
          }
          this.debug("  added members of anotherObject " + aproperty + " to anObject ", resultObject[aproperty]);
          continue;
        }
 
        // if two objects with merge function: recursively merge
        if (resultObject[aproperty] && typeof resultObject[aproperty].merge === "function") {
          if (callOnSelf === "self") {
            localCallOnSelf = callOnSelf;
          } else {
            localCallOnSelf = anObject[aproperty];
          }
          this.debug("Requesting recursive merge of internal property " + aproperty + " using method: " + localCallOnSelf);
          try {
            var result = resultObject[aproperty].merge(localCallOnSelf, anotherObject[aproperty], optionalOverwriteOrAsk);
            this.debug("after internal merge ", result);
            this.debug("after internal merge ", resultObject[aproperty]);
          } catch (e) {
            console.warn("problem merging this " + aproperty, e.stack);
          }
          continue;
        }
 
        overwrite = optionalOverwriteOrAsk;
        this.debug("Found conflict for " + aproperty + " Requested with " + optionalOverwriteOrAsk + " " + optionalOverwriteOrAsk.indexOf("overwrite"));
        if (optionalOverwriteOrAsk.indexOf("overwrite") === -1 && !FieldDBObject.ignore(aproperty, FieldDBObject.internalAttributesToAutoMerge)) {
          handleAsyncConfirmMerge(this, aproperty);
        }
        if (overwrite || FieldDBObject.ignore(aproperty, FieldDBObject.internalAttributesToAutoMerge)) {
          if (aproperty === "_dbname" && optionalOverwriteOrAsk.indexOf("keepDBname") > -1) {
            // resultObject._dbname = this.dbname;
            this.warn(" Keeping _dbname of " + resultObject.dbname);
          } else {
            if (!FieldDBObject.ignore(aproperty, FieldDBObject.internalAttributesToAutoMerge)) {
              this.debug("Overwriting contents of " + aproperty + " (this may cause disconnection in listeners)");
            }
            this.debug("Overwriting  ", anObject[aproperty], " ->", anotherObject[aproperty]);
 
            resultObject[aproperty] = anotherObject[aproperty];
          }
        } else {
          Iif (resultObject[aproperty] != anObject[aproperty]) {
            resultObject[aproperty] = anObject[aproperty];
          }
        }
 
        // TODO rewrite this function
        // if (overwrite || FieldDBObject.ignore(aproperty, FieldDBObject.internalAttributesToAutoMerge)) {
        //   if (aproperty === "_dbname" && optionalOverwriteOrAsk.indexOf("keepDBname") > -1) {
        //     // resultObject._dbname = this.dbname;
        //     this.warn(" Keeping _dbname of " + resultObject.dbname);
        //   } else {
        //     if (optionalOverwriteOrAsk.indexOf("ignore") > -1  || !FieldDBObject.ignore(aproperty, FieldDBObject.internalAttributesToAutoMerge)) {
        //       this.debug("Overwriting contents of " + aproperty + " (this may cause disconnection in listeners)");
        //     }
        //     this.debug("Overwriting  ", anObject[aproperty], " ->", anotherObject[aproperty]);
 
        //     resultObject[aproperty] = anotherObject[aproperty];
        //   }
        // } else if (optionalOverwriteOrAsk.indexOf("ignore") > -1 && !FieldDBObject.ignore(aproperty, FieldDBObject.internalAttributesToAutoMerge)) {
        //   return resultObject;
        // } else if (optionalOverwriteOrAsk.indexOf("overwrite") === -1) {
        //   handleAsyncConfirmMerge(this, aproperty);
        // } else  {
        //   // if (resultObject[aproperty] != anObject[aproperty]) {
        //   //   resultObject[aproperty] = anObject[aproperty];
        //   // }
        // }
      }
 
      return resultObject;
    }
  },
 
  fetchRevisions: {
    value: function(optionalUrl) {
      var deferred = Q.defer(),
        self = this;
 
      if (!this._id) {
        Q.nextTick(function() {
          self.warn("This hasn't been saved before, so there are no previous revisisons to show you.");
          deferred.resolve(self._revisions);
        });
        return deferred.promise;
      }
 
      Iif (!this.corpus || typeof this.corpus.fetchRevisions !== "function") {
        Q.nextTick(function() {
          deferred.reject({
            status: 406,
            userFriendlyErrors: ["This application has errored. Please notify its developers: Cannot fetch data if the database is not currently opened."]
          });
        });
        return deferred.promise;
      }
 
      self.corpus.fetchRevisions(this.id, optionalUrl).then(function(revisions) {
        Eif (!self._revisions) {
          self._revisions = revisions;
        } else {
          revisions.map(function(revision) {
            if (self._revisions.indexOf(revision) === -1) {
              self._revisions.push(revision);
            }
          });
        }
        self.debug("This " + self.id + " has " + self._revisions.length + " previous revisions");
        deferred.resolve(self._revisions);
      }, function(reason) {
        self.warn("Unable to update list of revisions currently.");
        self.debug(reason);
        deferred.reject(reason);
        return self;
      }).fail(function(error) {
        console.error(error.stack, self);
        deferred.reject(error);
      });
 
      return deferred.promise;
    }
  },
 
  fetch: {
    value: function(optionalUrl) {
      var deferred = Q.defer(),
        self = this;
 
      Iif (this.fetching && this.whenReady) {
        self.warn("Fetching is in process, don't need to fetch right now...");
        return this.whenReady;
      }
 
      if (!this.corpus || typeof this.corpus.get !== "function" || !this._id) {
        Q.nextTick(function() {
          self.fetching = self.loading = false;
          deferred.reject({
            status: 406,
            userFriendlyErrors: ["This application has errored. Please notify its developers: Cannot fetch data which has no id, or the if database is not currently opened."]
          });
        });
        return deferred.promise;
      }
 
      this.todo("Should probably call save before fetch to create a snapshot of the item regardless of whether the save is completeable, ");
      var oldRev = this.rev;
 
      this.fetching = this.loading = true;
      this.whenReady = deferred.promise;
      self.corpus.get(self.id, optionalUrl).then(function(result) {
        self.fetching = self.loading = false;
        Iif (!result) {
          deferred.reject({
            status: 400,
            userFriendlyErrors: ["This application has errored. Please notify its developers: Cannot fetch data url."]
          });
          return self;
        }
        self.loaded = true;
 
        // If this had no revision number before, and it does now, then this is a good fossil point
        Eif (!oldRev && (result._rev || result.rev)) {
          self.warn(self.id + " was probabbly a placeholder (didnt have .rev before fetch, but now it does) which is now filled in, calling merge with overwrite from server.");
 
          self.merge("self", FieldDBObject.convertDocIntoItsType(result), "overwrite");
          // Setting the fossil causes
          // A: the merge to count as something which needs to be seaved
          // B: the user's previous changes prior to fetch might get lost
          self.fossil = self.toJSON();
          self.unsaved = false;
        } else {
          self.warn("Cant tell if this was a placeholder, calling merge and asking user if there are merge conflicts.", result);
          self.merge("self", result);
          self.debug("After merge ", self.modifiedByUser);
        }
 
        deferred.resolve(self);
        return self;
      }, function(reason) {
        self.fetching = self.loading = false;
        self.loaded = false;
        self.debug("failed to fetch", reason);
        deferred.reject(reason);
        return self;
      }).fail(function(error) {
        console.error(error.stack, self);
        deferred.reject(error);
      });
 
      return deferred.promise;
    }
  },
 
  INTERNAL_MODELS: {
    value: {
      _id: FieldDBObject.DEFAULT_STRING,
      _rev: FieldDBObject.DEFAULT_STRING,
      dbname: FieldDBObject.DEFAULT_STRING,
      version: FieldDBObject.DEFAULT_STRING,
      dateCreated: FieldDBObject.DEFAULT_DATE,
      dateModified: FieldDBObject.DEFAULT_DATE,
      comments: FieldDBObject.DEFAULT_COLLECTION
    }
  },
 
  application: {
    get: function() {
      return FieldDBObject.application;
    },
    set: function() {}
  },
 
  corpus: {
    get: function() {
      var db = null;
      // this.debugMode = true;
      if (this.resumeAuthenticationSession && typeof this.resumeAuthenticationSession === "function") {
        db = this;
        this.debug("this " + this._id + " has the functions of a corpus, using it.", db);
      } else if (this._corpus) {
        db = this._corpus;
        this.debug("this " + this._id + " has a _corpus hard coded inside it, using it.", db);
      } else if (FieldDBObject.application && FieldDBObject.application._corpus) {
        db = FieldDBObject.application._corpus;
        this.debug("this " + this._id + " is running in the context where FieldDBObject.application._corpus is defined, using it.", db);
      } else {
 
        try {
          Eif (FieldDB && FieldDB["Database"]) {
            // db = FieldDB["Database"].prototype;
            this.debug("  using the Database.prototype to run db calls for " + this._id + ", this could be problematic " + this._id + " .");
            this.debug(" the database", db);
          }
        } catch (e) {
          var message = e ? e.message : " unknown error in getting the corpus";
          if (message !== "FieldDB is not defined") {
            this.warn(this._id + "Cant get the corpus, cant find the Database class.", e);
            if (e) {
              this.warn("  stack trace" + e.stack);
            }
          }
        }
      }
      if (!db) {
        this.warn("Operations that need a corpus/database wont work for the " + this._id + " object");
      }
 
      return db;
    },
    set: function(value) {
      Iif (value && value.dbname && this.dbname && value.dbname !== this.dbname) {
        this.warn("The corpus " + value.db + " cant be set on this item, its db is different" + this.dbname);
        return;
      }
      this.debug("setting corpus ", value);
      this._corpus = value;
    }
  },
 
  id: {
    get: function() {
      return this._id || FieldDBObject.DEFAULT_STRING;
    },
    set: function(value) {
      if (value === this._id) {
        return;
      }
      Iif (!value) {
        delete this._id;
        return;
      }
      Eif (value.trim) {
        value = value.trim();
      }
      // var originalValue = value + "";
      // value = this.sanitizeStringForPrimaryKey(value); /*TODO dont do this on all objects */
      // if (value === null) {
      //   this.bug("Invalid id, not using " + originalValue + " id remains as " + this._id);
      //   return;
      // }
      this._id = value;
    }
  },
 
  rev: {
    get: function() {
      return this._rev || FieldDBObject.DEFAULT_STRING;
    },
    set: function(value) {
      Iif (value === this._rev) {
        return;
      }
      Iif (!value) {
        delete this._rev;
        return;
      }
      Eif (value.trim) {
        value = value.trim();
      }
      this._rev = value;
    }
  },
 
  dbname: {
    get: function() {
      return this._dbname || FieldDBObject.DEFAULT_STRING;
    },
    set: function(value) {
      if (value === this._dbname) {
        return;
      }
      if (this._dbname && this._dbname !== "default" && this.rev) {
        throw new Error("This is the " + this._dbname + ". You cannot change the dbname of an object in this corpus to " + value + ", you must create a clone of the object first.");
      }
      if (!value) {
        delete this._dbname;
        return;
      }
      Eif (value.trim) {
        value = value.trim();
      }
      this._dbname = value;
    }
  },
 
  pouchname: {
    get: function() {
      this.debug("Pouchname is deprecated, use dbname instead.");
      return this.dbname;
    },
    set: function(value) {
      this.debug("Pouchname is deprecated, please use dbname instead.");
      this.dbname = value;
    }
  },
 
  couchConnection: {
    get: function() {
      console.error("CouchConnection is deprecated, use connection instead " + this.id);
      return this.connection;
    },
    set: function(value) {
      // console.error("CouchConnection is deprecated, use connection instead");
      this.connection = value;
    }
  },
 
  version: {
    get: function() {
      return this._version || FieldDBObject.DEFAULT_VERSION;
    },
    set: function(value) {
      if (value === this._version) {
        return;
      }
      Iif (!value) {
        value = FieldDBObject.DEFAULT_VERSION;
      }
      Eif (value.trim) {
        value = value.trim();
      }
      this._version = value;
    }
  },
 
  timestamp: {
    get: function() {
      return this._timestamp || this._dateCreated;
    },
    set: function(value) {
      Iif (value === this._timestamp) {
        return;
      }
      Iif (!value) {
        // delete this._timestamp;
        return;
      }
      if (value.replace) {
        try {
          value = value.replace(/["\\]/g, "");
          value = new Date(value);
          value = value.getTime();
        } catch (e) {
          this.warn("Upgraded timestamp" + value);
        }
      }
      this._timestamp = value;
 
      // Use timestamp as date created if there was none, or the timestamp is older.
      Eif (!this._dateCreated || this._dateCreated > value) {
        this.debug("Timestmap was older than dateCreated", this._dateCreated);
        this._dateCreated = value;
      }
    }
  },
 
  created_at: {
    get: function() {
      this.warn("created_at is deprecated use dateCreated instead");
      return this._created_at;
    },
    set: function(value) {
      this._created_at = value;
      this.dateCreated = value;
    }
  },
 
  dateCreated: {
    get: function() {
      return this._dateCreated || FieldDBObject.DEFAULT_DATE;
    },
    set: function(value) {
      if (value === this._dateCreated) {
        return;
      }
      if (!value) {
        // delete this._dateCreated;
        return;
      }
      if (value.replace) {
        try {
          value = value.replace(/["\\]/g, "");
          value = new Date(value);
          value = value.getTime();
        } catch (e) {
          this.warn("Upgraded dateCreated" + value);
        }
      }
      Iif (this._dateCreated || this._dateCreated < value) {
        this.warn("not setting _dateCreated, the new value is more recent", this._dateCreated, value);
        return;
      }
      this._dateCreated = value;
    }
  },
 
  updated_at: {
    get: function() {
      this.warn("updated_at is deprecated use dateModified instead");
      return this._updated_at;
    },
    set: function(value) {
      this._updated_at = value;
      this.dateModified = value;
    }
  },
 
  dateModified: {
    get: function() {
      return this._dateModified || FieldDBObject.DEFAULT_DATE;
    },
    set: function(value) {
      if (value === this._dateModified) {
        return;
      }
      if (!value) {
        delete this._dateModified;
        return;
      }
      if (value.replace) {
        try {
          value = value.replace(/["\\]/g, "");
          value = new Date(value);
          value = value.getTime();
        } catch (e) {
          this.warn("Upgraded dateModified" + value);
        }
      }
      this._dateModified = value;
    }
  },
 
  /**
   * Shows the differences between revisions of two couchdb docs, TODO not working yet but someday when it becomes a priority..
   */
  showDiffs: {
    value: function(oldrevision, newrevision) {
      this.todo("We haven't implemented the 'diff' tool yet" +
        " (ie, showing the changes, letting you undo changes etc)." +
        " We will do it eventually, when it becomes a priority. " +
        "<a target='blank'  href='https://github.com/FieldDB/FieldDB/issues/124'>" +
        "You can vote for it in our issue tracker</a>.  " +
        "We use the " +
        "<a target='blank' href='" + this.url + "/" + oldrevision + "?rev=" + newrevision + "'>" + "Futon User Interface</a> directly to track revisions in the data, you can too (if your a power user type).", "alert", "Track Changes:");
    }
  },
 
  comments: {
    get: function() {
      return this._comments || FieldDBObject.DEFAULT_COLLECTION;
    },
    set: function(value) {
      Iif (value === this._comments) {
        return;
      }
      Iif (!value) {
        delete this._comments;
        return;
      } else {
        if (typeof this.INTERNAL_MODELS["comments"] === "function" && Object.prototype.toString.call(value) === "[object Array]") {
          value = new this.INTERNAL_MODELS["comments"](value);
        }
      }
      this._comments = value;
    }
  },
 
  isEmpty: {
    value: function(aproperty) {
      var empty = !this[aproperty] || this[aproperty] === FieldDBObject.DEFAULT_COLLECTION || this[aproperty] === FieldDBObject.DEFAULT_ARRAY || this[aproperty] === FieldDBObject.DEFAULT_OBJECT || this[aproperty] === FieldDBObject.DEFAULT_STRING || this[aproperty] === FieldDBObject.DEFAULT_DATE || (this[aproperty].length !== undefined && this[aproperty].length === 0) || this[aproperty] === {};
      /* TODO also return empty if it matches a default of any version of the model? */
      return empty;
    }
  },
 
  toJSON: {
    value: function(includeEvenEmptyAttributes, removeEmptyAttributes, attributesToIgnore) {
      try {
        var json = {
            fieldDBtype: this.fieldDBtype
          },
          aproperty,
          underscorelessProperty;
 
        Iif (this.fetching) {
          this.warn("Cannot get json while " + this.id + " is fetching itself");
          this.debug(" this is the object", this);
          // return;
          // throw "Cannot get json while object is fetching itself";
        }
        /* this object has been updated to this version */
        this.version = this.version;
        /* force id to be set if possible */
        // this.id = this.id;
 
        if (this.useIdNotUnderscore) {
          json.id = this.id;
        } else {
          json._id = this.id;
        }
 
        if (!attributesToIgnore) {
          attributesToIgnore = [];
        }
        attributesToIgnore = attributesToIgnore.concat(FieldDBObject.internalAttributesToNotJSONify);
        this.debug("Ignoring for json ", attributesToIgnore);
        for (aproperty in this) {
          if (this.hasOwnProperty(aproperty) && typeof this[aproperty] !== "function" && !FieldDBObject.ignore(aproperty, attributesToIgnore)) {
            underscorelessProperty = aproperty.replace(/^_/, "");
            if (underscorelessProperty === "id" || underscorelessProperty === "rev") {
              underscorelessProperty = "_" + underscorelessProperty;
            }
            if (!removeEmptyAttributes || (removeEmptyAttributes && !this.isEmpty(aproperty))) {
              if (this[aproperty] && typeof this[aproperty].toJSON === "function") {
                json[underscorelessProperty] = this[aproperty].toJSON(includeEvenEmptyAttributes, removeEmptyAttributes);
              } else {
                json[underscorelessProperty] = this[aproperty];
              }
            }
          }
        }
 
        /* if the caller requests a complete object include the default for all defauls by calling get on them */
        if (includeEvenEmptyAttributes) {
          for (aproperty in this.INTERNAL_MODELS) {
            if (!json[aproperty] && this.INTERNAL_MODELS) {
              if (this.INTERNAL_MODELS[aproperty] && typeof this.INTERNAL_MODELS[aproperty] === "function" && typeof new this.INTERNAL_MODELS[aproperty]().toJSON === "function") {
                json[aproperty] = new this.INTERNAL_MODELS[aproperty]().toJSON(includeEvenEmptyAttributes, removeEmptyAttributes, attributesToIgnore);
              } else {
                json[aproperty] = this.INTERNAL_MODELS[aproperty];
              }
            }
          }
        }
 
        if (!json._id) {
          delete json._id;
        }
        if (this.useIdNotUnderscore) {
          delete json._id;
        }
 
        if (!json._rev) {
          delete json._rev;
        }
        if (json.dbname) {
          json.pouchname = json.dbname;
          this.debug("Serializing Pouchname for backward compatability until prototype can handle dbname");
        }
 
        for (var uninterestingAttrib in FieldDBObject.internalAttributesToNotJSONify) {
          Eif (FieldDBObject.internalAttributesToNotJSONify.hasOwnProperty(uninterestingAttrib)) {
            delete json[FieldDBObject.internalAttributesToNotJSONify[uninterestingAttrib]];
            delete json[FieldDBObject.internalAttributesToNotJSONify[uninterestingAttrib].replace(/^_/, "")];
          }
        }
 
        Eif (this.collection !== "private_corpora" || this.api !== "private_corpora") {
          delete json.confidential;
          delete json.confidentialEncrypter;
        } else {
          this.warn("serializing confidential in this object " + this._collection);
        }
        if (this.api) {
          json.api = this.api;
        }
 
        json.fieldDBtype = this.fieldDBtype;
        Iif (json.previousFieldDBtype && json.fieldDBtype && json.previousFieldDBtype === json.fieldDBtype) {
          delete json.previousFieldDBtype;
        }
        if (attributesToIgnore.indexOf("fieldDBtype") > -1) {
          delete json.fieldDBtype;
        }
        return json;
 
      } catch (e) {
        console.warn(e);
        console.error(e.stack);
        this.bug("Unable to serialze " + this.id + ". Please report this.");
        return null;
      }
    }
  },
 
  addRelatedData: {
    value: function(json) {
      var relatedData;
      Iif (this.fields && this.fields.relatedData) {
        relatedData = this.fields.relatedData.json.relatedData || [];
      } else Eif (this.relatedData) {
        relatedData = this.relatedData;
      } else {
        this.relatedData = relatedData = [];
      }
 
      json.relation = "associated file";
      relatedData.push(json);
    }
  },
 
  /**
   * Creates a deep copy of the object (not a reference)
   * @return {Object} a near-clone of the objcet
   */
  clone: {
    value: function(includeEvenEmptyAttributes) {
      var json = {},
        aproperty,
        underscorelessProperty;
      try {
        json = JSON.parse(JSON.stringify(this.toJSON(includeEvenEmptyAttributes)));
      } catch (e) {
        if (e) {
          console.warn(e);
          console.warn(e.stack);
          console.warn(e.message);
          console.warn(this);
          // throw e;
        }
      }
      // Use clone on internal properties which have a clone function
      for (aproperty in json) {
        underscorelessProperty = aproperty.replace(/^_/, "");
        if (this[aproperty] && typeof this[aproperty].clone === "function") {
          json[underscorelessProperty] = JSON.parse(JSON.stringify(this[aproperty].clone(includeEvenEmptyAttributes)));
        }
      }
 
      var source = this.id;
      if (this.id && this.rev) {
        var relatedData;
        Iif (json.fields && json.fields.relatedData) {
          relatedData = json.fields.relatedData.json.relatedData || [];
        } else Iif (json.relatedData) {
          relatedData = json.relatedData;
        } else {
          json.relatedData = relatedData = [];
        }
        Eif (this.rev) {
          source = source + "?rev=" + this.rev;
        } else {
          if (this.parent && this.parent._rev) {
            source = "parent" + this.parent._id + "?rev=" + this.parent._rev;
          }
        }
        relatedData.push({
          relation: "clonedFrom",
          URI: source
        });
      }
 
      /* Clear the current object's info which we shouldnt clone */
      delete json._id;
      delete json._rev;
      delete json.parent;
      delete json.dbname;
      delete json.pouchname;
 
      return new this.constructor(json);
    }
  },
 
  contextualizer: {
    get: function() {
      if (this.application && this.application.contextualizer) {
        return this.application.contextualizer;
      }
    },
    set: function() {}
  },
 
  /**
   *  Cleans a value to become a primary key on an object (replaces punctuation and symbols with underscore)
   *  formerly: item.replace(/[-\""+=?.*&^%,\/\[\]{}() ]/g, "")
   *
   * @param  String value the potential primary key to be cleaned
   * @return String       the value cleaned and safe as a primary key
   */
  sanitizeStringForFileSystem: {
    value: function(value, optionalReplacementCharacter) {
      this.debug("sanitizeStringForPrimaryKey " + value);
      Iif (!value) {
        return null;
      }
      if (optionalReplacementCharacter === undefined || optionalReplacementCharacter === "-") {
        optionalReplacementCharacter = "_";
      }
      if (value.trim) {
        value = Diacritics.remove(value);
        this.debug("sanitizeStringForPrimaryKey " + value);
 
        value = value.trim().replace(/[^-a-zA-Z0-9]+/g, optionalReplacementCharacter).replace(/^_/, "").replace(/_$/, "");
        this.debug("sanitizeStringForPrimaryKey " + value);
        return value;
      } else Eif (typeof value === "number") {
        return parseFloat(value, 10);
      } else {
        return null;
      }
    }
  },
 
  sanitizeStringForPrimaryKey: {
    value: function(value, optionalReplacementCharacter) {
      this.debug("sanitizeStringForPrimaryKey " + value);
      Iif (!value) {
        return null;
      }
      if (value.replace) {
        value = value.replace(/-/g, "_");
      }
      value = this.sanitizeStringForFileSystem(value, optionalReplacementCharacter);
      if (value && typeof value !== "number") {
        return this.camelCased(value);
      }
    }
  },
 
  camelCased: {
    value: function(value) {
      Iif (!value) {
        return null;
      }
      Eif (value.replace) {
        value = value.replace(/_([a-zA-Z])/g, function(word) {
          return word[1].toUpperCase();
        });
        value = value[0].toLowerCase() + value.substring(1, value.length);
      }
      return value;
    }
  }
 
});
 
exports.FieldDBObject = FieldDBObject;
exports.Document = FieldDBObject;