<commit_before>(function() {
  'use strict';

  var app = angular.module('radar.patients.diagnoses');

  function controllerFactory(
    ModelListDetailController,
    PatientDiagnosisPermission,
    firstPromise,
    $injector,
    store,
    _,
    getRadarGroup
  ) {
    function PrimaryPatientDiagnosisController($scope) {
      var self = this;

      $injector.invoke(ModelListDetailController, self, {
        $scope: $scope,
        params: {
          permission: new PatientDiagnosisPermission($scope.patient)
        }
      });

      $scope.multiple = false;

      self.load(firstPromise([
        store.findMany('patient-diagnoses', {patient: $scope.patient.id, primaryGroup: $scope.cohort.id}),
        store.findMany('diagnoses', {primaryGroup: $scope.cohort.id}).then(function(diagnoses) {
          $scope.diagnoses = _.sortBy(diagnoses, 'name');
        }),
        store.findMany('biopsy-diagnoses').then(function(biopsyDiagnoses) {
          $scope.biopsyDiagnoses = biopsyDiagnoses;
        }),
        getRadarGroup().then(function(group) {
          $scope.sourceGroup = group;
        })
      ])).then(function() {
        var multiple = $scope.items.length > 1 || $scope.cohort.multipleDiagnoses;

        if ($scope.items.length === 0) {
          if (self.createPermission()) {
            create();
          } else {
            self.list();
          }
        } else if (multiple) {
          self.list();
        } else {
          self.view($scope.items[0]);
        }

        $scope.multiple = multiple;
      });

      $scope.create = create;

      function create() {
        var item = store.create('patient-diagnoses', {
          patient: $scope.patient.id,
          sourceGroup: $scope.sourceGroup,
        });
        self.edit(item);
      }
    }

    PrimaryPatientDiagnosisController.$inject = ['$scope'];
    PrimaryPatientDiagnosisController.prototype = Object.create(ModelListDetailController.prototype);

    return PrimaryPatientDiagnosisController;
  }

  controllerFactory.$inject = [
    'ModelListDetailController',
    'PatientDiagnosisPermission',
    'firstPromise',
    '$injector',
    'store',
    '_',
    'getRadarGroup'
  ];

  app.factory('PrimaryPatientDiagnosisController', controllerFactory);

  app.directive('primaryPatientDiagnosisComponent', ['PrimaryPatientDiagnosisController', function(PrimaryPatientDiagnosisController) {
    return {
      scope: {
        patient: '=',
        cohort: '='
      },
      controller: PrimaryPatientDiagnosisController,
      templateUrl: 'app/patients/diagnoses/primary-diagnosis-component.html'
    };
  }]);
})();
<commit_msg>Add TODO<commit_after>(function() {
  'use strict';

  var app = angular.module('radar.patients.diagnoses');

  function controllerFactory(
    ModelListDetailController,
    PatientDiagnosisPermission,
    firstPromise,
    $injector,
    store,
    _,
    getRadarGroup
  ) {
    function PrimaryPatientDiagnosisController($scope) {
      var self = this;

      $injector.invoke(ModelListDetailController, self, {
        $scope: $scope,
        params: {
          permission: new PatientDiagnosisPermission($scope.patient)
        }
      });

      $scope.multiple = false;

      self.load(firstPromise([
        store.findMany('patient-diagnoses', {patient: $scope.patient.id, primaryGroup: $scope.cohort.id}),
        store.findMany('diagnoses', {primaryGroup: $scope.cohort.id}).then(function(diagnoses) {
          $scope.diagnoses = _.sortBy(diagnoses, 'name');
        }),
        store.findMany('biopsy-diagnoses').then(function(biopsyDiagnoses) {
          $scope.biopsyDiagnoses = biopsyDiagnoses;
        }),
        getRadarGroup().then(function(group) {
          $scope.sourceGroup = group;
        })
      ])).then(function() {
        // TODO this won't handle a UKRDC primary diagnoses being entered before a RaDaR one
        var multiple = $scope.items.length > 1 || $scope.cohort.multipleDiagnoses;

        if ($scope.items.length === 0) {
          if (self.createPermission()) {
            create();
          } else {
            self.list();
          }
        } else if (multiple) {
          self.list();
        } else {
          self.view($scope.items[0]);
        }

        $scope.multiple = multiple;
      });

      $scope.create = create;

      function create() {
        var item = store.create('patient-diagnoses', {
          patient: $scope.patient.id,
          sourceGroup: $scope.sourceGroup,
        });
        self.edit(item);
      }
    }

    PrimaryPatientDiagnosisController.$inject = ['$scope'];
    PrimaryPatientDiagnosisController.prototype = Object.create(ModelListDetailController.prototype);

    return PrimaryPatientDiagnosisController;
  }

  controllerFactory.$inject = [
    'ModelListDetailController',
    'PatientDiagnosisPermission',
    'firstPromise',
    '$injector',
    'store',
    '_',
    'getRadarGroup'
  ];

  app.factory('PrimaryPatientDiagnosisController', controllerFactory);

  app.directive('primaryPatientDiagnosisComponent', ['PrimaryPatientDiagnosisController', function(PrimaryPatientDiagnosisController) {
    return {
      scope: {
        patient: '=',
        cohort: '='
      },
      controller: PrimaryPatientDiagnosisController,
      templateUrl: 'app/patients/diagnoses/primary-diagnosis-component.html'
    };
  }]);
})();
<|endoftext|>


<commit_before>// Remove label before colon.
function stripColon(text) {
    var i = text.indexOf(":");
    if (i >= 0) {
        text = text.substr(i).trim();
        if (text[1] == " ") {
            text = text.substr(1).trim();
        }
    }
    return text;
}

// Split right label
function splitLabel(text) {
    var label = "", right = "";
    var i = text.lastIndexOf(":");
    if (i >= 0) {
        right = text.substr(i + 1).trim();
        if (right) {
            text = text.substr(0, i);

            i = text.lastIndexOf(" ");
            if (i >= 0) {
                label = text.substr(i + 1);
                if (label) {
                    text = text.substr(0, i);
                }
            }
        }
    }
    return [text, label, right];
}

var escapeTable = {
    "<": "&lt",
    "&": "&"
};

// escape character to html entity
function escape(s) {
    var s2 = "", i;

    for (i = 0; i < s.length; i++) {
        if (s.charCodeAt(i) & 0x80) {
            // ignore cjk
            s2 += s.substr(i, 2);
            i++;
            continue;
        } else if (escapeTable[s[i]]) {
            s2 += escapeTable[s[i]];
        } else {
            s2 += s[i];
        }
    }

    return s2;
}

function Span(f, b, l) {
    this.f = f;
    this.b = b;
    this.l = l;
    this.flash = false;
    this.halfStart = false;
    this.halfEnd = false;
    this.text = "";
    this.i = 0;
}

Span.prototype.toString = function() {
    if (!this.text) {
        return "";
    }

    var cls = "f" + this.f + " b" + this.b,
        w = this.text.length;

    if (this.l) {
        cls += " l";
    }
    if (this.flash) {
        cls += " flash";
    }
    if (this.halfStart) {
        cls += " half-start";
        w--;
    }
    if (this.halfEnd) {
        cls += " half-end";
        w--;
    }
    cls += " w" + w;
    return "" + escape(this.text) + "";
};

Span.prototype.copy = function() {
    var span = new Span(this.f, this.b, this.l);
    span.flash = this.flash;
    return span;
};

Span.prototype.reset = function() {
    this.f = 7;
    this.b = 0;
    this.l = false;
    this.flash = false;
}

// create head line
function makeHead(lLabel, lText, rLabel, rText) {
    if (!lText) {
        return "";
    }

    var fillSpace = 78, result = "
";

    fillSpace -= 2 + lLabel.length + 1 + lText.length;

    if (rText) {
        fillSpace -= 2 + rLabel.length + 2 + rText.length;
    }

    if (fillSpace < 0) {
        fillSpace = 0;
    }

    var span = new Span(4, 7, false);

    span.text = " " + lLabel + " ";

    result += span.toString();

    span.f = 7;
    span.b = 4;
    span.text = " " + lText + " ".repeat(fillSpace);

    result += span.toString();

    // result += makeSpan({f:4,b:7,text:" "+lLabel+" "}) + makeSpan({f:7,b:4,text:" "+lText+" ".repeat(fillSpace)});

    if (rText) {
        span.f = 4;
        span.b = 7;
        span.text = " " + rLabel + " ";

        result += span.toString();

        span.f = 7;
        span.b = 4;
        span.text = " " + rText + " ";

        result += span.toString();
        // result += makeSpan({f:4,b:7,text:" "+rLabel+" "}) + makeSpan({f:7,b:4,text:" "+rText+" "});
    }

    result += "
";

    return result;
}

// extract text to color
function extractColor(text, i, color) {
    var re = /\033\[([\d;]*)m/g;
    re.lastIndex = i;
    var match = re.exec(text);
    if (!match || match.index != i) {
        return null;
    }

    var span = color.copy();
    span.i = re.lastIndex;

    var tokens = match[1].split(";");
    var code;

    for (i = 0; i < tokens.length; i++) {
        code = +tokens[i];
        if (code == 0) {
            span.reset();
        } else if (code == 1) {
            span.l = true;
        } else if (code == 5) {
            span.flash = true;
        } else if (code == 7) {
            var t = span.f;
            span.f = span.b;
            span.b = t;
        } else if (code < 40) {
            span.f = code - 30;
        } else if (code < 50) {
            span.b = code - 40;
        }
    }
    return span;
}

// convert ansi string into html
function bbsReader(data) {
    var i = 0, match, result = "";

    var author, title, time, label, board;

    if ((match = /^(\xa7@\xaa\xcc:.*)\n(.*)\n(.*)\n/.exec(data))) {
        // draw header
        author = stripColon(match[1]);
        title = stripColon(match[2]);
        time = stripColon(match[3]);

        // find board
        var t = splitLabel(author);
        author = t[0];
        label = t[1];
        board = t[2];

        // 作者
        result += makeHead("\xa7@\xaa\xcc", author, label, board);
        // 標題
        result += makeHead("\xbc\xd0\xc3D", title);
        // 時間
        result += makeHead("\xae\xc9\xb6\xa1", time);

        // ─
        result += "
" + "\xa2w".repeat(39) + "
";

        i += match[0].length;
    }

    var span = new Span(7, 0, false),
        pos = 0, cleanLine = false, cjk = false;

    result += "
";

    for (; i < data.length; i++) {
        // Special color
        if (pos == 0) {
            var ch = data.substr(i, 2);
            if (ch == "\xa1\xb0") {
                // ※
                cleanLine = true;
                span.reset();
                span.f = 2;
            } else if (ch == ": ") {
                // :
                cleanLine = true;
                span.reset();
                span.f = 6;
            }
        }
        if (data[i] == "\x1b") {
            // ESC
            var span2 = extractColor(data, i, span);
            if (!span2) {
                span.text += data[i];
                pos++;
            } else if (cjk && data[span2.i] != "\n") {
                span.text += data[span2.i];
                span.halfEnd = true;

                result += span.toString();

                span2.text += span.text.substring(span.text.length - 2);
                span2.halfStart = true;

                pos++;
                i = span2.i;
                span = span2;
                cjk = false;
            } else {
                cjk = false;
                result += span.toString();
                i = span2.i - 1;
                span = span2;
            }
        } else if (data[i] == "\r") {
            continue;
        } else if (data[i] == "\n") {
            result += span.toString() + "

";
            span.text = "";
            span.halfStart = false;
            span.halfEnd = false;
            cjk = false;

            if (cleanLine) {
                span.reset();
                cleanLine = false;
            }

            pos = 0;
        } else {
            if (cjk) {
                cjk = false;
            } else if (data.charCodeAt(i) & 0x80) {
                cjk = true;
            }
            span.text += data[i];
            pos++;
        }
    }

    result += span.toString() + "
";

    return {
        html: result,
        title: title,
        author: author,
        time: time
    };
}

module.exports = bbsReader;
<commit_msg>Support continued ansi token<commit_after>// Remove label before colon.
function stripColon(text) {
    var i = text.indexOf(":");
    if (i >= 0) {
        text = text.substr(i).trim();
        if (text[1] == " ") {
            text = text.substr(1).trim();
        }
    }
    return text;
}

// Split right label
function splitLabel(text) {
    var label = "", right = "";
    var i = text.lastIndexOf(":");
    if (i >= 0) {
        right = text.substr(i + 1).trim();
        if (right) {
            text = text.substr(0, i);

            i = text.lastIndexOf(" ");
            if (i >= 0) {
                label = text.substr(i + 1);
                if (label) {
                    text = text.substr(0, i);
                }
            }
        }
    }
    return [text, label, right];
}

var escapeTable = {
    "<": "&lt",
    "&": "&"
};

// escape character to html entity
function escape(s) {
    var s2 = "", i;

    for (i = 0; i < s.length; i++) {
        if (s.charCodeAt(i) & 0x80) {
            // ignore cjk
            s2 += s.substr(i, 2);
            i++;
            continue;
        } else if (escapeTable[s[i]]) {
            s2 += escapeTable[s[i]];
        } else {
            s2 += s[i];
        }
    }

    return s2;
}

function Span(f, b, l) {
    this.f = f;
    this.b = b;
    this.l = l;
    this.flash = false;
    this.halfStart = false;
    this.halfEnd = false;
    this.text = "";
    this.i = 0;
}

Span.prototype.toString = function() {
    if (!this.text) {
        return "";
    }

    var cls = "f" + this.f + " b" + this.b,
        w = this.text.length;

    if (this.l) {
        cls += " l";
    }
    if (this.flash) {
        cls += " flash";
    }
    if (this.halfStart) {
        cls += " half-start";
        w--;
    }
    if (this.halfEnd) {
        cls += " half-end";
        w--;
    }
    cls += " w" + w;
    return "" + escape(this.text) + "";
};

Span.prototype.copy = function() {
    var span = new Span(this.f, this.b, this.l);
    span.flash = this.flash;
    return span;
};

Span.prototype.reset = function() {
    this.f = 7;
    this.b = 0;
    this.l = false;
    this.flash = false;
}

// create head line
function makeHead(lLabel, lText, rLabel, rText) {
    if (!lText) {
        return "";
    }

    var fillSpace = 78, result = "
";

    fillSpace -= 2 + lLabel.length + 1 + lText.length;

    if (rText) {
        fillSpace -= 2 + rLabel.length + 2 + rText.length;
    }

    if (fillSpace < 0) {
        fillSpace = 0;
    }

    var span = new Span(4, 7, false);

    span.text = " " + lLabel + " ";

    result += span.toString();

    span.f = 7;
    span.b = 4;
    span.text = " " + lText + " ".repeat(fillSpace);

    result += span.toString();

    // result += makeSpan({f:4,b:7,text:" "+lLabel+" "}) + makeSpan({f:7,b:4,text:" "+lText+" ".repeat(fillSpace)});

    if (rText) {
        span.f = 4;
        span.b = 7;
        span.text = " " + rLabel + " ";

        result += span.toString();

        span.f = 7;
        span.b = 4;
        span.text = " " + rText + " ";

        result += span.toString();
        // result += makeSpan({f:4,b:7,text:" "+rLabel+" "}) + makeSpan({f:7,b:4,text:" "+rText+" "});
    }

    result += "
";

    return result;
}

// extract text to color
function extractColor(text, i, color) {
    var re = /\033\[([\d;]*)m/g;
    re.lastIndex = i;
    var matches = [],
        match;
    do {
        match = re.exec(text);
        if (!match || match.index != i) {
            break;
        }
        matches.push(match);
        i = re.lastIndex;
    } while (text[re.lastIndex] == "\x1b");

    if (!matches.length) {
        return null;
    }

    var tokens = matches.map(function(match){
        return match[1].split(";");
    });
    tokens = Array.prototype.concat.call([], tokens);

    var span = color.copy();
    span.i = re.lastIndex;

    var tokens = match[1].split(";");
    var code;

    for (i = 0; i < tokens.length; i++) {
        code = +tokens[i];
        if (code == 0) {
            span.reset();
        } else if (code == 1) {
            span.l = true;
        } else if (code == 5) {
            span.flash = true;
        } else if (code == 7) {
            var t = span.f;
            span.f = span.b;
            span.b = t;
        } else if (code < 40) {
            span.f = code - 30;
        } else if (code < 50) {
            span.b = code - 40;
        }
    }
    return span;
}

// convert ansi string into html
function bbsReader(data) {
    var i = 0, match, result = "";

    var author, title, time, label, board;

    if ((match = /^(\xa7@\xaa\xcc:.*)\n(.*)\n(.*)\n/.exec(data))) {
        // draw header
        author = stripColon(match[1]);
        title = stripColon(match[2]);
        time = stripColon(match[3]);

        // find board
        var t = splitLabel(author);
        author = t[0];
        label = t[1];
        board = t[2];

        // 作者
        result += makeHead("\xa7@\xaa\xcc", author, label, board);
        // 標題
        result += makeHead("\xbc\xd0\xc3D", title);
        // 時間
        result += makeHead("\xae\xc9\xb6\xa1", time);

        // ─
        result += "
" + "\xa2w".repeat(39) + "
";

        i += match[0].length;
    }

    var span = new Span(7, 0, false),
        pos = 0, cleanLine = false, cjk = false;

    result += "
";

    for (; i < data.length; i++) {
        // Special color
        if (pos == 0) {
            var ch = data.substr(i, 2);
            if (ch == "\xa1\xb0") {
                // ※
                cleanLine = true;
                span.reset();
                span.f = 2;
            } else if (ch == ": ") {
                // :
                cleanLine = true;
                span.reset();
                span.f = 6;
            }
        }
        if (data[i] == "\x1b") {
            // ESC
            var span2 = extractColor(data, i, span);
            if (!span2) {
                span.text += data[i];
                pos++;
            } else if (cjk && data[span2.i] != "\n") {
                span.text += data[span2.i];
                span.halfEnd = true;

                result += span.toString();

                span2.text += span.text.substring(span.text.length - 2);
                span2.halfStart = true;

                pos++;
                i = span2.i;
                span = span2;
                cjk = false;
            } else {
                cjk = false;
                result += span.toString();
                i = span2.i - 1;
                span = span2;
            }
        } else if (data[i] == "\r") {
            continue;
        } else if (data[i] == "\n") {
            result += span.toString() + "

";
            span.text = "";
            span.halfStart = false;
            span.halfEnd = false;
            cjk = false;

            if (cleanLine) {
                span.reset();
                cleanLine = false;
            }

            pos = 0;
        } else {
            if (cjk) {
                cjk = false;
            } else if (data.charCodeAt(i) & 0x80) {
                cjk = true;
            }
            span.text += data[i];
            pos++;
        }
    }

    result += span.toString() + "
";

    return {
        html: result,
        title: title,
        author: author,
        time: time
    };
}

module.exports = bbsReader;
<|endoftext|>


<commit_before>/**
 * jsPDF viewerPreferences Plugin
 * @author Aras Abbasi (github.com/arasabbasi)
 * Licensed under the MIT License.
 * http://opensource.org/licenses/mit-license
 */

 /**
 * Adds the ability to set viewerPreferences
 *
 * @returns {jsPDF}
 * @name viewerpreferences
 * @example
 * var doc = new jsPDF()
 * doc.text(10, 10, "This is a test")
 * doc.viewerPreferences({"FitWindow":true});
 * doc.save("viewerPreferences.pdf")
 */

(function (jsPDFAPI) {
    "use strict";

    var configuration = {
        "HideToolbar": {defaultValue: false, value: false, type: "boolean", explicitSet: false, valueSet: [true, false], pdfVersion: 1.3},
        "HideMenubar": {defaultValue: false, value: false, type: "boolean", explicitSet: false, valueSet: [true, false], pdfVersion: 1.3},
        "HideWindowUI": {defaultValue: false, value: false, type: "boolean", explicitSet: false, valueSet: [true, false], pdfVersion: 1.3},
        "FitWindow": {defaultValue: false, value: false, type: "boolean", explicitSet: false, valueSet: [true, false], pdfVersion: 1.3},
        "CenterWindow": {defaultValue: false, value: false, type: "boolean", explicitSet: false, valueSet: [true, false], pdfVersion: 1.3},
        "DisplayDocTitle": {defaultValue: false, value: false, type: "boolean", explicitSet: false, valueSet: [true, false], pdfVersion: 1.4},
        "NonFullScreenPageMode": {defaultValue: "UseNone", value: "UseNone", type: "name", explicitSet: false, valueSet: ["UseNone", "UseOutlines", "UseThumbs", "UseOC"], pdfVersion: 1.3},
        "Direction": {defaultValue: "L2R", value: "L2R", type: "name", explicitSet: false, valueSet: ["L2R", "R2L"], pdfVersion: 1.3},
        "ViewArea": {defaultValue: "CropBox", value: "CropBox", type: "name", explicitSet: false, valueSet: ["MediaBox", "CropBox", "TrimBox", "BleedBox", "ArtBox"], pdfVersion: 1.4},
        "ViewClip": {defaultValue: "CropBox", value: "CropBox", type: "name", explicitSet: false, valueSet: ["MediaBox", "CropBox", "TrimBox", "BleedBox", "ArtBox"], pdfVersion: 1.4},
        "PrintArea": {defaultValue: "CropBox", value: "CropBox", type: "name", explicitSet: false, valueSet: ["MediaBox", "CropBox", "TrimBox", "BleedBox", "ArtBox"], pdfVersion: 1.4},
        "PrintClip": {defaultValue: "CropBox", value: "CropBox", type: "name", explicitSet: false, valueSet: ["MediaBox", "CropBox", "TrimBox", "BleedBox", "ArtBox"], pdfVersion: 1.4},
        "PrintScaling": {defaultValue: "AppDefault", value: "AppDefault", type: "name", explicitSet: false, valueSet: ["AppDefault", "None"], pdfVersion: 1.6},
        "Duplex": {defaultValue: "none", value: "none", type: "name", explicitSet: false, valueSet: ["Simplex", "DuplexFlipShortEdge", "DuplexFlipLongEdge", "none"], pdfVersion: 1.7},
        "PickTrayByPDFSize": {defaultValue: false, value: false, type: "boolean", explicitSet: false, valueSet: [true, false], pdfVersion: 1.7},
        "PrintPageRange": {defaultValue: "", value: "", type: "array", explicitSet: false, valueSet: null, pdfVersion: 1.7},
        "NumCopies": {defaultValue: 1, value: 1, type: "integer", explicitSet: false, valueSet: null, pdfVersion: 1.7}
    };

    var eventsAreEnabled = false;
    var configurationKeys = Object.keys(configuration);

    function arrayContainsElement(array, elementName) {
        var i;
        var result = false;

        for (i = 0; i < array.length; i += 1) {
            if (array[i] === elementName) {
                result = true;
            }
        }
        return result;
    }

    function setter(method, value) {
        var rangeArray = [];
        var i = 0;
        var j = 0;
        var isValid = true;
        if (value === undefined) {
            return configuration[method].value;
        }
        if (configuration[method].type === "boolean" && typeof value === "boolean") {
            configuration[method].value = value;
        } else if (configuration[method].type === "name" && arrayContainsElement(configuration[method].valueSet, value)) {
            configuration[method].value = value;
        } else if (configuration[method].type === "integer" && Number.isInteger(value)) {
            configuration[method].value = value;
        } else if (configuration[method].type === "array") {

            for (i = 0; i < value.length; i += 1) {
                isValid = true;
                if (value[i].length === 1 && typeof value[i][0] === "number") {
                    rangeArray.push(String(value[i]));
                } else if (value[i].length > 1) {
                    for (j = 0; j < value[i].length; j += 1) {
                        if (typeof value[i][j] !== "number") {
                            isValid = false;
                        }
                    }
                    if (isValid === true) {
                        rangeArray.push(String(value[i].join("-")));
                    }
                }
            }
            configuration[method].value = String(rangeArray);
        } else {
            configuration[method].value = configuration[method].defaultValue;
        }

        configuration[method].explicitSet = true;

        return configuration[method].value;
    }

    function resetConfiguration() {
        var i = 0;
        var len = configuration.length;

        for (i = 0; i < len; i += 1) {
            configuration[i].value = configuration[i].defaultValue;
            configuration[i].explicitSet = false;
        }
    }

    jsPDFAPI.viewerPreferences = function (options, doReset) {
        options = options || {};
        doReset = doReset || false;

        if (options === "reset" || doReset === true) {
            return resetConfiguration();
        }

        if (typeof options === "object") {
            var elem;
            for (elem in options) {
                if (arrayContainsElement(configurationKeys, elem)) {
                    setter(elem, options[elem]);
                }
            }
        }

        if (eventsAreEnabled === false) {
            this.internal.events.subscribe("putCatalog", function () {
                var pdfDict = [];
                var vPref;
                for (vPref in configuration) {
                    if (configuration[vPref].explicitSet === true) {
                        if (configuration[vPref].type === "name") {
                            pdfDict.push("/" + vPref + " /" + configuration[vPref].value);
                        } else {
                            pdfDict.push("/" + vPref + " " + configuration[vPref].value);
                        }
                    }
                }
                if (pdfDict.length !== 0) {
                    this.internal.write("/ViewerPreferences" + "<<\n" + pdfDict.join("\n") + "\n>>");
                }
            });
            eventsAreEnabled = true;
        }
    };
})(jsPDF.API);
<commit_msg>Update viewerpreferences.js<commit_after>/**
 * jsPDF viewerPreferences Plugin
 * @author Aras Abbasi (github.com/arasabbasi)
 * Licensed under the MIT License.
 * http://opensource.org/licenses/mit-license
 */

 /**
 * Adds the ability to set viewerPreferences
 *
 * @returns {jsPDF}
 * @name viewerpreferences
 * @example
 * var doc = new jsPDF()
 * doc.text(10, 10, "This is a test")
 * doc.viewerPreferences({"FitWindow":true});
 * doc.save("viewerPreferences.pdf")
 */

(function (jsPDFAPI) {
    "use strict";

    jsPDFAPI.viewerPreferences = function (options, doReset) {
        options = options || {};
        doReset = doReset || false;

        var configuration;
        var configurationTemplate = {
            "HideToolbar": {defaultValue: false, value: false, type: "boolean", explicitSet: false, valueSet: [true, false], pdfVersion: 1.3},
            "HideMenubar": {defaultValue: false, value: false, type: "boolean", explicitSet: false, valueSet: [true, false], pdfVersion: 1.3},
            "HideWindowUI": {defaultValue: false, value: false, type: "boolean", explicitSet: false, valueSet: [true, false], pdfVersion: 1.3},
            "FitWindow": {defaultValue: false, value: false, type: "boolean", explicitSet: false, valueSet: [true, false], pdfVersion: 1.3},
            "CenterWindow": {defaultValue: false, value: false, type: "boolean", explicitSet: false, valueSet: [true, false], pdfVersion: 1.3},
            "DisplayDocTitle": {defaultValue: false, value: false, type: "boolean", explicitSet: false, valueSet: [true, false], pdfVersion: 1.4},
            "NonFullScreenPageMode": {defaultValue: "UseNone", value: "UseNone", type: "name", explicitSet: false, valueSet: ["UseNone", "UseOutlines", "UseThumbs", "UseOC"], pdfVersion: 1.3},
            "Direction": {defaultValue: "L2R", value: "L2R", type: "name", explicitSet: false, valueSet: ["L2R", "R2L"], pdfVersion: 1.3},
            "ViewArea": {defaultValue: "CropBox", value: "CropBox", type: "name", explicitSet: false, valueSet: ["MediaBox", "CropBox", "TrimBox", "BleedBox", "ArtBox"], pdfVersion: 1.4},
            "ViewClip": {defaultValue: "CropBox", value: "CropBox", type: "name", explicitSet: false, valueSet: ["MediaBox", "CropBox", "TrimBox", "BleedBox", "ArtBox"], pdfVersion: 1.4},
            "PrintArea": {defaultValue: "CropBox", value: "CropBox", type: "name", explicitSet: false, valueSet: ["MediaBox", "CropBox", "TrimBox", "BleedBox", "ArtBox"], pdfVersion: 1.4},
            "PrintClip": {defaultValue: "CropBox", value: "CropBox", type: "name", explicitSet: false, valueSet: ["MediaBox", "CropBox", "TrimBox", "BleedBox", "ArtBox"], pdfVersion: 1.4},
            "PrintScaling": {defaultValue: "AppDefault", value: "AppDefault", type: "name", explicitSet: false, valueSet: ["AppDefault", "None"], pdfVersion: 1.6},
            "Duplex": {defaultValue: "none", value: "none", type: "name", explicitSet: false, valueSet: ["Simplex", "DuplexFlipShortEdge", "DuplexFlipLongEdge", "none"], pdfVersion: 1.7},
            "PickTrayByPDFSize": {defaultValue: false, value: false, type: "boolean", explicitSet: false, valueSet: [true, false], pdfVersion: 1.7},
            "PrintPageRange": {defaultValue: "", value: "", type: "array", explicitSet: false, valueSet: null, pdfVersion: 1.7},
            "NumCopies": {defaultValue: 1, value: 1, type: "integer", explicitSet: false, valueSet: null, pdfVersion: 1.7}
        };

        var configurationKeys = Object.keys(configurationTemplate);

        var rangeArray = [];
        var i = 0;
        var j = 0;
        var k = 0;
        var isValid = true;

        var method;
        var value;

        function arrayContainsElement(array, element) {
            var iterator;
            var result = false;

            for (iterator = 0; iterator < array.length; iterator += 1) {
                if (array[iterator] === element) {
                    result = true;
                }
            }
            return result;
        }

        if (this.internal.viewerpreferences === undefined) {
            this.internal.viewerpreferences = {};
            this.internal.viewerpreferences.configuration = JSON.parse(JSON.stringify(configurationTemplate));
            this.internal.viewerpreferences.isSubscribed = false;
        }
        configuration = this.internal.viewerpreferences.configuration;

        if (options === "reset" || doReset === true) {
            var len = configurationKeys.length;

            for (k = 0; k < len; k += 1) {
                configuration[configurationKeys[k]].value = configuration[configurationKeys[k]].defaultValue;
                configuration[configurationKeys[k]].explicitSet = false;
            }
        }

        if (typeof options === "object") {
            for (method in options) {
                value = options[method];
                if (arrayContainsElement(configurationKeys, method) && value !== undefined) {

                    if (configuration[method].type === "boolean" && typeof value === "boolean") {
                        configuration[method].value = value;
                    } else if (configuration[method].type === "name" && arrayContainsElement(configuration[method].valueSet, value)) {
                        configuration[method].value = value;
                    } else if (configuration[method].type === "integer" && Number.isInteger(value)) {
                        configuration[method].value = value;
                    } else if (configuration[method].type === "array") {

                        for (i = 0; i < value.length; i += 1) {
                            isValid = true;
                            if (value[i].length === 1 && typeof value[i][0] === "number") {
                                rangeArray.push(String(value[i]));
                            } else if (value[i].length > 1) {
                                for (j = 0; j < value[i].length; j += 1) {
                                    if (typeof value[i][j] !== "number") {
                                        isValid = false;
                                    }
                                }
                                if (isValid === true) {
                                    rangeArray.push(String(value[i].join("-")));
                                }
                            }
                        }
                        configuration[method].value = String(rangeArray);
                    } else {
                        configuration[method].value = configuration[method].defaultValue;
                    }

                    configuration[method].explicitSet = true;
                }
            }
        }

        if (this.internal.viewerpreferences.isSubscribed === false) {
            this.internal.events.subscribe("putCatalog", function () {
                var pdfDict = [];
                var vPref;
                for (vPref in configuration) {
                    if (configuration[vPref].explicitSet === true) {
                        if (configuration[vPref].type === "name") {
                            pdfDict.push("/" + vPref + " /" + configuration[vPref].value);
                        } else {
                            pdfDict.push("/" + vPref + " " + configuration[vPref].value);
                        }
                    }
                }
                if (pdfDict.length !== 0) {
                    this.internal.write("/ViewerPreferences" + "<<\n" + pdfDict.join("\n") + "\n>>");
                }
            });
            this.internal.viewerpreferences.isSubscribed = true;
        }

        this.internal.viewerpreferences.configuration = configuration;
    };
})(jsPDF.API);
<|endoftext|>


<commit_before>function CheckInsWindow(title) {
	var global = require('ui/common/globals');
	// Creates the default window with global color scheme
	var self = global.createWindow(title);

	// "Search for wine" text field
	var wines = Titanium.UI.createTextField({
		backgroundColor:'#FFF',
		top:80,
		left:20,
		width:350,
		height:40,
		hintText:'  Search for a wine...',
		paddingLeft:8,
		paddingRight:8,
		borderStyle:Ti.UI.INPUT_BORDERSTYLE_ROUNDED,
		keyboardType:Titanium.UI.KEYBOARD_DEFAULT,
	    returnKeyType:Titanium.UI.RETURNKEY_NEXT,
	    suppressReturn:false
	});

	// "Year" text field
	var year = Titanium.UI.createTextField({
		backgroundColor:'#FFF',
		bottom:170,
		left:20,
		width:165,
		height:40,
		hintText:'  Year...',
		paddingLeft:8,
		paddingRight:8,
		borderStyle:Ti.UI.INPUT_BORDERSTYLE_ROUNDED,
		keyboardType:Titanium.UI.KEYBOARD_DEFAULT,
	    returnKeyType:Titanium.UI.RETURNKEY_NEXT,
	    suppressReturn:false
	});

	// "Style" text field
	var style = Titanium.UI.createTextField({
		backgroundColor:'#FFF',
		bottom:170,
		right:20,
		width:165,
		height:40,
		hintText:'  Style...',
		paddingLeft:8,
		paddingRight:8,
		borderStyle:Ti.UI.INPUT_BORDERSTYLE_ROUNDED,
		keyboardType:Titanium.UI.KEYBOARD_DEFAULT,
	    returnKeyType:Titanium.UI.RETURNKEY_NEXT,
	    suppressReturn:false
	});

	// Creates "Look-Up" button
	var btn = Titanium.UI.createButton({
		color:'#000',
		title:"Look-Up",
		font:{fontSize:22},
		top: 150,
		width:200,
		height:45
	});

	// Creates "Browse" button
	var btn2 = Titanium.UI.createButton({
		color:'#000',
		title:"Browse",
		font:{fontSize:22},
		bottom:100,
		width:200,
		height:45
	});

	// Creates label for "browsing by year/style"
	var label1 = Titanium.UI.createLabel({
		color:'#000',            // Black color
		text:'Browse By Year/Style',
		font:{fontSize:25,fontFamily:'Helvetica Neue'},
		textAlign:'center',
		width:'auto'
	});

	// Displays pop-up message after clicking buttons
	btn.addEventListener("click", function(e){
		alert(e.source + " RESULTS FOR SEARCH");
	});
	btn2.addEventListener("click", function(e){
		alert(e.source + " RESULTS FOR BROWSING");
	});

	self.add(wines);
	self.add(year);
	self.add(style);
	self.add(btn);
	self.add(btn2);
	self.add(label1);
	//self.open();
	global.outputHook(self);
	return self;
};

module.exports = CheckInsWindow;<commit_msg>Check-In Window Fixes<commit_after>function CheckInsWindow(title) {
	var global = require('ui/common/globals');
	// Creates the default window with global color scheme
	var self = global.createWindow(title);

	// "Search for wine" text field
	var wines = Titanium.UI.createTextField({
		backgroundColor:'#FFF',
		top:20,
		//left:20,
		width:'80%',
		height:40,
		hintText:'  Search for a wine...',
		paddingLeft:8,
		paddingRight:8,
		borderStyle:Ti.UI.INPUT_BORDERSTYLE_ROUNDED,
		keyboardType:Titanium.UI.KEYBOARD_DEFAULT,
	    returnKeyType:Titanium.UI.RETURNKEY_NEXT,
	    suppressReturn:false
	});

	// "Year" text field
	var year = Titanium.UI.createTextField({
		backgroundColor:'#FFF',
		bottom:170,
		left:20,
		width:'40%',
		height:40,
		hintText:'  Year...',
		paddingLeft:8,
		paddingRight:8,
		borderStyle:Ti.UI.INPUT_BORDERSTYLE_ROUNDED,
		keyboardType:Titanium.UI.KEYBOARD_DEFAULT,
	    returnKeyType:Titanium.UI.RETURNKEY_NEXT,
	    suppressReturn:false
	});

	// "Style" text field
	var style = Titanium.UI.createTextField({
		backgroundColor:'#FFF',
		bottom:170,
		right:20,
		width:'40%',
		height:40,
		hintText:'  Style...',
		paddingLeft:8,
		paddingRight:8,
		borderStyle:Ti.UI.INPUT_BORDERSTYLE_ROUNDED,
		keyboardType:Titanium.UI.KEYBOARD_DEFAULT,
	    returnKeyType:Titanium.UI.RETURNKEY_NEXT,
	    suppressReturn:false
	});

	// Creates "Look-Up" button
	var btn = Titanium.UI.createButton({
		color:'#000',
		title:"Look-Up",
		font:{fontSize:18},
		top: 70,
		width:'80%',
		height:35

	});

	// Creates "Browse" button
	var btn2 = Titanium.UI.createButton({
		color:'#000',
		title:"Browse",
		font:{fontSize:18},
		bottom:120,
		width:'80%',
		height:35
	});

	// Creates label for "browsing by year/style"
	var label1 = Titanium.UI.createLabel({
		color:'#000',            // Black color
		text:'Browse By Year/Style',
		font:{fontSize:18,fontFamily:'Helvetica Neue'},
		textAlign:'center',
		top: 130,
		width:'auto'
	});

	// Displays pop-up message after clicking buttons
	btn.addEventListener("click", function(e){
		alert(e.source + " RESULTS FOR SEARCH");
	});
	btn2.addEventListener("click", function(e){
		alert(e.source + " RESULTS FOR BROWSING");
	});

	self.add(wines);
	self.add(year);
	self.add(style);
	self.add(btn);
	self.add(btn2);
	self.add(label1);
	//self.open();
	global.outputHook(self);
	return self;
};

module.exports = CheckInsWindow;<|endoftext|>


<commit_before>import { connect } from 'react-redux'
import { selectWorkspace } from '../actions/actions'
import WorkspaceSelectionList from '../components/WorkspaceSelectionList'

const listData = [
  {title:'UFO Sightings', modified:1490216837867, queries:4},
  {title:'Cartel Hideouts', modified:1490216827866, queries:4},
  {title:'Military Bases', modified:1490216817865, queries:4},
  {title:'Pictures of Cats', modified:1490216807864, queries:40000},
]

const mapStateToProps = (state) => {
  return {
    listData
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    onWorkspaceSelection: (workspace) => {
      dispatch(selectWorkspace(workspace))
    }
  }
}

const WorkspaceSelectionContainer = connect(
  mapStateToProps,
  mapDispatchToProps
)(WorkspaceSelectionList)

export default WorkspaceSelectionContainer
<commit_msg>Made names more PG<commit_after>import { connect } from 'react-redux'
import { selectWorkspace } from '../actions/actions'
import WorkspaceSelectionList from '../components/WorkspaceSelectionList'

const listData = [
  {title:'UFO Sightings', modified:1490216837867, queries:4},
  {title:'Oil Fields', modified:1490216827866, queries:4},
  {title:'Military Bases', modified:1490216817865, queries:4},
  {title:'Pictures of Cats', modified:1490216807864, queries:40000},
]

const mapStateToProps = (state) => {
  return {
    listData
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    onWorkspaceSelection: (workspace) => {
      dispatch(selectWorkspace(workspace))
    }
  }
}

const WorkspaceSelectionContainer = connect(
  mapStateToProps,
  mapDispatchToProps
)(WorkspaceSelectionList)

export default WorkspaceSelectionContainer
<|endoftext|>


<commit_before>'use strict';
var $ = require('jquery');
var ko = require('knockout');
var bootbox = require('bootbox');
var $osf = require('js/osfHelpers');
var jedit = require('json-editor');

var MetaData = require('../metadata_1.js');
var ctx = window.contextVars;
/**
    * Unblock UI and display error modal
    */

(function() {
    var $editor = document.getElementById('editor');

    var schema_data = [];
    var init_schemas = [];
    var prereg = [];
    var open_ended = [];
    var titles = [];
    var editor;

     schema_data = [
        {
            item1: "an answer",
            item2: "an answer",
            item3: "an answer",
            item4: "an answer",
            item5: "an answer",
            item6: "an answer",
            item7: "an answer",
            item8: "an answer",
            item9: "an answer",
            summary: "a summary",
        },
        {
            item10: "yes",
            item11: "an answer",
            item12: "an answer",
            item13: "an answer",
            item14: "an answer",
            item15: "an answer",
            item16: "an answer",
        },
        {

            item17: "Exact",
            item18: "Exact",
            item19: "Exact",
            item20: "Exact",
            item21: "Exact",
            item22: "Exact",
            item23: "Exact",
            item24: "an answer",
            item25: "an answer",
        },
        {
            item26: "an answer",
            item27: "an answer",
            item28: "an answer",
        }
    ];

    open_ended = [
        {
            id: "Open-Ended_Registration",
            title: "Open Ended Registration",
            type: "object",
            properties: {
                summary: {
                    type: "string",
                    format: "textarea",
                    title: "Provide a narrative summary of what is contained in this registration, or how it differs from prior registrations."
                }
            }
        }

    ];

    prereg = [
        {
            id: "Replication_Recipe_(Brandt_et_al.,_2013):_Pre-Registration",
            title: "The Nature of the Effect",
            type: "object",
            properties: {
                item1: {
                   type: "string", title: "Verbal description of the effect I am trying to replicate"
                },
                item2: {
                    type: "string", title: "It is important to replicate this effect because"
                },
                item3: {
                    type: "string", title: "The effect size of the effect I am trying to replicate is"
                },
                item4: {
                    type: "string", title: "The confidence interval of the original effect is"
                },
                item5: {
                    type: "string", title: "The sample size of the original effect is"
                },
                item6: {
                    type: "string", title: "Where was the original study conducted? (e.g., lab, in the field, online)"
                },
                item7: {
                    type: "string", title: "What country/region was the original study conducted in?"
                },
                item8: {
                    type: "string", title: "What kind of sample did the original study use? (e.g., student, Mturk, representative)"
                },
                item9: {
                    type: "string", title: "Was the original study conducted with paper-and-pencil surveys, on a computer, or something else?"
                }
            }
        },
        {
            title: "Designing the Replication Study",
            type: "object",
            properties: {
                item10: {
                    type: "string", title: "Are the original materials for the study available from the author?", enum: ["yes", "no"], description: "Choose..."
                },
                item11: {
                    type: "string", title: "I know that assumptions (e.g., about the meaning of the stimuli) in the original study will also hold in my replication because"
                },
                item12: {
                    type: "string", title: "Location of the experimenter during data collection"
                },
                item13: {
                    type: "string", title: "Experimenter knowledge of participant experimental condition"
                },
                item14: {
                    type: "string", title: "Experimenter knowledge of overall hypotheses"
                },
                item15: {
                    type: "string", title: "My target sample size is"
                },
                item16: {
                    type: "string", title: "The rationale for my sample size is"
                }
            }
        },
        {
            title: "Documenting Differences between the Original and Replication Study",
            type: "object",
            properties: {
                item17: {
                    type: "string", title: "The similarities/differences in the instructions are", enum: ["Exact", "Close", "Different"], description: "Choose..."
                },
                item18: {
                    type: "string", title: "The similarities/differences in the measures are", enum: ["Exact", "Close", "Different"], description: "Choose..."
                },
                item19: {
                    type: "string", title: "The similarities/differences in the stimuli are", enum: ["Exact", "Close", "Different"], description: "Choose..."
                },
                item20: {
                    type: "string", title: "The similarities/differences in the procedure are", enum: ["Exact", "Close", "Different"], description: "Choose..."
                },
                item21: {
                    type: "string", title: "The similarities/differences in the location (e.g., lab vs. online; alone vs. in groups) are", enum: ["Exact", "Close", "Different"], description: "Choose..."
                },
                item22: {
                    type: "string", title: "The similarities/difference in remuneration are", enum: ["Exact", "Close", "Different"], description: "Choose..."
                },
                item23: {
                    type: "string", title: "The similarities/differences between participant populations are", enum: ["Exact", "Close", "Different"], description: "Choose..."
                },
                item24: {
                    type: "string", title: "What differences between the original study and your study might be expected to influence the size and/or direction of the effect?"
                },
                item25: {
                    type: "string", title: "I have taken the following steps to test whether the differences listed in the previous question will influence the outcome of my replication attempt"
                }
            }
        },
        {
            title: "Analysis and Replication Evaluation",
            type: "object",
            properties: {
                item26: {
                    type: "string", title: "My exclusion criteria are (e.g., handling outliers, removing participants from analysis)"
                },
                item27: {
                    type: "string", title: "My analysis plan is (justify differences from the original)"
                },
                item28: {
                    type: "string", title: "A successful replication is defined as"
                }
            }
        }
    ];

    // all schemas are in one array of arrays
    init_schemas.push(open_ended);
    init_schemas.push(prereg);

    var which_schema = 0;

    // this is how the import and export should work
    //var str = JSON.stringify(prereg);
    //console.log(str);
    //console.log(JSON.parse(str));

    var loadData = function(schemas, arrays, which) {
        // incorrect data input
        if (schemas[which].length > arrays.length) {
            alert("The amount of data is inconsistent. Unable to load.");
            return;
        } if (schemas[which].length <= 0) {
            alert("There is no data to load.");
            return;
        }

        // load nav bar -- need to account for situations when there is only one page (take away prev and next)
        var tabs = '
«
';
        var pages;
        for (pages in schemas[which]) {
            titles.push(schemas[which][pages].title);
            tabs = tabs + '
' + schemas[which][pages].title + '
';
        }

        tabs = tabs + '
»
';

        document.getElementById("myNavBar").innerHTML = tabs;

        // load the data for the first schema and display
        if(editor) editor.destroy();
        editor = new JSONEditor($editor,{
            schema: schemas[which][0],
            theme: 'bootstrap3',
            disable_collapse: true,
            disable_edit_json: true,
            disable_properties: true,
            no_additional_properties: true
        });
        editor.setValue(arrays[0]);
        window.editor = editor;
    };

    // where the array of schemas and array of data is held
    loadData(init_schemas, schema_data, 0);

    // called when switches pages
    var reload = function(schemas, data, num, which) {
        if(editor) editor.destroy();
        editor = new JSONEditor($editor,{
            schema: schemas[which][num],
            theme: 'bootstrap3',
            disable_collapse: true,
            disable_edit_json: true,
            disable_properties: true,
            no_additional_properties: true
        });
        editor.setValue(data[num]);
        window.editor = editor;
    };

    // need to update so that it doesn't register when the top nav bar is clicked
    $(document.body).on('click', 'a', function() {
        var index = 0;
        var clicked = this.id;
        if (clicked === 'prev') {
            index = titles.indexOf(editor.options.schema.title);
            if (index === 0) {
                reload(init_schemas, schema_data, 0, which_schema);
            } else {
                reload(init_schemas, schema_data, parseInt(index) - 1, which_schema);
            }
        } else if (clicked === 'next') {
            index = titles.indexOf(editor.options.schema.title);
            var max = init_schemas.length - 1;
            if (index === max) {
                reload(init_schemas, schema_data, max, which_schema);
            } else {
                reload(init_schemas, schema_data, parseInt(index) + 1, which_schema);
            }

        } else {
            var id = clicked.split("tab");
            reload(init_schemas, schema_data, id[1], which_schema);
        }

        // this doesn't really work...needs to add query string to url without page refresh
        //window.history.pushState('container', editor.options.schema.title, window.location.href + '?' + editor.options.schema.title);

    });

    // get schema that was selected by user
    $(document.body).on('change', "#select-registration-template", function() {
        var $tempName = '';
        var $this = $(this);
        var val = $this.val();
        if (val !== '') {
            document.getElementById("title").innerHTML = val;

            var schema;
            for (schema in init_schemas) {
                if (init_schemas[schema][0].id === val) {
                    which_schema = schema;
                    loadData(init_schemas, schema_data, which_schema);
                }
            }

            //reload(init_schemas, schema_data, 0);
        } else {
            document.getElementById("title").innerHTML = "Select an option above";
        }
    });

    document.getElementById('save').onclick = function () {
        console.log(editor.options.schema.title);
        var schema;
        for (schema in init_schemas) {
            if (init_schemas[schema].title === editor.options.schema.title) {
                schema_data[schema] = editor.getValue();
            }
        }
    };

})();

$(document).ready(function() {

    // $.ajax({
    //     url: ctx.node.urls.api + 'beforedraft/',
    //     contentType: 'application/json',
    //     success: function(response) {
    //         if (response.prompts && response.prompts.length) {
    //             bootbox.confirm(
    //                 $osf.joinPrompts(response.prompts, 'Are you sure you want to create a draft of this project?'),
    //                 function(result) {
    //                     if (result) {
    //                         draftNode(data);
    //                     }
    //                 }
    //             );
    //         } else {
    //             draftNode(data);
    //         }
    //     }
    // });

    // Don't submit form on enter; must use $.delegate rather than $.on
    // to catch dynamically created form elements
    // $('#registration_template').delegate('input, select', 'keypress', function(event) {
    //     return event.keyCode !== 13;
    // });

    // var registrationViewModel = new MetaData.ViewModel(
    //     ctx.regSchema,
    //     ctx.registered,
    //     [ctx.node.id].concat(ctx.node.children)
    // );
    // // Apply view model
    // ko.applyBindings(registrationViewModel, $('#registration_template')[0]);
    // registrationViewModel.updateIdx('add', true);

    // if (ctx.registered) {
    //     registrationViewModel.unserialize(ctx.regPayload);
    // }

    // $('#registration_template form').on('submit', function() {

    //     // Serialize responses
    //     var serialized = registrationViewModel.serialize(),
    //         data = serialized.data,
    //         complete = serialized.complete;

    //     // Clear continue text and stop if incomplete
    //     if (!complete) {
    //         registrationViewModel.continueText('');
    //         return false;
    //     }

    //     $.ajax({
    //         url: ctx.node.urls.api + 'beforeregister/',
    //         contentType: 'application/json',
    //         success: function(response) {
    //             if (response.prompts && response.prompts.length) {
    //                 bootbox.confirm(
    //                     $osf.joinPrompts(response.prompts, 'Are you sure you want to register this project?'),
    //                     function(result) {
    //                         if (result) {
    //                             registerNode(data);
    //                         }
    //                     }
    //                 );
    //             } else {
    //                 registerNode(data);
    //             }
    //         }
    //     });

    // $(document).ready(function() {

    // $.ajax({
    //     url: ctx.node.urls.api + 'beforerdraft/',
    //     contentType: 'application/json',
    //     success: function(response) {
    //         if (response.prompts && response.prompts.length) {
    //             bootbox.confirm(
    //                 $osf.joinPrompts(response.prompts, 'Are you sure you want to create a draft of this project?'),
    //                 function(result) {
    //                     if (result) {
    //                         draftNode(data);
    //                     }
    //                 }
    //             );
    //         } else {
    //             draftNode(data);
    //         }
    //     }
    // });

    //     return false;

    // });
});
<commit_msg>added other schemas and updated save function to work with single data storage<commit_after>'use strict';
var $ = require('jquery');
var ko = require('knockout');
var bootbox = require('bootbox');
var $osf = require('js/osfHelpers');
var jedit = require('json-editor');

var MetaData = require('../metadata_1.js');
var ctx = window.contextVars;
/**
    * Unblock UI and display error modal
    */

(function() {
    var $editor = document.getElementById('editor');

    var schema_data = [];
    var init_schemas = [];
    var prereg = [];
    var open_ended = [];
    var postcomp = [];
    var osf_stand = [];
    var titles = [];
    var editor;

     schema_data = [
        {
            item1: "an answer",
            item2: "an answer",
            item3: "an answer",
            item4: "an answer",
            item5: "an answer",
            item6: "an answer",
            item7: "an answer",
            item8: "an answer",
            item9: "an answer",
            summary: "a summary",
            item29: "an answer",
            datacompletion: "yes",
            looked: "yes",
            comments: "an answer",
        },
        {
            item10: "yes",
            item11: "an answer",
            item12: "an answer",
            item13: "an answer",
            item14: "an answer",
            item15: "an answer",
            item16: "an answer",
            item30: "an answer",
            item31: "an answer",
            item32: "significantly different from the original effect size",
            item33: "success",
            item34: "an answer",
            item35: "an answer",
            item36: "an answer",
            item37: "an answer",

        },
        {

            item17: "Exact",
            item18: "Exact",
            item19: "Exact",
            item20: "Exact",
            item21: "Exact",
            item22: "Exact",
            item23: "Exact",
            item24: "an answer",
            item25: "an answer",
        },
        {
            item26: "an answer",
            item27: "an answer",
            item28: "an answer",
        }
    ];

    open_ended = [
        {
            id: "Open-Ended_Registration",
            title: "Open Ended Registration",
            type: "object",
            properties: {
                summary: {
                    type: "string",
                    format: "textarea",
                    title: "Provide a narrative summary of what is contained in this registration, or how it differs from prior registrations."
                }
            }
        }

    ];

    osf_stand = [
        {
            id: "OSF-Standard_Pre-Data_Collection_Registration",
            title: "OSF-Standard Pre-Data Collection Registration",
            type: "object",
            properties: {
                datacompletion: {
                    type: "array",
                    title: "Is data collection for this project underway or complete?",
                    uniqueItems: "true",
                    items: {
                        type: "string",
                        enum: ["yes", "no"],
                    },
                    description: "Choose..."
                },
                looked: {
                    type: "array",
                    title: "Have you looked at the data?",
                    uniqueItems: "true",
                    items: {
                        type: "string",
                        enum: ["yes", "no"],
                    },
                    description: "Choose..."
                },
                comments: {
                    type: "string",
                    format: "textarea",
                    title: "Other Comments"
                }
            }
        }
    ];

    postcomp = [
        {
            id: "Replication_Recipe_(Brandt_et_al.,_2013):_Post-Completion",
            title: "Registering the Replication Attempt",
            type: "object",
            properties: {
                item29: {
                    type: "string", format: "text", title: "The finalized materials, procedures, analysis plan etc of the replication are registered here"
                }
            }
        },
        {
            title: "Reporting the Replication",
            type: "object",
            properties: {
                item30: {
                    type: "string", format: "text", title: "The effect size of the replication is"
                },
                item31: {
                    type: "string", format: "text", title: "The confidence interval of the replication effect size is"
                },
                item32: {
                    type: "array", title: "The replication effect size is",
                    uniqueItems: "true",
                    items: {
                        type: "string",
                        enum: ["significantly different from the original effect size", "not significantly different from the original effect size"],
                    },
                    description: "Choose..."
                },
                item33: {
                    type: "array", title: "I judge the replication to be a(n)",
                    uniqueItems: "true",
                    items: {
                        type: "string",
                        enum: ["success", "informative failure to replicate", "practical failure to replicate", "inconclusive"],
                    },
                    description: "Choose..."
                },
                item34: {
                    type: "string", format: "textarea", title: "I judge it so because"
                },
                item35: {
                    type: "string", format: "text", title: "Interested experts can obtain my data and syntax here"
                },
                item36: {
                    type: "string", format: "text", title: "All of the analyses were reported in the report or are available here"
                },
                item37: {
                    type: "string", format: "textarea", title: "The limitations of my replication study are"
                }
            }
        }

    ]

    prereg = [
        {
            id: "Replication_Recipe_(Brandt_et_al.,_2013):_Pre-Registration",
            title: "The Nature of the Effect",
            type: "object",
            properties: {
                item1: {
                   type: "string", format: "textarea", title: "Verbal description of the effect I am trying to replicate"
                },
                item2: {
                    type: "string", format: "textarea", title: "It is important to replicate this effect because"
                },
                item3: {
                    type: "string", format: "text", title: "The effect size of the effect I am trying to replicate is"
                },
                item4: {
                    type: "string", format: "text", title: "The confidence interval of the original effect is"
                },
                item5: {
                    type: "string", format: "text", title: "The sample size of the original effect is"
                },
                item6: {
                    type: "string", format: "text", title: "Where was the original study conducted? (e.g., lab, in the field, online)"
                },
                item7: {
                    type: "string", format: "text", title: "What country/region was the original study conducted in?"
                },
                item8: {
                    type: "string", format: "text", title: "What kind of sample did the original study use? (e.g., student, Mturk, representative)"
                },
                item9: {
                    type: "string", format: "text", title: "Was the original study conducted with paper-and-pencil surveys, on a computer, or something else?"
                }
            }
        },
        {
            title: "Designing the Replication Study",
            type: "object",
            properties: {
                item10: {
                    type: "array", title: "Are the original materials for the study available from the author?",
                    uniqueItems: "true",
                    items: {
                        type: "string",
                        enum: ["yes", "no"],
                    },
                    description: "Choose..."
                },
                item11: {
                    type: "string", format: "textarea", title: "I know that assumptions (e.g., about the meaning of the stimuli) in the original study will also hold in my replication because"
                },
                item12: {
                    type: "string", format: "text", title: "Location of the experimenter during data collection"
                },
                item13: {
                    type: "string", format: "text", title: "Experimenter knowledge of participant experimental condition"
                },
                item14: {
                    type: "string", format: "text", title: "Experimenter knowledge of overall hypotheses"
                },
                item15: {
                    type: "string", format: "text", title: "My target sample size is"
                },
                item16: {
                    type: "string", format: "textarea", title: "The rationale for my sample size is"
                }
            }
        },
        {
            title: "Documenting Differences between the Original and Replication Study",
            type: "object",
            properties: {
                item17: {
                    type: "array", title: "The similarities/differences in the instructions are",
                    uniqueItems: "true",
                    items: {
                        type: "string",
                        enum: ["Exact", "Close", "Different"],
                    },
                    description: "Choose..."
                },
                item18: {
                    type: "array", title: "The similarities/differences in the measures are",
                    uniqueItems: "true",
                    items: {
                        type: "string",
                        enum: ["Exact", "Close", "Different"],
                    },
                    description: "Choose..."
                },
                item19: {
                    type: "array", title: "The similarities/differences in the stimuli are",
                    uniqueItems: "true",
                    items: {
                        type: "string",
                        enum: ["Exact", "Close", "Different"],
                    },
                    description: "Choose..."
                },
                item20: {
                    type: "array", title: "The similarities/differences in the procedure are",
                    uniqueItems: "true",
                    items: {
                        type: "string",
                        enum: ["Exact", "Close", "Different"],
                    },
                    description: "Choose..."
                },
                item21: {
                    type: "array", title: "The similarities/differences in the location (e.g., lab vs. online; alone vs. in groups) are",
                    uniqueItems: "true",
                    items: {
                        type: "string",
                        enum: ["Exact", "Close", "Different"],
                    },
                    description: "Choose..."
                },
                item22: {
                    type: "array", title: "The similarities/difference in remuneration are",
                    uniqueItems: "true",
                    items: {
                        type: "string",
                        enum: ["Exact", "Close", "Different"],
                    },
                    description: "Choose..."
                },
                item23: {
                    type: "array", title: "The similarities/differences between participant populations are",
                    uniqueItems: "true",
                    items: {
                        type: "string",
                        enum: ["Exact", "Close", "Different"],
                    },
                    description: "Choose..."
                },
                item24: {
                    type: "string", format: "textarea", title: "What differences between the original study and your study might be expected to influence the size and/or direction of the effect?"
                },
                item25: {
                    type: "string", format: "textarea", title: "I have taken the following steps to test whether the differences listed in the previous question will influence the outcome of my replication attempt"
                }
            }
        },
        {
            title: "Analysis and Replication Evaluation",
            type: "object",
            properties: {
                item26: {
                    type: "string", format: "textarea", title: "My exclusion criteria are (e.g., handling outliers, removing participants from analysis)"
                },
                item27: {
                    type: "string", format: "textarea", title: "My analysis plan is (justify differences from the original)"
                },
                item28: {
                    type: "string", format: "textarea", title: "A successful replication is defined as"
                }
            }
        }
    ];

    // all schemas are in one array of arrays
    init_schemas.push(open_ended);
    init_schemas.push(prereg);
    init_schemas.push(postcomp);
    init_schemas.push(osf_stand);

    var which_schema = 0;

    // this is how the import and export should work
    //var str = JSON.stringify(prereg);
    //console.log(str);
    //console.log(JSON.parse(str));

    var loadData = function(schemas, arrays, which) {
        // incorrect data input
        if (schemas[which].length > arrays.length) {
            alert("The amount of data is inconsistent. Unable to load.");
            return;
        } if (schemas[which].length <= 0) {
            alert("There is no data to load.");
            return;
        }

        // load nav bar -- need to account for situations when there is only one page (take away prev and next)
        var tabs = '
«
';
        var pages;
        for (pages in schemas[which]) {
            titles.push(schemas[which][pages].title);
            tabs = tabs + '
' + schemas[which][pages].title + '
';
        }

        tabs = tabs + '
»
';

        document.getElementById("myNavBar").innerHTML = tabs;

        // load the data for the first schema and display
        if(editor) editor.destroy();
        editor = new JSONEditor($editor,{
            schema: schemas[which][0],
            theme: 'bootstrap3',
            disable_collapse: true,
            disable_edit_json: true,
            disable_properties: true,
            no_additional_properties: true
        });
        editor.setValue(arrays[0]);
        window.editor = editor;
    };

    // called when switches pages
    var reload = function(schemas, data, num, which) {
        if(editor) editor.destroy();
        editor = new JSONEditor($editor,{
            schema: schemas[which][num],
            theme: 'bootstrap3',
            disable_collapse: true,
            disable_edit_json: true,
            disable_properties: true,
            no_additional_properties: true
        });
        editor.setValue(data[num]);
        window.editor = editor;
    };

    // need to update so that it doesn't register when the top nav bar is clicked
    $(document.body).on('click', 'a', function() {
        var index = 0;
        var clicked = this.id;
        if (clicked === 'prev') {
            index = titles.indexOf(editor.options.schema.title);
            if (index === 0) {
                reload(init_schemas, schema_data, 0, which_schema);
            } else {
                reload(init_schemas, schema_data, parseInt(index) - 1, which_schema);
            }
        } else if (clicked === 'next') {
            index = titles.indexOf(editor.options.schema.title);
            var max = init_schemas.length - 1;
            if (index === max) {
                reload(init_schemas, schema_data, max, which_schema);
            } else {
                reload(init_schemas, schema_data, parseInt(index) + 1, which_schema);
            }

        } else {
            var id = clicked.split("tab");
            reload(init_schemas, schema_data, id[1], which_schema);
        }

        // this doesn't really work...needs to add query string to url without page refresh
        //window.history.pushState('container', editor.options.schema.title, window.location.href + '?' + editor.options.schema.title);

    });

    // get schema that was selected by user
    $(document.body).on('change', "#select-registration-template", function() {
        var $this = $(this);
        var val = $this.val();
        var tempName = val.replace(/_/g , " ");

        if (val !== '') {
            document.getElementById("title").innerHTML = tempName;

            var schema;
            for (schema in init_schemas) {
                if (init_schemas[schema][0].id === val) {
                    which_schema = schema;
                    loadData(init_schemas, schema_data, which_schema);
                }
            }

            //reload(init_schemas, schema_data, 0);
        } else {
            document.getElementById("title").innerHTML = "Select an option above";
        }
    });

    document.getElementById('save').onclick = function () {
        var schema;
        var value;
        for (schema in init_schemas[which_schema]) {
            if (init_schemas[which_schema][schema].title === editor.options.schema.title) {
                for (value in editor.getValue()) {
                   schema_data[schema][value] = editor.getValue()[value];
                }
            }
        }
    };

})();

$(document).ready(function() {

    // $.ajax({
    //     url: ctx.node.urls.api + 'beforedraft/',
    //     contentType: 'application/json',
    //     success: function(response) {
    //         if (response.prompts && response.prompts.length) {
    //             bootbox.confirm(
    //                 $osf.joinPrompts(response.prompts, 'Are you sure you want to create a draft of this project?'),
    //                 function(result) {
    //                     if (result) {
    //                         draftNode(data);
    //                     }
    //                 }
    //             );
    //         } else {
    //             draftNode(data);
    //         }
    //     }
    // });

    // Don't submit form on enter; must use $.delegate rather than $.on
    // to catch dynamically created form elements
    // $('#registration_template').delegate('input, select', 'keypress', function(event) {
    //     return event.keyCode !== 13;
    // });

    // var registrationViewModel = new MetaData.ViewModel(
    //     ctx.regSchema,
    //     ctx.registered,
    //     [ctx.node.id].concat(ctx.node.children)
    // );
    // // Apply view model
    // ko.applyBindings(registrationViewModel, $('#registration_template')[0]);
    // registrationViewModel.updateIdx('add', true);

    // if (ctx.registered) {
    //     registrationViewModel.unserialize(ctx.regPayload);
    // }

    // $('#registration_template form').on('submit', function() {

    //     // Serialize responses
    //     var serialized = registrationViewModel.serialize(),
    //         data = serialized.data,
    //         complete = serialized.complete;

    //     // Clear continue text and stop if incomplete
    //     if (!complete) {
    //         registrationViewModel.continueText('');
    //         return false;
    //     }

    //     $.ajax({
    //         url: ctx.node.urls.api + 'beforeregister/',
    //         contentType: 'application/json',
    //         success: function(response) {
    //             if (response.prompts && response.prompts.length) {
    //                 bootbox.confirm(
    //                     $osf.joinPrompts(response.prompts, 'Are you sure you want to register this project?'),
    //                     function(result) {
    //                         if (result) {
    //                             registerNode(data);
    //                         }
    //                     }
    //                 );
    //             } else {
    //                 registerNode(data);
    //             }
    //         }
    //     });

    // $(document).ready(function() {

    // $.ajax({
    //     url: ctx.node.urls.api + 'beforerdraft/',
    //     contentType: 'application/json',
    //     success: function(response) {
    //         if (response.prompts && response.prompts.length) {
    //             bootbox.confirm(
    //                 $osf.joinPrompts(response.prompts, 'Are you sure you want to create a draft of this project?'),
    //                 function(result) {
    //                     if (result) {
    //                         draftNode(data);
    //                     }
    //                 }
    //             );
    //         } else {
    //             draftNode(data);
    //         }
    //     }
    // });

    //     return false;

    // });
});
<|endoftext|>


<commit_before>/**
 *   Iridescence Smart Connector Web UI RESTful Client
 *   Copyright (C) 2015 eCaresoft Inc
 *   Ernesto Angel Celis de la Fuente <developer@celisdelafuente.net>
 *
 *   This file is part of Iridescence Smart Connector
 *
 *   Iridescence Smart Connector is free software: you can redistribute it
 *   under the terms of the GNU Affero General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or (at
 *   your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU Affero General Public License for more details.
 *
 *   You should have received a copy of the GNU Affero General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

var srcdata, tplsrc;

var leaf = function()
{
  this.text = '';
  this.nodes = [];
};

/**
 * Save adapters to YAML in the server
 * @method save
 * */
var save_workspace = function()
{
  var payload = {'meta': null, 'data': []};
  payload.meta = JSON.stringify(work_meta);
  adapters.forEach(function(adapter) {
    payload.data.push(JSON.stringify(adapter.data("props")));
  });
  $.post("/api/",
     {"__anti-forgery-token": $('#__anti-forgery-token').val(),
       "workspace":payload
     },
    function(res) {
      $("#info-box").fadeIn("slow");
      $("#info-box").html("Workspace " + $("#work-name").val() + " saved");
      $("#info-box").fadeOut("slow");
    });
};

/**
 * Wrap element in draggable span
 *
 * @method drag_wrapper
 * @param String string
 */
var drag_wrapper = function(element)
{
  return '' +
    element + '';
};

/**
 * Wrap element in droppable span
 * @method drop_wrapper
 * @param String element
 */
var drop_wrapper = function(element)
{
  return '' +
    element + '';
}

/**
 * Handles JSON response for HL7v2 adapter, bootstrap-treeview ready
 *
 * @method hl7v2_handler
 * @param {Object} json_data response
 */
var hl7v2_handler = function(json_data)
{
  var tree = [];
  json_data['template'].forEach(function(item)
  {
    var a_leaf = Object.create(leaf.prototype);
    a_leaf.text = item.id;
    a_leaf.nodes = [];
    item.fields.forEach(function(field)
    {
      var b_leaf = Object.create(leaf.prototype);
      var isArray = field.content instanceof Array;
      if(isArray) {
        if(field.content.length > 1) {
          b_leaf.text = field.content.join('^');
          b_leaf.nodes = typeof b_leaf.nodes === 'undefined' ? [] : b_leaf.nodes;
          field.content.forEach(function(comp)
                       {
                        b_leaf.nodes.push({text: comp});
                       });
        } else {
          b_leaf.text = typeof field.content[0] !== 'undefined' ?
            drop_wrapper(field.content[0]) : drop_wrapper('');
        }
      } else {
        b_leaf.text = drop_wrapper(field.content);
      }
      a_leaf.nodes.push(b_leaf);
    });
    tree.push(a_leaf);
  });
  return [{text: 'template', nodes: tree}];
};

/**
 * Handles JSON response for CSV adapter
 * TODO handle first row column names
 *
 * @method csv_handler
 * @param {Object} json_data response
 */
var csv_handler = function(json_data)
{
  var matrix = [];
  var row_number = 0;
  json_data.matrix.forEach(function(row) {
    var cells = [];
    row.forEach(function(cell) {
      cells.push({text: cell});
    });
    matrix.push({text: row_number.toString(), nodes: cells});
    row_number++;
  });
  return [{text: "src", nodes: matrix}];
};

/**
 * Handles JSON response for RDMS
 *
 * @method db_handler
 * @param {Object} json_data response
 */
var db_handler = function(json_data) {
  var table_schema = [];
  var table_definition = [];
  // Get table names
  if(json_data.tables != null) {
    json_data.tables.forEach(function(item){
      table_schema.push({
        "text": Object.getOwnPropertyNames(item)[0],
        "nodes":item.valueOf()
      });
    });
    // Get columns and return associative array of tables:columns
    table_schema.map(function(table){
      var cols = [];
      table.nodes[table.text].map(function(column){
        cols.push({
          text: drag_wrapper(column.column_name)});
      });
      table_definition.push({"text": table.text, "nodes": cols});
    });
    return [{text: "tables", nodes: table_definition}];
  }
};

/**
 * Stores in a variable the Table Definition retrieved by test_connection
 *
 * @method adapter_connection_handler
 * @param {String} url Adapters URL
 * @param {Object} json_data response
 */
var adapter_connection_handler = function(url, json_data)
{
  var proto = new URI(url).scheme();
  switch(proto) {
    case "postgres":
    case "postgresql":
    case "mysql":
      srcdata = db_handler(json_data);
      break;
    case "csv":
      srcdata = csv_handler(json_data);
      break;
    default:
      console.log("Empty response");
  }
};

/**
 * POST file
 */
var file_upload_handler = function ()
{
  // Change this to the location of your server-side upload handler:
  var url = context + '/upload';
  $.post(context + "/api/upload",
     {"__anti-forgery-token": $("#__anti-forgery-token").val(),
       "file": $('#file').val()
     },
     function(res)
     {
       console.log(res);
     }
  );
};

/**
 * GET HL7 Template
 */
var get_template = function(id)
{
  id = typeof id !== 'undefined' ? id : '';
  $.get('/api/template/' + id,
    {'__anti-forgery-token': $('#__anti-forgery-token').val()},
    function(res)
    {
      if(id !== '') {
        tplsrc = hl7v2_handler(res);
        tplsrc_treeview();
      } else {
        fill_templates(res['template']);
      }
    });
};

/**
 * GET Data Source Schema
 *
 * @method test_connection
 * @param {String} url
 */
var test_connection = function (url)
{
  $.get("/api/adapter/test/",
    {"__anti-forgery-token": $("#__anti-forgery-token").val(),
      "url": url
    },
    function(res) {
      adapter_connection_handler(url, res);
    });
};

/**
 * GET Data From Source
 */
var build_select = function()
{
  $.get("/api/adapter/build_select/",
    {"__anti-forgery-token": $("#__anti-forgery-token").val(),
      "url": $('#adapter-url').val(),
      "tables": $('#adapter-from').val(),
      "query": $('#adapter-query').val()
    },
   function(res) {
    console.log(res);
   });
};
<commit_msg>Droppable template tree WIP<commit_after>/**
 *   Iridescence Smart Connector Web UI RESTful Client
 *   Copyright (C) 2015 eCaresoft Inc
 *   Ernesto Angel Celis de la Fuente <developer@celisdelafuente.net>
 *
 *   This file is part of Iridescence Smart Connector
 *
 *   Iridescence Smart Connector is free software: you can redistribute it
 *   under the terms of the GNU Affero General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or (at
 *   your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU Affero General Public License for more details.
 *
 *   You should have received a copy of the GNU Affero General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

var srcdata, tplsrc;

var leaf = function()
{
  this.text = '';
  this.nodes = [];
};

/**
 * Save adapters to YAML in the server
 * @method save
 * */
var save_workspace = function()
{
  var payload = {'meta': null, 'data': []};
  payload.meta = JSON.stringify(work_meta);
  adapters.forEach(function(adapter) {
    payload.data.push(JSON.stringify(adapter.data("props")));
  });
  $.post("/api/",
     {"__anti-forgery-token": $('#__anti-forgery-token').val(),
       "workspace":payload
     },
    function(res) {
      $("#info-box").fadeIn("slow");
      $("#info-box").html("Workspace " + $("#work-name").val() + " saved");
      $("#info-box").fadeOut("slow");
    });
};

/**
 * Wrap element in draggable span
 *
 * @method drag_wrapper
 * @param String string
 */
var drag_wrapper = function(element)
{
  return '' +
    element + '';
};

/**
 * Wrap element in droppable span
 * @method drop_wrapper
 * @param String element
 */
var drop_wrapper = function(element)
{
  return '' +
    element + '';
}

/**
 * Handles JSON response for HL7v2 adapter, bootstrap-treeview ready
 *
 * @method hl7v2_handler
 * @param {Object} json_data response
 */
var hl7v2_handler = function(json_data)
{
  var tree = [];
  json_data['template'].forEach(function(item)
  {
    var a_leaf = Object.create(leaf.prototype);
    a_leaf.text = item.id;
    a_leaf.nodes = [];
    item.fields.forEach(function(field)
    {
      var b_leaf = Object.create(leaf.prototype);
      var isArray = field.content instanceof Array;
      if(isArray) {
        if(field.content.length > 1) {
          b_leaf.text = field.content.join('^');
          b_leaf.nodes = typeof b_leaf.nodes === 'undefined' ? [] : b_leaf.nodes;
          field.content.forEach(function(comp)
                       {
                        b_leaf.nodes.push({text: drop_wrapper(comp)});
                       });
        } else {
          b_leaf.text = typeof field.content[0] !== 'undefined' ?
            drop_wrapper(field.content[0]) : drop_wrapper('');
        }
      } else {
        b_leaf.text = drop_wrapper(field.content);
      }
      a_leaf.nodes.push(b_leaf);
    });
    tree.push(a_leaf);
  });
  return [{text: 'template', nodes: tree}];
};

/**
 * Handles JSON response for CSV adapter
 * TODO handle first row column names
 *
 * @method csv_handler
 * @param {Object} json_data response
 */
var csv_handler = function(json_data)
{
  var matrix = [];
  var row_number = 0;
  json_data.matrix.forEach(function(row) {
    var cells = [];
    row.forEach(function(cell) {
      cells.push({text: cell});
    });
    matrix.push({text: row_number.toString(), nodes: cells});
    row_number++;
  });
  return [{text: "src", nodes: matrix}];
};

/**
 * Handles JSON response for RDMS
 *
 * @method db_handler
 * @param {Object} json_data response
 */
var db_handler = function(json_data) {
  var table_schema = [];
  var table_definition = [];
  // Get table names
  if(json_data.tables != null) {
    json_data.tables.forEach(function(item){
      table_schema.push({
        "text": Object.getOwnPropertyNames(item)[0],
        "nodes":item.valueOf()
      });
    });
    // Get columns and return associative array of tables:columns
    table_schema.map(function(table){
      var cols = [];
      table.nodes[table.text].map(function(column){
        cols.push({
          text: drag_wrapper(column.column_name)});
      });
      table_definition.push({"text": table.text, "nodes": cols});
    });
    return [{text: "tables", nodes: table_definition}];
  }
};

/**
 * Stores in a variable the Table Definition retrieved by test_connection
 *
 * @method adapter_connection_handler
 * @param {String} url Adapters URL
 * @param {Object} json_data response
 */
var adapter_connection_handler = function(url, json_data)
{
  var proto = new URI(url).scheme();
  switch(proto) {
    case "postgres":
    case "postgresql":
    case "mysql":
      srcdata = db_handler(json_data);
      break;
    case "csv":
      srcdata = csv_handler(json_data);
      break;
    default:
      console.log("Empty response");
  }
};

/**
 * POST file
 */
var file_upload_handler = function ()
{
  // Change this to the location of your server-side upload handler:
  var url = context + '/upload';
  $.post(context + "/api/upload",
     {"__anti-forgery-token": $("#__anti-forgery-token").val(),
       "file": $('#file').val()
     },
     function(res)
     {
       console.log(res);
     }
  );
};

/**
 * GET HL7 Template
 */
var get_template = function(id)
{
  id = typeof id !== 'undefined' ? id : '';
  $.get('/api/template/' + id,
    {'__anti-forgery-token': $('#__anti-forgery-token').val()},
    function(res)
    {
      if(id !== '') {
        tplsrc = hl7v2_handler(res);
        tplsrc_treeview();
      } else {
        fill_templates(res['template']);
      }
    });
};

/**
 * GET Data Source Schema
 *
 * @method test_connection
 * @param {String} url
 */
var test_connection = function (url)
{
  $.get("/api/adapter/test/",
    {"__anti-forgery-token": $("#__anti-forgery-token").val(),
      "url": url
    },
    function(res) {
      adapter_connection_handler(url, res);
    });
};

/**
 * GET Data From Source
 */
var build_select = function()
{
  $.get("/api/adapter/build_select/",
    {"__anti-forgery-token": $("#__anti-forgery-token").val(),
      "url": $('#adapter-url').val(),
      "tables": $('#adapter-from').val(),
      "query": $('#adapter-query').val()
    },
   function(res) {
    console.log(res);
   });
};
<|endoftext|>


<commit_before>var configoptions = {
    "serverURL": "",
    "selectedCalculation": "0",
    "invertAxis": "false",
    "selectedSort": "Frequency",
    "targetSpeciesName" : "Overview",
    "refSpecies": "Homo sapiens",
    "targetSpeciesList" : [{ "name": "Homo sapiens", "taxon": "9606"},
			   { "name": "Mus musculus", "taxon": "10090" },
			   { "name": "Danio rerio", "taxon": "7955"}
			]
};<commit_msg>Changed Axis Flip Default<commit_after>var configoptions = {
    "serverURL": "",
    "selectedCalculation": "0",
    "invertAxis": false,
    "selectedSort": "Frequency",
    "targetSpeciesName" : "Overview",
    "refSpecies": "Homo sapiens",
    "targetSpeciesList" : [{ "name": "Homo sapiens", "taxon": "9606"},
			   { "name": "Mus musculus", "taxon": "10090" },
			   { "name": "Danio rerio", "taxon": "7955"}
			]
};<|endoftext|>


<commit_before>app.section('pageView');

viewModel.pageView ={}; var pv = viewModel.pageView;

pv.indexWidget = ko.observable("");
pv.templateWidgetItem =  [
    '
',
        '
',
         	'',
        '
',
    '
'
].join("");

pv.prepareGridStack = function () {
    $("#page-designer-grid-stack").gridstack({
    	disableDrag: true,
        disableResize: true,
    });
};

pv.mapWidgets = function(){
	var $gridStack = $("#page-designer-grid-stack").data("gridstack");
	$div = $('#frame');
	app.ajaxPost("/pagedesigner/pageview", {title: viewModel.pageID}, function(res){
		if(!app.isFine(res)){
			return;
		}
		var widgets = res.data.widgets;

		(widgets == null ? [] : widgets).forEach(function (d) {
	        var $item = $(pv.templateWidgetItem);
	        $item.attr("data-id", d._id);
	        $item.data("id", d._id);
	        $item.data("widget-id", d.widgetId);
	        $gridStack.addWidget($item, d.x, d.y, d.width, d.height);

            var param = {
                _id: d._id,
                pageID: viewModel.pageID,
                widgetID: d.widgetId
            };

	        app.ajaxPost("/page/loadwidgetpagecontent", param, function (res) {
	        	if (!app.isFine(res)) {
					return;
				}

				var widgetBaseURL = baseURL + "res-widget/" +d.widgetId+"/" ;
		        var page = res.data.Content;
		        page = page.replace(/src\=\"/g, 'src="' + widgetBaseURL);
		        page = page.replace(/href\=\"/g, 'href="' + widgetBaseURL);

                var $iFrame = $("[data-id='" + d._id + "'] iframe");
                var iWindow = $iFrame[0].contentWindow;

		        $iFrame.off("load").on("load", function () {
                    console.log("widget " + d._id + " loaded");

                    iWindow.window.Render(
                        { dsChart: [] },
                        res.data.WidgetPageData.config,
                        res.data.WidgetData.config
                    );

                    app.ajaxPost("/page/loadwidgetpagedata", res.data.WidgetPageData.dataSources, function (res2) {
                        // if (!app.isFine(res)) {
                        //     return;
                        // }

                        if (res2.data == null) {
                            res2.data = {};
                        }

                        iWindow.window.Render(
                            res2.data,
                            res.data.WidgetPageData.config,
                            res.data.WidgetData.config
                        );
                    });
		        });

				var container =  iWindow.document;
		        container.open();
       	 		container.write(page);
        		container.close();

	        });

	        // $.each(d, function(i, w){
	        // 	console.log(i.dataSources)
	        // 	for(var key in w.dataSource){
	        // 		if(w.dataSources.hasOwnProperty(key)){
	        // 			console.log(w.dataSources(key));
	        // 		}
	        // 	}
	        // });
	    });
	});
}

$(function(){
	pv.prepareGridStack();
	pv.mapWidgets();
});
<commit_msg>no message<commit_after>app.section('pageView');

viewModel.pageView ={}; var pv = viewModel.pageView;

pv.indexWidget = ko.observable("");
pv.templateWidgetItem =  [
    '
',
        '
',
         	'',
        '
',
    '
'
].join("");

pv.prepareGridStack = function () {
    $("#page-designer-grid-stack").gridstack({
    	disableDrag: true,
        disableResize: true,
    });
};

pv.mapWidgets = function(){
	var $gridStack = $("#page-designer-grid-stack").data("gridstack");
	$div = $('#frame');
	app.ajaxPost("/pagedesigner/pageview", {title: viewModel.pageID}, function(res){
		if(!app.isFine(res)){
			return;
		}
		var widgets = res.data.widgets;

		(widgets == null ? [] : widgets).forEach(function (d) {
	        var $item = $(pv.templateWidgetItem);
	        $item.attr("data-id", d._id);
	        $item.data("id", d._id);
	        $item.data("widget-id", d.widgetId);
	        $gridStack.addWidget($item, d.x, d.y, d.width, d.height);

            var param = {
                _id: d._id,
                pageID: viewModel.pageID,
                widgetID: d.widgetId
            };

	        app.ajaxPost("/page/loadwidgetpagecontent", param, function (res) {
	        	if (!app.isFine(res)) {
					return;
				}

				var widgetBaseURL = baseURL + "res-widget/" +d.widgetId+"/" ;
		        var page = res.data.Content;
		        page = page.replace(/src\=\"/g, 'src="' + widgetBaseURL);
		        page = page.replace(/href\=\"/g, 'href="' + widgetBaseURL);

                var $iFrame = $("[data-id='" + d._id + "'] iframe");
                var iWindow = $iFrame[0].contentWindow;

		        $iFrame.off("load").on("load", function () {
                    console.log("widget " + d._id + " loaded");

                    iWindow.window.Render(
                        { dsChart: [] },
                        res.data.WidgetPageData.config,
                        res.data.WidgetData.config
                    );

                    app.ajaxPost("/page/loadwidgetpagedata", res.data.WidgetPageData.dataSources, function (res2) {
                        // if (!app.isFine(res)) {
                        //     return;
                        // }

                        if (res2.data == null) {
                            res2.data = {};
                        }

                        iWindow.window.Render(
                            res2.data,
                            res.data.WidgetPageData.config,
                            res.data.WidgetData.config
                        );
                    });
		        });

				var container =  iWindow.document;
		        container.open();
       	 		container.write(page);
        		container.close();

	        });

	        // $.each(d, function(i, w){
	        // 	console.log(i.dataSources)
	        // 	for(var key in w.dataSource){
	        // 		if(w.dataSources.hasOwnProperty(key)){
	        // 			console.log(w.dataSources(key));
	        // 		}
	        // 	}
	        // });
	    });
	});
}

$(function(){
	pv.prepareGridStack();
	pv.mapWidgets();
});
<|endoftext|>