Code coverage report for api/corpus/Corpus.js

Statements: 47% (204 / 434)      Branches: 55% (154 / 280)      Functions: 36.67% (33 / 90)      Lines: 47% (204 / 434)      Ignored: none     

All files » api/corpus/ » Corpus.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  1 1 1 1 1 1 1 1 1   1 1                                                                                           1 66 62   66 66   1   1                   204     4     4       4 4   4           12 12           12             1527     91 91           14     41     41       41                                     11           3                           11           15     30           15     30           1     1     1                                                                                                                                                                                                                                                                                         40 40 40             7   7 7 14 14     7     7                                                                                                                                                                                                                                     721 721     721 721           721               721 8     8 5 5   3     721 721           13     13 13 13   13           6   6 6   6                                   2     2   2 2     2       2                     2   2                                       1     1       1 1           1 1   1       1 1                   2     2 1   1   1 1   1   1 1 5 4 4   1 1       1 1   1 1 1     2 1 1       2                                                                               1   1         1 1                           41 35   41 3   38 34       38   38 4       34 34 5 5 2   3   5     5   5     5   5     5   5   34   34 27 1 1 1 1 1   26 5 5 5 5 5   21 2 2 2 2 2   19 2 2 2 2 2   17 2 2 2 2 2   15 2 2 2 2 2           34 13 13 13   13   34 34     34   34 34                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         10 10 10   10       10 10   10 9   10 9     10 10           1 1  
/* global window, OPrime */
var Confidential = require("./../confidentiality_encryption/Confidential").Confidential;
var CorpusMask = require("./CorpusMask").CorpusMask;
var LanguageDatum = require("./../datum/LanguageDatum").LanguageDatum;
var DatumField = require("./../datum/DatumField").DatumField;
var DatumFields = require("./../datum/DatumFields").DatumFields;
var Session = require("./../datum/Session").Session;
var Speaker = require("./../user/Speaker").Speaker;
var FieldDBObject = require("./../FieldDBObject").FieldDBObject;
var Q = require("q");
 
var DEFAULT_CORPUS_MODEL = require("./corpus.json");
var DEFAULT_PSYCHOLINGUISTICS_CORPUS_MODEL = require("./psycholinguistics-corpus.json");
 
/**
 * @class A corpus is like a git repository, it has a remote, a title
 *        a description and perhaps a readme When the user hits sync
 *        their "branch" of the corpus will be pushed to the central
 *        remote, and we will show them a "diff" of what has
 *        changed.
 *
 * The Corpus may or may not be a git repository, so this class is
 * to abstract the functions we would expect the corpus to have,
 * regardless of how it is really stored on the disk.
 *
 *
 * @property {String} title This is used to refer to the corpus, and
 *           what appears in the url on the main website eg
 *           http://fieldlinguist.com/LingLlama/SampleFieldLinguisticsCorpus
 * @property {String} description This is a short description that
 *           appears on the corpus details page
 * @property {String} remote The git url of the remote eg:
 *           git@fieldlinguist.com:LingLlama/SampleFieldLinguisticsCorpus.git
 *
 * @property {Consultants} consultants Collection of consultants who contributed to the corpus
 * @property {DatumStates} datumstates Collection of datum states used to describe the state of datums in the corpus
 * @property {DatumFields} datumFields Collection of datum fields used in the corpus
 * @property {ConversationFields} conversationfields Collection of conversation-based datum fields used in the corpus
 * @property {Sessions} sessions Collection of sessions that belong to the corpus
 * @property {DataLists} datalists Collection of data lists created under the corpus
 * @property {Permissions} permissions Collection of permissions groups associated to the corpus
 *
 *
 * @property {Glosser} glosser The glosser listens to
 *           orthography/utterence lines and attempts to guess the
 *           gloss.
 * @property {Lexicon} lexicon The lexicon is a list of morphemes,
 *           allomorphs and glosses which are used to index datum, and
 *           also to gloss datum.
 *
 * @description The initialize function probably checks to see if
 *              the corpus is new or existing and brings it down to
 *              the user's client.
 *
 * @extends CorpusMask
 * @tutorial tests/corpus/CorpusTest.js
 */
 
var Corpus = function Corpus(options) {
  if (!this._fieldDBtype) {
    this._fieldDBtype = "Corpus";
  }
  this.debug("Constructing corpus", options);
  CorpusMask.apply(this, arguments);
};
Corpus.DEFAULT_DATUM = LanguageDatum;
 
Corpus.prototype = Object.create(CorpusMask.prototype, /** @lends Corpus.prototype */ {
  constructor: {
    value: Corpus
  },
 
  /**
   *  Must customize id to the original method since CorpusMask overrides it with "corpus"
   */
  id: {
    get: function() {
      return this._id || FieldDBObject.DEFAULT_STRING;
    },
    set: function(value) {
      Iif (value === this._id) {
        return;
      }
      Iif (!value) {
        delete this._id;
        return;
      }
      Eif (value.trim) {
        value = value.trim();
      }
      this._id = value;
    }
  },
 
  dateOfLastDatumModifiedToCheckForOldSession: {
    get: function() {
      var timestamp = 0;
      Iif (this.sessions && this.sessions.length > 0) {
        var mostRecentSession = this.sessions[this.sessions.length - 1];
        if (mostRecentSession.dateModified) {
          timestamp = mostRecentSession.dateModified;
        }
      }
      return new Date(timestamp);
    },
    set: function() {}
  },
 
  confidential: {
    get: function() {
      return this._confidential || FieldDBObject.DEFAULT_OBJECT;
    },
    set: function(value) {
      this.ensureSetViaAppropriateType("confidential", value);
      return this._confidential;
    }
  },
 
  publicCorpus: {
    get: function() {
      return this._publicCorpus || FieldDBObject.DEFAULT_STRING;
    },
    set: function(value) {
      Iif (value === this._publicCorpus) {
        return;
      }
      Iif (!value || (value !== "Public" && value !== "Private")) {
        this.warn("Corpora can be either Public or Private, if you make your corpus Public you can customize which fields are visible to public visitors.");
        value = "Private";
      }
      this._publicCorpus = value;
    }
  },
 
  /**
   * TODO decide if we want to fetch these from the server, and keep a fossil in the object?
   * @type {Object}
   */
  corpusMask: {
    get: function() {
      if (!this._corpusMask) {
        this.corpusMask = {
          "id": "corpus"
        };
      // this.corpusMask.fetch();
      }
      return this._corpusMask;
    },
    set: function(value) {
      this.ensureSetViaAppropriateType("corpusMask", value);
    }
  },
 
  corpus: {
    get: function() {
      return this;
    },
    set: function() {
      // do nothing
    }
  },
 
  publicSelf: {
    get: function() {
      console.error("publicSelf is deprecated, use corpusMask instead");
      return this.corpusMask;
    },
    set: function(value) {
      // console.error("publicSelf is deprecated, use corpusMask instead");
      this.corpusMask = value;
    }
  },
 
  validationStati: {
    get: function() {
      return this._validationStati || FieldDBObject.DEFAULT_COLLECTION;
    },
    set: function(value) {
      this.ensureSetViaAppropriateType("validationStati", value);
    }
  },
 
  tags: {
    get: function() {
      return this._tags || FieldDBObject.DEFAULT_COLLECTION;
    },
    set: function(value) {
      this.ensureSetViaAppropriateType("tags", value);
    }
  },
 
  fetch: {
    value: function(optionalUrl) {
      Iif (!this.id && this.dbname) {
        return this.loadCorpusByDBname(this.dbname);
      } else {
        Iif (optionalUrl) {
          this.warn("Using a custom url to fetch this Corpus." + optionalUrl);
        }
        return CorpusMask.prototype.fetch.apply(this, arguments);
      }
    }
  },
 
  loadCorpusByDBname: {
    value: function(dbname) {
      if (!dbname) {
        throw new Error("Cannot load corpus, its dbname was undefined");
      }
      var deferred = this.loadCorpusByDBnameDeferred || Q.defer(),
        self = this;
 
      dbname = dbname.trim();
 
      this.dbname = dbname;
      this.loading = true;
 
      // this.debugMode = true;
      Q.nextTick(function() {
 
        var tryAgainInCaseThereWasALag = function(reason) {
          self.debug(reason);
          if (self.runningloadCorpusByDBname) {
            self.warn("Error finding a corpus in " + self.dbname + " database. This database will not function normally. Please report this.");
            self.bug("Error finding corpus details in " + self.dbname + " database. This database will not function normally. Please report this.");
            deferred.reject(reason);
            return;
          }
          self.runningloadCorpusByDBname = true;
          self.loadCorpusByDBnameDeferred = deferred;
          self.debug("Wating 1000ms to try to load again.");
          setTimeout(function() {
            self.loadCorpusByDBname(dbname);
          }, 1000);
        };
 
        self.fetchCollection(self.api).then(function(corpora) {
          self.debug(corpora);
 
          var corpusAsSelf = function(corpusid) {
            self.runningloadCorpusByDBname = false;
            delete self.loadCorpusByDBnameDeferred;
            self.id = corpusid;
            self.fetch().then(function(result) {
              self.debug("Finished fetch of corpus ", result);
              self.loading = false;
              deferred.resolve(result);
            }, function(reason) {
              self.loading = false;
              deferred.reject(reason);
            }).fail(function(error) {
              console.error(error.stack, self);
              deferred.reject(error);
            });
          };
 
          if (corpora.length === 1) {
            corpusAsSelf(corpora[0]._id);
          } else if (corpora.length > 1) {
            self.warn("Impossible to have more than one corpus for this dbname, marking irrelevant corpora as trashed");
            corpora.map(function(row) {
              if (row.value.dbname === self.dbname || row.value.pouchname === self.dbname) {
                corpusAsSelf(row.value._id);
              } else {
                self.warn("There were multiple corpora details in this database, it is probaly one of the old offline databases prior to v1.30 or the result of merged corpora. This is not really a problem, the correct details will be used, and this corpus details will be marked as deleted. " + row.value);
                row.value.trashed = "deleted";
                self.set(row.value).then(function(result) {
                  self.debug("flag as deleted succedded", result);
                }, function(reason) {
                  self.warn("flag as deleted failed", reason, row.value);
                }).fail(function(error) {
                  console.error(error.stack, self);
                  deferred.reject(error);
                });
              }
            });
          } else {
            tryAgainInCaseThereWasALag(corpora);
          }
        }, function(reason) {
          self.debug(JSON.stringify(reason));
          if (reason && reason.userFriendlyErrors && reason.userFriendlyErrors[0].indexOf("device will be unable to contact") > -1) {
            deferred.reject(reason);
          } else {
            tryAgainInCaseThereWasALag(reason);
          }
 
        });
 
      });
 
      return deferred.promise;
    }
  },
 
  fetchMask: {
    value: function() {
      this.todo("test fetchMask");
      if (!this.dbname) {
        throw new Error("Cannot load corpus's public self, its dbname was undefined");
      }
      var deferred = Q.defer(),
        self = this;
 
      Q.nextTick(function() {
 
        if (self.corpusMask && self.corpusMask.rev) {
          deferred.resolve(self.corpusMask);
          return;
        }
 
        self.corpusMask = new CorpusMask({
          dbname: self.dbname
        });
 
        self.corpusMask.fetch()
          .then(deferred.resolve, deferred.reject)
          .fail(function(error) {
            console.error(error.stack, self);
            deferred.reject(error);
          });
 
      });
      return deferred.promise;
    }
  },
 
  /**
   * backbone-couchdb adaptor set up
   */
 
  // The couchdb-connector is capable of mapping the url scheme
  // proposed by the authors of Backbone to documents in your database,
  // so that you don't have to change existing apps when you switch the sync-strategy
  api: {
    value: "private_corpora"
  },
 
  defaults: {
    get: function() {
      var corpusTemplate = JSON.parse(JSON.stringify(DEFAULT_CORPUS_MODEL));
      corpusTemplate.confidential.secretkey = FieldDBObject.uuidGenerator();
      return corpusTemplate;
    },
    set: function() {}
  },
 
  defaults_psycholinguistics: {
    get: function() {
      var doc = this.defaults;
 
      Eif (DEFAULT_PSYCHOLINGUISTICS_CORPUS_MODEL) {
        for (var property in DEFAULT_PSYCHOLINGUISTICS_CORPUS_MODEL) {
          Eif (DEFAULT_PSYCHOLINGUISTICS_CORPUS_MODEL.hasOwnProperty(property)) {
            doc[property] = DEFAULT_PSYCHOLINGUISTICS_CORPUS_MODEL[property];
          }
        }
        doc.participantFields = this.defaults.speakerFields.concat(doc.participantFields);
      }
 
      return JSON.parse(JSON.stringify(doc));
    },
    set: function() {}
  },
 
  /**
   * Make the  model marked as Deleted, mapreduce function will
   * ignore the deleted models so that it does not show in the app,
   * but deleted model remains in the database until the admin empties
   * the trash.
   *
   * Also remove it from the view so the user cant see it.
   *
   */
  putInTrash: {
    value: function() {
      OPrime.bug("Sorry deleting corpora is not available right now. Too risky... ");
      if (true) {
        return;
      }
      /* TODO contact server to delte the corpus, if the success comes back, then do this */
      this.trashed = "deleted" + Date.now();
      this.save();
    }
  },
 
  /**
   *  This the function called by the add button, it adds a new comment state both to the collection and the model
   * @type {Object}
   */
  newComment: {
    value: function(commentstring) {
      var m = {
        "text": commentstring,
      };
 
      this.comments.add(m);
      this.unsavedChanges = true;
 
      window.app.addActivity({
        verb: "commented",
        verbicon: "icon-comment",
        directobjecticon: "",
        directobject: "'" + commentstring + "'",
        indirectobject: "on <i class='icon-cloud'></i><a href='#corpus/" + this.id + "'>this corpus</a>",
        teamOrPersonal: "team",
        context: " via Offline App."
      });
 
      window.app.addActivity({
        verb: "commented",
        verbicon: "icon-comment",
        directobjecticon: "",
        directobject: "'" + commentstring + "'",
        indirectobject: "on <i class='icon-cloud'></i><a href='#corpus/" + this.id + "'>" + this.get("title") + "</a>",
        teamOrPersonal: "personal",
        context: " via Offline App."
      });
 
      return m;
    }
  },
 
  currentSession: {
    get: function() {
      return this._currentSession;
    },
    set: function(value) {
      this._currentSession = value;
    }
  },
 
  /**
   * Builds a new session in this corpus, copying the current session's fields (if available) or the corpus' session fields.
   * @return {Session} a new session for this corpus
   */
  newSession: {
    value: function(options) {
      var sessionFields;
      if (this.currentSession && this.currentSession.sessionFields) {
        sessionFields = this.currentSession.sessionFields.clone();
      } else {
        sessionFields = this.sessionFields.clone();
      }
      var session = new Session({
        dbname: this.dbname,
        fields: sessionFields,
        confidential: this.confidential,
      // url: this.url
      });
 
      for (var field in options) {
        if (!options.hasOwnProperty(field)) {
          continue;
        }
        if (session.fields[field]) {
          this.debug("  this option appears to be a sessionField " + field);
          session.fields[field].value = options[field];
        } else {
          session[field] = options[field];
        }
      }
 
      return session;
    }
  },
 
  newDoc: {
    value: function(options) {
      return this.newDatum(options);
    }
  },
 
  newDatum: {
    value: function(options) {
      this.debug("Creating a datum for this corpus");
      Iif (!this.datumFields || !this.datumFields.clone) {
        throw new Error("This corpus has no default datum fields... It is unable to create a datum.");
      }
      var datum;
      Iif (options instanceof Corpus.DEFAULT_DATUM) {
        datum = options;
        datum.dbname = this.dbname;
        datum.confidential = this.confidential;
        datum = this.updateDatumToCorpusFields(datum);
      } else {
        datum = new Corpus.DEFAULT_DATUM({
          fields: new DatumFields(this.datumFields.cloneStructure()),
          dbname: this.dbname,
          confidential: this.confidential,
          audioVideo: [],
          images: []
        });
      }
      for (var field in options) {
        Iif (!options.hasOwnProperty(field)) {
          continue;
        }
        if (datum.fields[field]) {
          this.debug("  this option appears to be a datumField " + field);
          datum.fields[field].value = options[field];
        } else {
          datum[field] = options[field];
        }
      }
      datum.fossil = datum.toJSON();
      return datum;
    }
  },
 
  newDatumAsync: {
    value: function(options) {
      var deferred = Q.defer(),
        self = this;
 
      Q.nextTick(function() {
        var datum = self.newDatum(options);
        deferred.resolve(datum);
      });
      return deferred.promise;
    }
  },
 
  newField: {
    value: function(field) {
      field = field || {};
 
      Eif (!(field instanceof DatumField)) {
        field = new DatumField(field);
      }
      return field;
    }
  },
 
  addDatumField: {
    value: function(field) {
      if (!field.id && field.label) {
        field.id = field.label;
      }
      if (!(field instanceof DatumField)) {
        field = new DatumField(field);
      }
      this.datumFields.add(field);
    }
  },
 
  newSpeaker: {
    value: function(options) {
      var deferred = Q.defer(),
        self = this;
 
      Q.nextTick(function() {
 
        self.debug("Creating a datum for this corpus");
        Iif (!self.speakerFields || !self.speakerFields.clone) {
          throw new Error("This corpus has no default datum fields... It is unable to create a datum.");
        }
        var datum = new Speaker({
          speakerFields: new DatumFields(self.speakerFields.clone()),
          confidential: self.confidential
        });
        for (var field in options) {
          if (!options.hasOwnProperty(field)) {
            continue;
          }
          if (datum.speakerFields[field]) {
            self.debug("  this option appears to be a datumField " + field);
            datum.speakerFields[field].value = options[field];
          } else {
            datum[field] = options[field];
          }
        }
        deferred.resolve(datum);
      });
      return deferred.promise;
    }
  },
 
  updateDatumToCorpusFields: {
    value: function(datum) {
      if (!this.datumFields) {
        return datum;
      }
      if (!datum.fields) {
        datum.fields = this.datumFields.clone();
        return datum;
      }
      datum.fields = new DatumFields().merge(this.datumFields, datum.fields);
      return datum;
    }
  },
 
  updateSpeakerToCorpusFields: {
    value: function(speaker) {
      Iif (!this.speakerFields) {
        this.speakerFields = this.defaults_psycholinguistics.speakerFields;
      }
      Iif (!speaker.fields) {
        speaker.fields = this.speakerFields.clone();
        return speaker;
      }
      speaker.fields = new DatumFields().merge(this.speakerFields, speaker.fields);
      return speaker;
    }
  },
 
  updateParticipantToCorpusFields: {
    value: function(participant) {
      Eif (!this.participantFields) {
        this.participantFields = this.defaults_psycholinguistics.participantFields;
      }
      Iif (!participant.fields) {
        participant.fields = this.participantFields.clone();
        return participant;
      }
      participant.fields = new DatumFields().merge(this.participantFields, participant.fields, "overwrite");
      return participant;
    }
  },
 
  /**
   * Builds a new corpus based on this one (if this is not the team's practice corpus)
   * @return {Corpus} a new corpus based on this one
   */
  newCorpus: {
    value: function(options) {
      var corpus,
        self = this;
 
      if (this.dbname && this.dbname.indexOf("firstcorpus") > -1) {
        corpus = new Corpus(Corpus.prototype.defaults);
      } else {
        corpus = this.clone();
 
        corpus.comments = [];
        corpus.confidential = new Confidential().fillWithDefaults();
 
        var fieldsToClear = ["datumFields", "sessionFields", "conversationFields", "participantFields", "speakerFields"];
        //clear out search terms from the new corpus's datum fields
        var defaults = this.defaults;
        fieldsToClear.map(function(fieldsType) {
          if (self[fieldsType]) {
            self.debug("Cloning structure only of fieldsType: ", fieldsType);
            corpus[fieldsType] = self[fieldsType].cloneStructure();
          } else {
            self.debug("fieldsType " + fieldsType + " was missing on this corpus, it's copy will have the fields. ", self);
            corpus[fieldsType] = defaults[fieldsType];
          }
        });
 
        Eif (this.dbname) {
          corpus.dbname = this.dbname + "_copy";
        }
        corpus.title = corpus.title + " copy";
        corpus.titleAsUrl = corpus.titleAsUrl + "Copy";
        corpus.description = "Copy of: " + corpus.description;
      }
 
      for (var aproperty in options) {
        Eif (options.hasOwnProperty(aproperty)) {
          corpus[aproperty] = options[aproperty];
        }
      }
 
      return corpus;
    }
  },
 
  cloneStructure: {
    value: function() {
      return this.newCorpus();
    }
  },
 
  /**
   * DO NOT store in attributes when saving to pouch (too big)
   * @type {FieldDBGlosser}
   */
  glosser: {
    get: function() {
      return this.glosserExternalObject;
    },
    set: function(value) {
      if (value === this.glosserExternalObject) {
        return;
      }
      this.glosserExternalObject = value;
    }
  },
 
  lexicon: {
    get: function() {
      return this.lexiconExternalObject;
    },
    set: function(value) {
      if (value === this.lexiconExternalObject) {
        return;
      }
      this.lexiconExternalObject = value;
    }
  },
 
  find: {
    value: function(uri) {
      var deferred = Q.defer();
 
      Iif (!uri) {
        deferred.reject(new Error("Uri must be specified "));
        return deferred.promise;
      }
 
      return this.get(uri).catch(function() {
        return [];
      });
    }
  },
 
  /**
   *  This function looks for the field's details from the corpus fields, if it exists it returns that field template.
   *
   * If the field isnt in the corpus' fields exactly, it looks for fields which this field should map to (eg, if the field is codepermanent it can be mapped to anonymouscode)
   * @param  {String/Object} field A datumField to look for, or the label/id of a datum field to look for.
   * @return {DatumField}       A datum field with details filled in from the corresponding field in the corpus, or from a template.
   */
  normalizeFieldWithExistingCorpusFields: {
    value: function(field, optionalAllFields) {
      if (field && typeof field.trim === "function") {
        field = field.trim();
      }
      if (field === undefined || field === null || field === "") {
        return;
      }
      if (typeof field !== "object") {
        field = {
          id: field
        };
      }
      var incomingFieldIdOrLabel = field.id || field.label;
      // incomingFieldIdOrLabel = incomingFieldIdOrLabel + "";
      if (incomingFieldIdOrLabel === undefined || incomingFieldIdOrLabel === null || incomingFieldIdOrLabel === "") {
        return;
      }
      // this.debugMode = true;
      // this.debug("Normalizing " + incomingFieldIdOrLabel + " if it is known to this corpus.");
      var fuzzyLabel = incomingFieldIdOrLabel.toLowerCase().replace(/[^a-z]/g, "");
      if (!optionalAllFields) {
        optionalAllFields = new DatumFields();
        if (this.datumFields && this.datumFields.length > 0) {
          optionalAllFields.add(this.datumFields.toJSON());
        } else {
          optionalAllFields.add(DEFAULT_CORPUS_MODEL.datumFields);
        }
        Iif (this.participantFields && this.participantFields.length > 0 && this.participantFields.toJSON) {
          optionalAllFields.add(this.participantFields.toJSON());
        } else {
          optionalAllFields.add(DEFAULT_PSYCHOLINGUISTICS_CORPUS_MODEL.participantFields);
        }
        Iif (this.speakerFields && this.speakerFields.length > 0 && this.speakerFields.toJSON) {
          optionalAllFields.add(this.speakerFields.toJSON());
        } else {
          optionalAllFields.add(DEFAULT_CORPUS_MODEL.speakerFields);
        }
        Iif (this.conversationFields && this.conversationFields.length > 0 && this.conversationFields.toJSON) {
          optionalAllFields.add(this.conversationFields.toJSON());
        } else {
          optionalAllFields.add(DEFAULT_CORPUS_MODEL.conversationFields);
        }
        this.debug("Using a clone of the corpus fields. ", optionalAllFields);
      }
      var correspondingDatumField = optionalAllFields.find(field, null, true);
      /* if there is no corresponding field yet in the optionalAllFields, then maybe there is a field which is normalized to this label */
      if (!correspondingDatumField || correspondingDatumField.length === 0) {
        if (fuzzyLabel.indexOf("checkedwith") > -1 || fuzzyLabel.indexOf("checkedby") > -1 || fuzzyLabel.indexOf("publishedin") > -1) {
          correspondingDatumField = optionalAllFields.find("validationStatus");
          Eif (correspondingDatumField.length > 0) {
            this.debug("This header matches an existing corpus field. ", correspondingDatumField);
            correspondingDatumField[0].labelFieldLinguists = field.labelFieldLinguists || incomingFieldIdOrLabel;
            correspondingDatumField[0].labelExperimenters = field.labelExperimenters || incomingFieldIdOrLabel;
          }
        } else if (fuzzyLabel.indexOf("codepermanent") > -1) {
          correspondingDatumField = optionalAllFields.find("anonymouscode");
          Eif (correspondingDatumField.length > 0) {
            this.debug("This header matches an existing corpus field. ", correspondingDatumField);
            correspondingDatumField[0].labelFieldLinguists = field.labelFieldLinguists || incomingFieldIdOrLabel;
            correspondingDatumField[0].labelExperimenters = field.labelExperimenters || incomingFieldIdOrLabel;
          }
        } else if (fuzzyLabel.indexOf("nsection") > -1) {
          correspondingDatumField = optionalAllFields.find("courseNumber");
          Eif (correspondingDatumField.length > 0) {
            this.debug("This header matches an existing corpus field. ", correspondingDatumField);
            correspondingDatumField[0].labelFieldLinguists = field.labelFieldLinguists || incomingFieldIdOrLabel;
            correspondingDatumField[0].labelExperimenters = field.labelExperimenters || incomingFieldIdOrLabel;
          }
        } else if (fuzzyLabel.indexOf("prenom") > -1 || fuzzyLabel.indexOf("prnom") > -1) {
          correspondingDatumField = optionalAllFields.find("firstname");
          Eif (correspondingDatumField.length > 0) {
            this.debug("This header matches an existing corpus field. ", correspondingDatumField);
            correspondingDatumField[0].labelFieldLinguists = field.labelFieldLinguists || incomingFieldIdOrLabel;
            correspondingDatumField[0].labelExperimenters = field.labelExperimenters || incomingFieldIdOrLabel;
          }
        } else if (fuzzyLabel.indexOf("nomdefamille") > -1) {
          correspondingDatumField = optionalAllFields.find("lastname");
          Eif (correspondingDatumField.length > 0) {
            this.debug("This header matches an existing corpus field. ", correspondingDatumField);
            correspondingDatumField[0].labelFieldLinguists = field.labelFieldLinguists || incomingFieldIdOrLabel;
            correspondingDatumField[0].labelExperimenters = field.labelExperimenters || incomingFieldIdOrLabel;
          }
        } else if (fuzzyLabel.indexOf("datedenaissance") > -1) {
          correspondingDatumField = optionalAllFields.find("dateofbirth");
          Eif (correspondingDatumField.length > 0) {
            this.debug("This header matches an existing corpus field. ", correspondingDatumField);
            correspondingDatumField[0].labelFieldLinguists = field.labelFieldLinguists || incomingFieldIdOrLabel;
            correspondingDatumField[0].labelExperimenters = field.labelExperimenters || incomingFieldIdOrLabel;
          }
        }
      }
 
      /* if the field is still not defined inthe corpus, construct a blank field with this label */
      if (!correspondingDatumField || correspondingDatumField.length === 0) {
        correspondingDatumField = [new DatumField(DatumField.prototype.defaults)];
        correspondingDatumField[0].id = incomingFieldIdOrLabel;
        correspondingDatumField[0].labelFieldLinguists = incomingFieldIdOrLabel;
        // correspondingDatumField[0].notInCorpus = true;
        optionalAllFields.add(correspondingDatumField[0]);
      }
      Eif (correspondingDatumField && correspondingDatumField[0]) {
        correspondingDatumField = correspondingDatumField[0];
      }
 
      this.debug("correspondingDatumField ", correspondingDatumField);
 
      Eif (correspondingDatumField instanceof DatumField) {
        return correspondingDatumField;
      } else {
        return new DatumField(correspondingDatumField);
      }
    }
  },
 
  prepareANewOfflinePouch: {
    value: function() {
      throw new Error("I dont know how to prepareANewOfflinePouch");
    }
  },
 
  /**
   * Accepts two functions to call back when save is successful or
   * fails. If the fail callback is not overridden it will alert
   * failure to the user.
   *
   * - Adds the corpus to the corpus if it is in the right corpus, and wasn't already there
   * - Adds the corpus to the user if it wasn't already there
   * - Adds an activity to the logged in user with diff in what the user changed.
   * @return {Promise} promise for the saved corpus
   */
  saveCorpus: {
    value: function() {
      var deferred = Q.defer(),
        self = this;
 
      var newModel = false;
      if (!this.id) {
        self.debug("New corpus");
        newModel = true;
      } else {
        self.debug("Existing corpus");
      }
      var oldrev = this.get("_rev");
 
      this.timestamp = Date.now();
 
      self.unsavedChanges = false;
      self.save().then(function(model) {
        var title = model.title;
        var differences = "#diff/oldrev/" + oldrev + "/newrev/" + model._rev;
        var verb = "modified";
        var verbicon = "icon-pencil";
        if (newModel) {
          verb = "added";
          verbicon = "icon-plus";
        }
        var teamid = self.dbname.split("-")[0];
        window.app.addActivity({
          verb: "<a href='" + differences + "'>" + verb + "</a> ",
          verbmask: verb,
          verbicon: verbicon,
          directobject: "<a href='#corpus/" + model.id + "'>" + title + "</a>",
          directobjectmask: "a corpus",
          directobjecticon: "icon-cloud",
          indirectobject: "created by <a href='#user/" + teamid + "'>" + teamid + "</a>",
          context: " via Offline App.",
          contextmask: "",
          teamOrPersonal: "personal"
        });
        window.app.addActivity({
          verb: "<a href='" + differences + "'>" + verb + "</a> ",
          verbmask: verb,
          verbicon: verbicon,
          directobject: "<a href='#corpus/" + model.id + "'>" + title + "</a>",
          directobjectmask: "a corpus",
          directobjecticon: "icon-cloud",
          indirectobject: "created by <a href='#user/" + teamid + "'>this team</a>",
          context: " via Offline App.",
          contextmask: "",
          teamOrPersonal: "team"
        });
        deferred.resolve(self);
      }, deferred.reject).fail(
        function(error) {
          console.error(error.stack, self);
          deferred.reject(error);
        });
 
      return deferred.promise;
    }
  },
 
  /**
   * If more views are added to corpora, add them here
   * @returns {} an object containing valid map reduce functions
   * TODO: add conversation search to the get_datum_fields function
   */
  validDBQueries: {
    value: function() {
      return {
        // activities: {
        //   url: "/_design/deprecated/_view/activities",
        //   map: requireoff("./../../map_reduce_unused/views/activities/map")
        // },
        // add_synctactic_category: {
        //   url: "/_design/deprecated/_view/add_synctactic_category",
        //   map: requireoff("./../../map_reduce_unused/views/add_synctactic_category/map")
        // },
        // audioIntervals: {
        //   url: "/_design/deprecated/_view/audioIntervals",
        //   map: requireoff("./../../map_reduce_unused/views/audioIntervals/map")
        // },
        // byCollection: {
        //   url: "/_design/deprecated/_view/byCollection",
        //   map: requireoff("./../../map_reduce_unused/views/byCollection/map")
        // },
        // by_date: {
        //   url: "/_design/deprecated/_view/by_date",
        //   map: requireoff("./../../map_reduce_unused/views/by_date/map")
        // },
        // by_rhyming: {
        //   url: "/_design/deprecated/_view/by_rhyming",
        //   map: requireoff("./../../map_reduce_unused/views/by_rhyming/map"),
        //   reduce: requireoff("./../../map_reduce_unused/views/by_rhyming/reduce")
        // },
        // cleaning_example: {
        //   url: "/_design/deprecated/_view/cleaning_example",
        //   map: requireoff("./../../map_reduce_unused/views/cleaning_example/map")
        // },
        // corpora: {
        //   url: "/_design/deprecated/_view/corpora",
        //   map: requireoff("./../../map_reduce_unused/views/corpora/map")
        // },
        // datalists: {
        //   url: "/_design/deprecated/_view/datalists",
        //   map: requireoff("./../../map_reduce_unused/views/datalists/map")
        // },
        // datums: {
        //   url: "/_design/deprecated/_view/datums",
        //   map: requireoff("./../../map_reduce_unused/views/datums/map")
        // },
        // datums_by_user: {
        //   url: "/_design/deprecated/_view/datums_by_user",
        //   map: requireoff("./../../map_reduce_unused/views/datums_by_user/map"),
        //   reduce: requireoff("./../../map_reduce_unused/views/datums_by_user/reduce")
        // },
        // datums_chronological: {
        //   url: "/_design/deprecated/_view/datums_chronological",
        //   map: requireoff("./../../map_reduce_unused/views/datums_chronological/map")
        // },
        // deleted: {
        //   url: "/_design/deprecated/_view/deleted",
        //   map: requireoff("./../../map_reduce_unused/views/deleted/map")
        // },
        // export_eopas_xml: {
        //   url: "/_design/deprecated/_view/export_eopas_xml",
        //   map: requireoff("./../../map_reduce_unused/views/export_eopas_xml/map"),
        //   reduce: requireoff("./../../map_reduce_unused/views/export_eopas_xml/reduce")
        // },
        // get_corpus_datum_tags: {
        //   url: "/_design/deprecated/_view/get_corpus_datum_tags",
        //   map: requireoff("./../../map_reduce_unused/views/get_corpus_datum_tags/map"),
        //   reduce: requireoff("./../../map_reduce_unused/views/get_corpus_datum_tags/reduce")
        // },
        // get_corpus_fields: {
        //   url: "/_design/deprecated/_view/get_corpus_fields",
        //   map: requireoff("./../../map_reduce_unused/views/get_corpus_fields/map")
        // },
        // get_corpus_validationStati: {
        //   url: "/_design/deprecated/_view/get_corpus_validationStati",
        //   map: requireoff("./../../map_reduce_unused/views/get_corpus_validationStati/map"),
        //   reduce: requireoff("./../../map_reduce_unused/views/get_corpus_validationStati/reduce")
        // },
        // get_datum_fields: {
        //   url: "/_design/deprecated/_view/get_datum_fields",
        //   map: requireoff("./../../map_reduce_unused/views/get_datum_fields/map")
        // },
        // get_datums_by_session_id: {
        //   url: "/_design/deprecated/_view/get_datums_by_session_id",
        //   map: requireoff("./../../map_reduce_unused/views/get_datums_by_session_id/map")
        // },
        // get_frequent_fields: {
        //   url: "/_design/deprecated/_view/get_frequent_fields",
        //   map: requireoff("./../../map_reduce_unused/views/get_frequent_fields/map"),
        //   reduce: requireoff("./../../map_reduce_unused/views/get_frequent_fields/reduce")
        // },
        // get_search_fields_chronological: {
        //   url: "/_design/deprecated/_view/get_search_fields_chronological",
        //   map: requireoff("./../../map_reduce_unused/views/get_search_fields_chronological/map")
        // },
        // glosses_in_utterance: {
        //   url: "/_design/deprecated/_view/glosses_in_utterance",
        //   map: requireoff("./../../map_reduce_unused/views/glosses_in_utterance/map"),
        //   reduce: requireoff("./../../map_reduce_unused/views/glosses_in_utterance/reduce")
        // },
        // lexicon_create_tuples: {
        //   url: "/_design/deprecated/_view/lexicon_create_tuples",
        //   map: requireoff("./../../map_reduce_unused/views/lexicon_create_tuples/map"),
        //   reduce: requireoff("./../../map_reduce_unused/views/lexicon_create_tuples/reduce")
        // },
        // morpheme_neighbors: {
        //   url: "/_design/deprecated/_view/morpheme_neighbors",
        //   map: requireoff("./../../map_reduce_unused/views/morpheme_neighbors/map"),
        //   reduce: requireoff("./../../map_reduce_unused/views/morpheme_neighbors/reduce")
        // },
        // morphemes_in_gloss: {
        //   url: "/_design/deprecated/_view/morphemes_in_gloss",
        //   map: requireoff("./../../map_reduce_unused/views/morphemes_in_gloss/map"),
        //   reduce: requireoff("./../../map_reduce_unused/views/morphemes_in_gloss/reduce")
        // },
        // recent_comments: {
        //   url: "/_design/deprecated/_view/recent_comments",
        //   map: requireoff("./../../map_reduce_unused/views/recent_comments/map")
        // },
        // sessions: {
        //   url: "/_design/deprecated/_view/sessions",
        //   map: requireoff("./../../map_reduce_unused/views/sessions/map")
        // },
        // users: {
        //   url: "/_design/deprecated/_view/users",
        //   map: requireoff("./../../map_reduce_unused/views/users/map")
        // },
        // word_list: {
        //   url: "/_design/deprecated/_view/word_list",
        //   map: requireoff("./../../map_reduce_unused/views/word_list/map"),
        //   reduce: requireoff("./../../map_reduce_unused/views/word_list/reduce")
        // },
        // map_reduce_unused_word_list_rdf: {
        //   url: "/_design/deprecated/_view/map_reduce_unused_word_list_rdf",
        //   map: requireoff("./../../map_reduce_unused/views/word_list_rdf/map"),
        //   reduce: requireoff("./../../map_reduce_unused/views/word_list_rdf/reduce")
        // }
      };
    }
  },
 
  validate: {
    value: function(attrs) {
      attrs = attrs || this;
      if (attrs.publicCorpus) {
        if (attrs.publicCorpus !== "Public") {
          if (attrs.publicCorpus !== "Private") {
            return "Corpus must be either Public or Private"; //TODO test this.
          }
        }
      }
    }
  },
 
  /**
   * This function takes in a dbname, which could be different
   * from the current corpus in case there is a master corpus with
   * more/better monolingual data.
   *
   * @param dbname
   * @param callback
   */
  buildMorphologicalAnalyzerFromTeamServer: {
    value: function(dbname, callback) {
      if (!dbname) {
        dbname = this.dbname;
      }
      this.glosser.downloadPrecedenceRules(dbname, this.glosserURL, callback);
    }
  },
  /**
   * This function takes in a dbname, which could be different
   * from the current corpus incase there is a master corpus wiht
   * more/better monolingual data.
   *
   * @param dbname
   * @param callback
   */
  buildLexiconFromTeamServer: {
    value: function(dbname, callback) {
      if (!dbname) {
        dbname = this.dbname;
      }
      this.lexicon.buildLexiconFromCouch(dbname, callback);
    }
  },
 
  /**
   * This function takes in a dbname, which could be different
   * from the current corpus incase there is a master corpus wiht
   * more representative datum
   * example : https://corpusdev.example.org/lingllama-cherokee/_design/deprecated/_view/get_frequent_fields?group=true
   *
   * It takes the values stored in the corpus, if set, otherwise it will take the values from this corpus since the window was last refreshed
   *
   * If a url is passed, it contacts the server for fresh info.
   *
   * @param dbname
   * @param callback
   */
  getFrequentDatumFields: {
    value: function() {
      return this.getFrequentValues("fields", ["judgement", "utterance", "morphemes", "gloss", "translation"]);
    }
  },
 
  /**
   * This function takes in a dbname, which could be different
   * from the current corpus incase there is a master corpus wiht
   * more representative datum
   * example : https://corpusdev.example.org/lingllama-cherokee/_design/deprecated/_view/get_corpus_validationStati?group=true
   *
   * It takes the values stored in the corpus, if set, otherwise it will take the values from this corpus since the window was last refreshed
   *
   * If a url is passed, it contacts the server for fresh info.
   *
   * @param dbname
   * @param callback
   */
  getFrequentDatumValidationStates: {
    value: function() {
      return this.getFrequentValues("validationStatus", ["Checked", "Deleted", "ToBeCheckedByAnna", "ToBeCheckedByBill", "ToBeCheckedByClaude"]);
    }
  },
 
  getCorpusSpecificLocalizations: {
    value: function(optionalLocaleCode) {
      var self = this;
 
      if (optionalLocaleCode) {
        this.todo("Test the loading of an optionalLocaleCode");
        this.get(optionalLocaleCode + "/messages.json").then(function(locale) {
          if (!locale) {
            self.warn("the requested locale was empty.");
            return;
          }
          self.application.contextualizer.addMessagesToContextualizedStrings("null", locale);
        }, function(error) {
          self.warn("The requested locale wasn't loaded");
          self.debug("locale loading error", error);
        }).fail(function(error) {
          console.error(error.stack, self);
        });
      } else {
        this.fetchCollection("locales").then(function(locales) {
          for (var localeIndex = 0; localeIndex < locales.length; localeIndex++) {
            if (!locales[localeIndex]) {
              self.warn("the requested locale was empty.");
              continue;
            }
            self.application.contextualizer.addMessagesToContextualizedStrings(null, locales[localeIndex]);
          }
        }, function(error) {
          self.warn("The locales didn't loaded");
          self.debug("locale loading error", error);
        }).fail(function(error) {
          console.error(error.stack, self);
        });
      }
 
      return this;
    }
  },
 
  getFrequentValues: {
    value: function(fieldname, defaults) {
      var deferred = Q.defer(),
        self;
 
      if (!defaults) {
        defaults = self["defaultFrequentDatum" + fieldname];
      }
 
      /* if we have already asked the server in this page load, return */
      if (self["frequentDatum" + fieldname]) {
        Q.nextTick(function() {
          deferred.resolve(self["frequentDatum" + fieldname]);
        });
        return deferred.promise;
      }
 
      // var jsonUrl = self.validDBQueries["get_corpus_" + fieldname].url + "?group=true&limit=100";
      this.fetchCollection("frequentDatum" + fieldname, 0, 0, 100, true).then(function(frequentValues) {
        /*
         * TODO Hide optionally specified values
         */
        self["frequentDatum" + fieldname] = frequentValues;
        deferred.resolve(frequentValues);
      }, function(response) {
        self.debug("resolving defaults for frequentDatum" + fieldname, response);
        deferred.resolve(defaults);
      });
 
      return deferred.promise;
    }
  },
  /**
   * This function takes in a dbname, which could be different
   * from the current corpus incase there is a master corpus wiht
   * more representative datum
   * example : https://corpusdev.example.org/lingllama-cherokee/_design/deprecated/_view/get_corpus_validationStati?group=true
   *
   * It takes the values stored in the corpus, if set, otherwise it will take the values from this corpus since the window was last refreshed
   *
   * If a url is passed, it contacts the server for fresh info.
   *
   * @param dbname
   * @param callback
   */
  getFrequentDatumTags: {
    value: function() {
      return this.getFrequentValues("tags", ["Passive", "WH", "Indefinte", "Generic", "Agent-y", "Causative", "Pro-drop", "Ambigous"]);
    }
  },
 
  toJSON: {
    value: function(includeEvenEmptyAttributes, removeEmptyAttributes) {
      this.debug("Customizing toJSON ", includeEvenEmptyAttributes, removeEmptyAttributes);
      var attributesNotToJsonify = ["gravatar", "OLAC_export_connections", "url"];
      var json = FieldDBObject.prototype.toJSON.apply(this, [includeEvenEmptyAttributes, removeEmptyAttributes, attributesNotToJsonify]);
 
      Iif (!json) {
        this.warn("Not returning json right now.");
        return;
      }
      Eif (this.team && typeof this.team.toJSON === "function") {
        json.team = this.team.toJSON();
      }
      if (this.confidential && typeof this.confidential.toJSON === "function") {
        json.confidential = this.confidential.toJSON();
      }
      if (this.activityConnection && typeof this.activityConnection.toJSON === "function") {
        json.activityConnection = this.activityConnection.toJSON();
      }
 
      this.debug(json);
      return json;
    }
  }
 
});
 
exports.Corpus = Corpus;
exports.FieldDatabase = Corpus;