<commit_before>//implement weback or something in this so we can build a dist file based on multiple src files.

window.modus = function () {
    //TODO: build some way to pass in like a web bridge handler?!

    //Helpers
    function _getParameterByName(name, url) {
        if (!url) url = window.location.href;
        name = name.replace(/[\[\]]/g, '\\$&');
        var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
            results = regex.exec(url);
        if (!results) return null;
        if (!results[2]) return '';
        return decodeURIComponent(results[2].replace(/\+/g, ' '));
    }

    //TODO: Break this in to a different file
    let _createExampleResult = function (request) {
        console.log("generating example output");

        var name = request.methodName;
        var result = null;

        switch (name) {
            case "getCurrentUserName":
                result = "Obi Won Kenobi"
                break;
            case "getCurrentUserEmail":
                result = "maul_killer@jedicouncil.crst"
                break;
            case "getAccessToken":
                result = "exampleToken"
                break;
            case "getCurrentUserRegions":
                result = ["Tatooine", "Stewjon", "Coruscant"]
                break;

            //Storage
            case "getItem":
            case "getGlobalItem":
                result = window[request.data.key] ? window[request.data.key] : null;
                break;
            case "setItem":
            case "setGlobalItem":
                window[request.data.key] = request.data.value;
                break;

            //Email
            case "sendAgenda":
            case "sendEmail":
            case "sendEmailHtml":
                var e = request.data;
                var body = e.body ? e.body : e.html ? e.html : "";
                var to = e.to ? e.to : e.emailAddress;
                var mailto = "mailto:" + to + "?subject=" + e.subject + "&body=" + body + "&cc=" + e.cc;
                window.open(mailto);
                break;

            //Agendas
            case "getAgendas":
                result = JSON.stringify([{ agendaId: "1", agendaTitle: "Bespin Meeting" }, { agendaId: "2", agendaTitle: "Endor Visit" }, { agendaId: "3", agendaTitle: "Hoth Beach Vacation" }])
                break;

            //Other
            case "asyncHttpRequest":
                result = JSON.stringify({ 'example': 'hello world' });
                break;
            case "getFollowupGuid":
                result = "0d38ecdb-fe7b-11ea-8e12-22000a0dc04b";
                break;
            case "previewNextFollowupLink":
                result = "http://www.adr.sh/23qg/e29l/30i/3u";
                break;
        }

        window[request.successMethodId](result);
    }

    //Marshall
    let _callNativeFunction = function (methodName, methodData) {
        var id = Math.floor(Math.random() * 10000000);
        var successId = methodName + "_success_" + id;
        var errorId = methodName + "_error_" + id;

        return new Promise(function (resolve, reject) {
            //build success function
            window[successId] = function (data) {
                resolve(data);
                window[successId] = null;
                window[errorId] = null;
                delete window[successId];
                delete window[errorId];
            };

            //build error function
            window[errorId] = function (data) {
                reject(data);
                window[successId] = null;
                window[errorId] = null;
                delete window[successId];
                delete window[errorId];
            };

            //create request
            let request = {
                methodName: methodName,
                data: methodData,
                successMethodId: successId,
                errorMethodId: errorId
            };

            let os = _getParameterByName("os");

            //For Windows builds that don't pass in the os param
            let userAgent = navigator.userAgent;

            //  Windows
            if (os === "windows" || userAgent.includes("Windows.Desktop")) {
                return window.external.notify(JSON.stringify(request));
            }

            //  iOS
            if (os === "ios" || (window.webkit && window.webkit.messageHandlers.modus != undefined)) {
                return window.webkit.messageHandlers.modus.postMessage(JSON.stringify(request));
            }
            //  Android
            if (os === "android" || window.appInterface != undefined) {
                return window.appInterface.postMessage(JSON.stringify(request));
            }

            //Defaults and Stubs
            return _createExampleResult(request);
        });
    }

    //Public
    return {
        //User
        getCurrentUserName: _callNativeFunction.bind(null, "getCurrentUserName", null),
        getCurrentUserEmail: _callNativeFunction.bind(null, "getCurrentUserEmail", null),
        getCurrentUserRegions: _callNativeFunction.bind(null, "getCurrentUserRegions", null),
        getAccessToken: _callNativeFunction.bind(null, "getAccessToken", null),

        //Storage
        getItem: function (key) { return _callNativeFunction("getItem", { key: key }) },
        setItem: function (key, value) { return _callNativeFunction("setItem", { key: key, value: value }) },
        getGlobalItem: function (key) { return _callNativeFunction("getGlobalItem", { key: key }) },
        setGlobalItem: function (key, value) { return _callNativeFunction("setGlobalItem", { key: key, value: value }) },

        //Emails
        sendEmail: function (to, cc, subject, body) { return _callNativeFunction("sendEmail", { to: to, cc: cc, subject: subject, body: body }) },
        sendEmailHtml: function (to, cc, subject, html) { return _callNativeFunction("sendEmailHtml", { to: to, cc: cc, subject: subject, html: html }) },
        sendEmailWithFileAttachmentFromBase64: function (data) { return _callNativeFunction("sendEmailWithFileAttachmentFromBase64", { data: data }) },

        //Agendas
        getAgendas: _callNativeFunction.bind(null, "getAgendas", null),
        sendAgenda: function (agendaId, emailAddress) { return _callNativeFunction("sendAgenda", { agendaId: agendaId, emailAddress: emailAddress }) },

        //Other
        scanBarcode: _callNativeFunction.bind(null, "scanPDF417Barcode", null),
        asyncHttpRequest: function (url, verb, headers, body) { return _callNativeFunction("asyncHttpRequest", { url: url, verb: verb, headers: headers, body: body }) },
        sendFollowup: function (step, bundleName, link) { return _callNativeFunction("sendFollowup", {step: step, bundle: bundleName, link : link }) },
        previewNextFollowupLink: _callNativeFunction.bind(null, "previewNextFollowupLink", null),
        getFollowupGuid: function (followupLink) { return _callNativeFunction("getFollowupGuid", { link: followupLink }) },
        promptShareMenuWithData: function (fileName, base64) { return _callNativeFunction("promptShareMenuWithData", { nane: fileName, fileAsBase64: base64 }) },

    }
}();<commit_msg>added new functions used for the micro site and also converted it to be use export default Modus instead of overriding it as window.modus<commit_after>/* eslint-disable */
var Modus = (function() {
    //Variables
    let _os = _getParameterByName("os");

    //Helpers
    function _getParameterByName(name, url) {
        if (!url) url = window.location.href;
        name = name.replace(/[\[\]]/g, '\\$&');
        var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
            results = regex.exec(url);
        if (!results) return null;
        if (!results[2]) return '';
        return decodeURIComponent(results[2].replace(/\+/g, ' '));
    }

    //Break this in to a different file
    let _createExampleResult = function (request) {
        //TODO: should this be somewhere else?
        var name = request.methodName;
        var result = null;

        switch (name) {
            case "getCurrentUserName":
                result = "Obi Won Kenobi"
                break;
            case "getCurrentUserEmail":
                result = "maul_killer@jedicouncil.crst"
                break;
            case "getAccessToken":
                result = "exampleToken"
                break;
            case "getCurrentUserRegions":
                result = ["Tatooine", "Stewjon", "Coruscant"]
                break;

            //Storage
            case "getItem":
            case "getGlobalItem":
                result = localStorage.getItem(request.data.key);
                break;
            case "setItem":
            case "setGlobalItem":
                localStorage.setItem(request.data.key, request.data.value);
                break;

            //Email
            case "sendAgenda":
            case "sendEmail":
            case "sendEmailHtml":
                var e = request.data;
                var body = e.body ? e.body : e.html ? e.html : "";
                var to = e.to ? e.to : e.emailAddress;
                var mailto = "mailto:" + to + "?subject=" + e.subject + "&body=" + body + "&cc=" + e.cc;
                window.open(mailto);
                break;
            //Agendas
            case "getAgendas":
                result = JSON.stringify([{agendaId: "1", agendaTitle: "Bespin Meeting"}, {agendaId: "2", agendaTitle: "Endor Visit"}, {agendaId: "3", agendaTitle: "Hoth Beach Vacation"}])
                break;
        }

        window[request.successMethodId](result);
    }

    //Marshall
    let _callNativeFunction = function (methodName, methodData) {
        var id = Math.floor(Math.random() * 10000000);
        var successId = methodName + "_success_" + id;
        var errorId = methodName + "_error_" + id;

        return new Promise(function (resolve, reject) {
            //build success function
            window[successId] = function (data) {
                resolve(data);
                window[successId] = null;
                window[errorId] = null;
                delete window[successId];
                delete window[errorId];
            };

            //build error function
            window[errorId] = function (data) {
                reject(data);
                window[successId] = null;
                window[errorId] = null;
                delete window[successId];
                delete window[errorId];
            };

            //create request
            let request = {
                methodName: methodName,
                data: methodData,
                successMethodId: successId,
                errorMethodId: errorId
            };

            let os = _getParameterByName("os");

            //For Windows builds that don't pass in the os param
            let userAgent = navigator.userAgent;

            //  Windows
            if (os === "windows" || userAgent.includes("Windows.Desktop")) {
                return window.external.notify(JSON.stringify(request));
            }

            //  iOS
            if (os === "ios" || (window.webkit && window.webkit.messageHandlers.modus != undefined)) {
                return window.webkit.messageHandlers.modus.postMessage(request);
            }
            //  Android
            if (os === "android" || window.appInterface != undefined) {
                return window.appInterface.postMessage(JSON.stringify(request));
            }

            //Defaults and Stubs
            return _createExampleResult(request);
        });
    }

    //Public
    return {
         //User
        getCurrentUserName: _callNativeFunction.bind(null, "getCurrentUserName", null),
        getCurrentUserEmail: _callNativeFunction.bind(null, "getCurrentUserEmail", null),
        getCurrentUserRegions: _callNativeFunction.bind(null, "getCurrentUserRegions", null),
        getAccessToken: _callNativeFunction.bind(null, "getAccessToken", null),

        //Storage
        getItem: function (key) { return _callNativeFunction("getItem", { key: key }) },
        setItem: function (key, value) { return _callNativeFunction("setItem", { key: key, value: value }) },
        getGlobalItem: function (key) { return _callNativeFunction("getGlobalItem", { key: key }) },
        setGlobalItem: function (key, value) { return _callNativeFunction("setGlobalItem", { key: key, value: value }) },

        //Emails
        sendEmail: function (to, cc, subject, body) { return _callNativeFunction("sendEmail", { to: to, cc: cc, subject: subject, body: body }) },
        sendEmailHtml: function (to, cc, subject, html) { return _callNativeFunction("sendEmailHtml", { to: to, cc: cc, subject: subject, html: html }) },
        sendEmailWithFileAttachmentFromBase64: function (data) { return _callNativeFunction("sendEmailWithFileAttachmentFromBase64", { data: data }) },

        //Agendas
        getAgendas: _callNativeFunction.bind(null, "getAgendas", null),
        sendAgenda: function (agendaId, emailAddress) { return _callNativeFunction("sendAgenda", { agendaId: agendaId, emailAddress: emailAddress }) },

        //Other
        scanBarcode: _callNativeFunction.bind(null, "scanPDF417Barcode", null),
        asyncHttpRequest: function (url, verb, headers, body) { return _callNativeFunction("asyncHttpRequest", { url: url, verb: verb, headers: headers, body: body }) },
        sendFollowup: function (step, bundleName, link) { return _callNativeFunction("sendFollowup", {step: step, bundle: bundleName, link : link }) },
        previewNextFollowupLink: _callNativeFunction.bind(null, "previewNextFollowupLink", null),
        getFollowupGuid: function (followupLink) { return _callNativeFunction("getFollowupGuid", { link: followupLink }) },
        promptShareMenuWithData: function (fileName, base64) { return _callNativeFunction("promptShareMenuWithData", { nane: fileName, fileAsBase64: base64 }) },
        getMediaWithPicker: function (currentMedias) { return _callNativeFunction("getMediaWithPicker", {medias: currentMedias }) },
        getDeviceFilePicker: function (type, guid, user) { return _callNativeFunction("getDeviceFilePicker", {type: type, guid: guid, user: user }) },
    }
})();

export default Modus;<|endoftext|>


<commit_before>import defined from "./defined.js";
import IndexDatatype from "./IndexDatatype.js";
import PrimitiveType from "./PrimitiveType.js";

/**
 * Utility functions for generating indices for model wireframes. The indices are
 * outputted as typed arrays, which can then be put into buffers for rendering.
 *
 * @private
 */
export default function WireframeIndexGenerator() {}

function createWireframeFromTriangles(vertexCount) {
  const wireframeIndices = IndexDatatype.createTypedArray(
    vertexCount,
    vertexCount * 2
  );
  const length = vertexCount;
  let index = 0;
  for (let i = 0; i < length; i += 3) {
    wireframeIndices[index++] = i;
    wireframeIndices[index++] = i + 1;
    wireframeIndices[index++] = i + 1;
    wireframeIndices[index++] = i + 2;
    wireframeIndices[index++] = i + 2;
    wireframeIndices[index++] = i;
  }

  return wireframeIndices;
}

function createWireframeFromTriangleIndices(vertexCount, originalIndices) {
  const originalIndicesCount = originalIndices.length;
  const wireframeIndices = IndexDatatype.createTypedArray(
    vertexCount,
    originalIndicesCount * 2
  );
  let index = 0;
  for (let i = 0; i < originalIndicesCount; i += 3) {
    const point0 = originalIndices[i];
    const point1 = originalIndices[i + 1];
    const point2 = originalIndices[i + 2];

    wireframeIndices[index++] = point0;
    wireframeIndices[index++] = point1;
    wireframeIndices[index++] = point1;
    wireframeIndices[index++] = point2;
    wireframeIndices[index++] = point2;
    wireframeIndices[index++] = point0;
  }

  return wireframeIndices;
}

function createWireframeFromTriangleStrip(vertexCount) {
  const numberOfTriangles = vertexCount - 2;
  const wireframeIndicesCount = 2 + numberOfTriangles * 4;
  const wireframeIndices = IndexDatatype.createTypedArray(
    vertexCount,
    wireframeIndicesCount
  );
  let index = 0;

  // Handle the first edge
  wireframeIndices[index++] = 0;
  wireframeIndices[index++] = 1;

  // Add two edges for every triangle in the strip
  for (let i = 0; i < numberOfTriangles; i++) {
    wireframeIndices[index++] = i + 1;
    wireframeIndices[index++] = i + 2;
    wireframeIndices[index++] = i + 2;
    wireframeIndices[index++] = i;
  }

  return wireframeIndices;
}

function createWireframeFromTriangleStripIndices(vertexCount, originalIndices) {
  const originalIndicesCount = originalIndices.length;
  const numberOfTriangles = originalIndicesCount - 2;
  const wireframeIndicesCount = 2 + numberOfTriangles * 4;
  const wireframeIndices = IndexDatatype.createTypedArray(
    vertexCount,
    wireframeIndicesCount
  );
  let index = 0;

  // Handle the first edge
  wireframeIndices[index++] = originalIndices[0];
  wireframeIndices[index++] = originalIndices[1];

  // Add two edges for every triangle in the strip
  for (let i = 0; i < numberOfTriangles; i++) {
    const point0 = originalIndices[i];
    const point1 = originalIndices[i + 1];
    const point2 = originalIndices[i + 2];

    wireframeIndices[index++] = point1;
    wireframeIndices[index++] = point2;
    wireframeIndices[index++] = point2;
    wireframeIndices[index++] = point0;
  }

  return wireframeIndices;
}

function createWireframeFromTriangleFan(vertexCount) {
  const numberOfTriangles = vertexCount - 2;
  const wireframeIndicesCount = 2 + numberOfTriangles * 4;
  const wireframeIndices = IndexDatatype.createTypedArray(
    vertexCount,
    wireframeIndicesCount
  );
  let index = 0;

  // Handle the first edge
  wireframeIndices[index++] = 0;
  wireframeIndices[index++] = 1;

  // Add two edges for every triangle in the fan
  for (let i = 0; i < numberOfTriangles; i++) {
    wireframeIndices[index++] = i + 1;
    wireframeIndices[index++] = i + 2;
    wireframeIndices[index++] = i + 2;
    wireframeIndices[index++] = 0;
  }

  return wireframeIndices;
}

function createWireframeFromTriangleFanIndices(vertexCount, originalIndices) {
  const originalIndicesCount = originalIndices.length;
  const numberOfTriangles = originalIndicesCount - 2;
  const wireframeIndicesCount = 2 + numberOfTriangles * 4;
  const wireframeIndices = IndexDatatype.createTypedArray(
    vertexCount,
    wireframeIndicesCount
  );
  let index = 0;

  // Handle the first edge
  const firstPoint = originalIndices[0];
  wireframeIndices[index++] = firstPoint;
  wireframeIndices[index++] = originalIndices[1];

  // Add two edges for every triangle in the fan
  for (let i = 0; i < numberOfTriangles; i++) {
    const point1 = originalIndices[i + 1];
    const point2 = originalIndices[i + 2];

    wireframeIndices[index++] = point1;
    wireframeIndices[index++] = point2;
    wireframeIndices[index++] = point2;
    wireframeIndices[index++] = firstPoint;
  }

  return wireframeIndices;
}

/**
 * Generates a wireframe index buffer for a primitive.
 *
 * @param {PrimitiveType} primitiveType The primitive type.
 * @param {Number} vertexCount The number of vertices in the primitive.
 * @param {Uint8Array|Uint16Array|Uint32Array} [originalIndices] A typed array containing the original indices of the primitive.
 *
 * @return {Uint16Array|Uint32Array} A typed array with the wireframe indices, or undefined if the primitive type does not use triangles.
 *
 * @private
 */
WireframeIndexGenerator.createWireframeIndices = function (
  primitiveType,
  vertexCount,
  originalIndices
) {
  const hasOriginalIndices = defined(originalIndices);
  if (primitiveType === PrimitiveType.TRIANGLES) {
    return hasOriginalIndices
      ? createWireframeFromTriangleIndices(vertexCount, originalIndices)
      : createWireframeFromTriangles(vertexCount);
  }

  if (primitiveType === PrimitiveType.TRIANGLE_STRIP) {
    return hasOriginalIndices
      ? createWireframeFromTriangleStripIndices(vertexCount, originalIndices)
      : createWireframeFromTriangleStrip(vertexCount);
  }

  if (primitiveType === PrimitiveType.TRIANGLE_FAN) {
    return hasOriginalIndices
      ? createWireframeFromTriangleFanIndices(vertexCount, originalIndices)
      : createWireframeFromTriangleFan(vertexCount);
  }

  return undefined;
};

/**
 * Gets the number of indices in the wireframe index buffer of a primitive type.
 *
 * @param {PrimitiveType} primitiveType The primitive type.
 * @param {Number} originalCount The original number of vertices or indices in the primitive.
 * @return {Number} The number of indices in the primitive's wireframe.
 *
 * @private
 */
WireframeIndexGenerator.getWireframeIndicesCount = function (
  primitiveType,
  originalCount
) {
  // For TRIANGLES, the wireframe takes every triangle (i.e. three of the original
  // indices) and turns it into lines. Each triangle has three lines, and each line
  // requires two indices, so the final count is twice the original.
  if (primitiveType === PrimitiveType.TRIANGLES) {
    return originalCount * 2;
  }

  // For TRIANGLE_STRIP and TRIANGLE_FAN, the number of triangles in the primitive
  // is equal to the total number of vertices minus two. This is because after the
  // first edge is specified by the first two indices, every point afterwards
  // contributes two more edges with two of the previous points, forming a new triangle.
  // Each of these edges requires two indices, so each triangle in the primitive
  // results in four indices in addition to the first two.
  if (
    primitiveType === PrimitiveType.TRIANGLE_STRIP ||
    primitiveType === PrimitiveType.TRIANGLE_FAN
  ) {
    const numberOfTriangles = originalCount - 2;
    return 2 + numberOfTriangles * 4;
  }

  return originalCount;
};
<commit_msg>Make WireframeIndexGenerator a namespace<commit_after>import defined from "./defined.js";
import IndexDatatype from "./IndexDatatype.js";
import PrimitiveType from "./PrimitiveType.js";

/**
 * Functions for generating indices for model wireframes. The indices are
 * outputted as typed arrays, which can then be put into buffers for rendering.
 *
 * @namespace WireframeIndexGenerator
 * @private
 */
const WireframeIndexGenerator = {};

function createWireframeFromTriangles(vertexCount) {
  const wireframeIndices = IndexDatatype.createTypedArray(
    vertexCount,
    vertexCount * 2
  );
  const length = vertexCount;
  let index = 0;
  for (let i = 0; i < length; i += 3) {
    wireframeIndices[index++] = i;
    wireframeIndices[index++] = i + 1;
    wireframeIndices[index++] = i + 1;
    wireframeIndices[index++] = i + 2;
    wireframeIndices[index++] = i + 2;
    wireframeIndices[index++] = i;
  }

  return wireframeIndices;
}

function createWireframeFromTriangleIndices(vertexCount, originalIndices) {
  const originalIndicesCount = originalIndices.length;
  const wireframeIndices = IndexDatatype.createTypedArray(
    vertexCount,
    originalIndicesCount * 2
  );
  let index = 0;
  for (let i = 0; i < originalIndicesCount; i += 3) {
    const point0 = originalIndices[i];
    const point1 = originalIndices[i + 1];
    const point2 = originalIndices[i + 2];

    wireframeIndices[index++] = point0;
    wireframeIndices[index++] = point1;
    wireframeIndices[index++] = point1;
    wireframeIndices[index++] = point2;
    wireframeIndices[index++] = point2;
    wireframeIndices[index++] = point0;
  }

  return wireframeIndices;
}

function createWireframeFromTriangleStrip(vertexCount) {
  const numberOfTriangles = vertexCount - 2;
  const wireframeIndicesCount = 2 + numberOfTriangles * 4;
  const wireframeIndices = IndexDatatype.createTypedArray(
    vertexCount,
    wireframeIndicesCount
  );
  let index = 0;

  // Handle the first edge
  wireframeIndices[index++] = 0;
  wireframeIndices[index++] = 1;

  // Add two edges for every triangle in the strip
  for (let i = 0; i < numberOfTriangles; i++) {
    wireframeIndices[index++] = i + 1;
    wireframeIndices[index++] = i + 2;
    wireframeIndices[index++] = i + 2;
    wireframeIndices[index++] = i;
  }

  return wireframeIndices;
}

function createWireframeFromTriangleStripIndices(vertexCount, originalIndices) {
  const originalIndicesCount = originalIndices.length;
  const numberOfTriangles = originalIndicesCount - 2;
  const wireframeIndicesCount = 2 + numberOfTriangles * 4;
  const wireframeIndices = IndexDatatype.createTypedArray(
    vertexCount,
    wireframeIndicesCount
  );
  let index = 0;

  // Handle the first edge
  wireframeIndices[index++] = originalIndices[0];
  wireframeIndices[index++] = originalIndices[1];

  // Add two edges for every triangle in the strip
  for (let i = 0; i < numberOfTriangles; i++) {
    const point0 = originalIndices[i];
    const point1 = originalIndices[i + 1];
    const point2 = originalIndices[i + 2];

    wireframeIndices[index++] = point1;
    wireframeIndices[index++] = point2;
    wireframeIndices[index++] = point2;
    wireframeIndices[index++] = point0;
  }

  return wireframeIndices;
}

function createWireframeFromTriangleFan(vertexCount) {
  const numberOfTriangles = vertexCount - 2;
  const wireframeIndicesCount = 2 + numberOfTriangles * 4;
  const wireframeIndices = IndexDatatype.createTypedArray(
    vertexCount,
    wireframeIndicesCount
  );
  let index = 0;

  // Handle the first edge
  wireframeIndices[index++] = 0;
  wireframeIndices[index++] = 1;

  // Add two edges for every triangle in the fan
  for (let i = 0; i < numberOfTriangles; i++) {
    wireframeIndices[index++] = i + 1;
    wireframeIndices[index++] = i + 2;
    wireframeIndices[index++] = i + 2;
    wireframeIndices[index++] = 0;
  }

  return wireframeIndices;
}

function createWireframeFromTriangleFanIndices(vertexCount, originalIndices) {
  const originalIndicesCount = originalIndices.length;
  const numberOfTriangles = originalIndicesCount - 2;
  const wireframeIndicesCount = 2 + numberOfTriangles * 4;
  const wireframeIndices = IndexDatatype.createTypedArray(
    vertexCount,
    wireframeIndicesCount
  );
  let index = 0;

  // Handle the first edge
  const firstPoint = originalIndices[0];
  wireframeIndices[index++] = firstPoint;
  wireframeIndices[index++] = originalIndices[1];

  // Add two edges for every triangle in the fan
  for (let i = 0; i < numberOfTriangles; i++) {
    const point1 = originalIndices[i + 1];
    const point2 = originalIndices[i + 2];

    wireframeIndices[index++] = point1;
    wireframeIndices[index++] = point2;
    wireframeIndices[index++] = point2;
    wireframeIndices[index++] = firstPoint;
  }

  return wireframeIndices;
}

/**
 * Generates a wireframe index buffer for a primitive, either by reindexing the existing indices
 * or creating them from scratch if the model had none.
 *
 * @param {PrimitiveType} primitiveType The primitive type.
 * @param {Number} vertexCount The number of vertices in the primitive.
 * @param {Uint8Array|Uint16Array|Uint32Array} [originalIndices] A typed array containing the original indices of the primitive.
 *
 * @return {Uint16Array|Uint32Array} A typed array with the wireframe indices, or undefined if the primitive type does not use triangles.
 *
 * @private
 */
WireframeIndexGenerator.createWireframeIndices = function (
  primitiveType,
  vertexCount,
  originalIndices
) {
  const hasOriginalIndices = defined(originalIndices);
  if (primitiveType === PrimitiveType.TRIANGLES) {
    return hasOriginalIndices
      ? createWireframeFromTriangleIndices(vertexCount, originalIndices)
      : createWireframeFromTriangles(vertexCount);
  }

  if (primitiveType === PrimitiveType.TRIANGLE_STRIP) {
    return hasOriginalIndices
      ? createWireframeFromTriangleStripIndices(vertexCount, originalIndices)
      : createWireframeFromTriangleStrip(vertexCount);
  }

  if (primitiveType === PrimitiveType.TRIANGLE_FAN) {
    return hasOriginalIndices
      ? createWireframeFromTriangleFanIndices(vertexCount, originalIndices)
      : createWireframeFromTriangleFan(vertexCount);
  }

  return undefined;
};

/**
 * Gets the number of indices in the wireframe index buffer of a primitive type.
 *
 * @param {PrimitiveType} primitiveType The primitive type.
 * @param {Number} originalCount The original number of vertices or indices in the primitive.
 * @return {Number} The number of indices in the primitive's wireframe.
 *
 * @private
 */
WireframeIndexGenerator.getWireframeIndicesCount = function (
  primitiveType,
  originalCount
) {
  // For TRIANGLES, the wireframe takes every triangle (i.e. three of the original
  // indices) and turns it into lines. Each triangle has three lines, and each line
  // requires two indices, so the final count is twice the original.
  if (primitiveType === PrimitiveType.TRIANGLES) {
    return originalCount * 2;
  }

  // For TRIANGLE_STRIP and TRIANGLE_FAN, the number of triangles in the primitive
  // is equal to the total number of vertices minus two. This is because after the
  // first edge is specified by the first two indices, every point afterwards
  // contributes two more edges with two of the previous points, forming a new triangle.
  // Each of these edges requires two indices, so each triangle in the primitive
  // results in four indices in addition to the first two.
  if (
    primitiveType === PrimitiveType.TRIANGLE_STRIP ||
    primitiveType === PrimitiveType.TRIANGLE_FAN
  ) {
    const numberOfTriangles = originalCount - 2;
    return 2 + numberOfTriangles * 4;
  }

  return originalCount;
};

export default WireframeIndexGenerator;
<|endoftext|>


<commit_before>//global variables go here:

//execute functions here:
setUp();

//function definitions go here:

function randomAnswers() {
    var answers = [1, 1, 2, 2, 3, 3, 4, 4, 5];
    answers.sort(function (item) {
        return .5 - Math.random();
    })
    return answers;
}

function setUp() {
    var grid = document.getElementsByTagName("td");
    var answers = randomAnswers();

    for (var i = 0; i < grid.length; i++) {
        var cell = grid[i];
        cell.completed = false;
        cell.clicked = false;
        cell.value = answers[i];

        cell.addEventListener("mouseenter", function () {
            if (this.completed == false && this.clicked == false)
                this.style.background = "orange";
        });

        cell.addEventListener("mouseleave", function () {
            if (this.completed == false && this.clicked == false)
                this.style.background = "blue";
        });

        cell.addEventListener("click", function () {
            if (this.isCompleted) {
                return;
            }

            // find if theres any other match
            var grid = document.getElementsByTagName("td");
            for (var i = 0; i < grid.length; i++) {
                var cell = grid[i], otherClickedCell;
                if (cell.isClicked) {
                    otherClickedCell = cell;
                }
            };

            console.log(otherClickedCell);

            if (!otherClickedCell) { // not other cell clicked
                this.style.background = "red";
                this.innerText = this.value;
                this.clicked = true;
            } else {
                if (otherClickedCell.value == this.value) { // matches the value
                    otherClickedCell.isCompleted = true;
                    otherClickedCell.style.background = "purple";
                    this.isCompleted = true;
                    this.style.background = "purple";
                    this.innerText = this.value;
                } else {
                    otherClickedCell.isClicked = false;
                    otherClickedCell.style.background = "blue";
                }
            }
        });
    }
}

<commit_msg>Mod1 tutorial<commit_after>//global variables go here:
var clickedArray = [];
var interval;
var started = false;
var time = 0;

//execute functions here:
setUp();

//function definitions go here:

function reveal(cell) {
    cell.style.backgroundColor = "red";
    cell.innerHTML = cell.value;
    cell.clicked = true;
}

function startTimer() {
    if (started == false) {
        document.getElementById("timer").innerHTML = "Time Elapsed: " + time;

        interval = setInterval(function () {
            time++;
            document.getElementById("timer").innerHTML = "Time Elapsed: " + time;
        }, 1000);
        started = true;
    }
}

function randomAnswers() {
    var answers = [1, 1, 2, 2, 3, 3, 4, 4, 5];
    answers.sort(function (item) {
        return .5 - Math.random();
    })
    return answers;
}

function setUp() {
    var grid = document.getElementsByTagName("td");
    var answers = randomAnswers();

    for (var i = 0; i < grid.length; i++) {
        var cell = grid[i];
        cell.completed = false;
        cell.clicked = false;
        cell.value = answers[i];

        cell.addEventListener("mouseenter", function () {
            if (this.completed == false && this.clicked == false)
                this.style.background = "orange";
        });

        cell.addEventListener("mouseleave", function () {
            if (this.completed == false && this.clicked == false)
                this.style.background = "blue";
        });

        cell.addEventListener("click", function () {
            startTimer();

            if (this.completed == false && this.clicked == false) {
                clickedArray.push(this);
                reveal(this);
            }
        });
    }
}

<|endoftext|>


<commit_before>import React from "react";
import { Table } from "reactjs-components";

import ConfigurationMapHeading
  from "#SRC/js/components/ConfigurationMapHeading";
import Networking from "#SRC/js/constants/Networking";
import { findNestedPropertyInObject } from "#SRC/js/utils/Util";
import ValidatorUtil from "#SRC/js/utils/ValidatorUtil";

import ConfigurationMapEditAction
  from "../components/ConfigurationMapEditAction";
import {
  getColumnClassNameFn,
  getColumnHeadingFn,
  getDisplayValue
} from "../utils/ServiceConfigDisplayUtil";
import ServiceConfigUtil from "../utils/ServiceConfigUtil";
import ServiceConfigBaseSectionDisplay from "./ServiceConfigBaseSectionDisplay";

function getNetworkType(networkType, appDefinition) {
  networkType = networkType || Networking.type.HOST;
  const networkName = findNestedPropertyInObject(
    appDefinition,
    "ipAddress.networkName"
  );

  return networkName != null ? Networking.type.USER : networkType;
}

class ServiceNetworkingConfigSection extends ServiceConfigBaseSectionDisplay {
  /**
   * @override
   */
  shouldExcludeItem(row) {
    if (row.key !== "ipAddress.networkName") {
      return false;
    }

    const { appConfig } = this.props;
    const networkName = findNestedPropertyInObject(appConfig, row.key);

    return !networkName;
  }

  /**
   * @override
   */
  getDefinition() {
    const { onEditClick } = this.props;

    return {
      tabViewID: "networking",
      values: [
        {
          heading: "Network",
          headingLevel: 1
        },
        {
          key: "container.docker.network",
          label: "Network Type",
          transformValue: getNetworkType
        },
        {
          key: "ipAddress.networkName",
          label: "Network Name"
        },
        {
          key: "portDefinitions",
          render(portDefinitions, appDefinition) {
            const keys = {
              name: "name",
              port: "port",
              protocol: "protocol",
              labels: "labels",
              service: "servicePort"
            };

            const networkType = getNetworkType(
              findNestedPropertyInObject(
                appDefinition,
                "container.docker.network"
              ),
              appDefinition
            );

            const containerPortMappings = findNestedPropertyInObject(
              appDefinition,
              "container.docker.portMappings"
            );

            if (
              containerPortMappings != null &&
              containerPortMappings.length !== 0
            ) {
              portDefinitions = containerPortMappings;
              keys.port = "hostPort";
            }

            // Make sure to have something to render, even if there is no data
            if (!portDefinitions) {
              portDefinitions = [];
            }

            const columns = [
              {
                heading: getColumnHeadingFn("Name"),
                prop: keys.name,
                render(prop, row) {
                  return getDisplayValue(row[prop]);
                },
                className: getColumnClassNameFn(),
                sortable: true
              },
              {
                heading: getColumnHeadingFn("Protocol"),
                prop: keys.protocol,
                className: getColumnClassNameFn(),
                render(prop, row) {
                  let protocol = row[prop] || "";
                  protocol = protocol.replace(/,\s*/g, ", ");

                  return getDisplayValue(protocol);
                },
                sortable: true
              },
              {
                heading: getColumnHeadingFn("Host Port"),
                prop: keys.port,
                className: getColumnClassNameFn(),
                render(prop, row) {
                  return getDisplayValue(row[prop]);
                },
                sortable: true
              },
              {
                heading: getColumnHeadingFn("Load Balanced Address"),
                prop: "",
                className: getColumnClassNameFn(),
                render(prop, row) {
                  const { port, labels } = row;
                  const vipLabel = ServiceConfigUtil.findVIPLabel(labels);

                  if (vipLabel) {
                    return ServiceConfigUtil.buildHostNameFromVipLabel(
                      labels[vipLabel],
                      port
                    );
                  }

                  return Not Enabled;
                },
                sortable: true
              }
            ];

            // We add the container port column if the network type is anything
            // but HOST.
            if (networkType !== Networking.type.HOST) {
              const hostPortIndex = columns.findIndex(column => {
                return column.prop === keys.port;
              });

              columns.splice(hostPortIndex, 0, {
                heading: getColumnHeadingFn("Container Port"),
                prop: "containerPort",
                className: getColumnClassNameFn(),
                render(prop, row) {
                  return getDisplayValue(row[prop]);
                },
                sortable: true
              });
            }

            const containsServicePorts = portDefinitions.filter(function(
              portDefinition
            ) {
              const result = portDefinition.servicePort
                ? portDefinition.servicePort !== 0
                : false;

              return result;
            });

            if (containsServicePorts.length > 0) {
              const hostPortIndex = columns.findIndex(column => {
                return column.prop === keys.port;
              });
              const servicePortsPosition = hostPortIndex + 1;

              columns.splice(servicePortsPosition, 0, {
                heading: getColumnHeadingFn("Service Port"),
                prop: keys.service,
                className: getColumnClassNameFn(),
                render(prop, row) {
                  return getDisplayValue(row[prop]);
                },
                sortable: true
              });
            }

            if (onEditClick) {
              columns.push({
                heading() {
                  return null;
                },
                className: "configuration-map-action",
                prop: "edit",
                render() {
                  return (
                    <ConfigurationMapEditAction
                      onEditClick={onEditClick}
                      tabViewID="networking"
                    />
                  );
                }
              });
            }

            if (ValidatorUtil.isEmpty(portDefinitions)) {
              return;
            }

            return [
              <ConfigurationMapHeading
                key="service-endpoints-heading"
                level={2}
              >

                Service Endpoints
              </ConfigurationMapHeading>,

            ];
          }
        }
      ]
    };
  }
}

module.exports = ServiceNetworkingConfigSection;
<commit_msg>fix(DCOS-15234): Minor improvement to detecting if there is service port available to display<commit_after>import React from "react";
import { Table } from "reactjs-components";

import ConfigurationMapHeading
  from "#SRC/js/components/ConfigurationMapHeading";
import Networking from "#SRC/js/constants/Networking";
import { findNestedPropertyInObject } from "#SRC/js/utils/Util";
import ValidatorUtil from "#SRC/js/utils/ValidatorUtil";

import ConfigurationMapEditAction
  from "../components/ConfigurationMapEditAction";
import {
  getColumnClassNameFn,
  getColumnHeadingFn,
  getDisplayValue
} from "../utils/ServiceConfigDisplayUtil";
import ServiceConfigUtil from "../utils/ServiceConfigUtil";
import ServiceConfigBaseSectionDisplay from "./ServiceConfigBaseSectionDisplay";

function getNetworkType(networkType, appDefinition) {
  networkType = networkType || Networking.type.HOST;
  const networkName = findNestedPropertyInObject(
    appDefinition,
    "ipAddress.networkName"
  );

  return networkName != null ? Networking.type.USER : networkType;
}

class ServiceNetworkingConfigSection extends ServiceConfigBaseSectionDisplay {
  /**
   * @override
   */
  shouldExcludeItem(row) {
    if (row.key !== "ipAddress.networkName") {
      return false;
    }

    const { appConfig } = this.props;
    const networkName = findNestedPropertyInObject(appConfig, row.key);

    return !networkName;
  }

  /**
   * @override
   */
  getDefinition() {
    const { onEditClick } = this.props;

    return {
      tabViewID: "networking",
      values: [
        {
          heading: "Network",
          headingLevel: 1
        },
        {
          key: "container.docker.network",
          label: "Network Type",
          transformValue: getNetworkType
        },
        {
          key: "ipAddress.networkName",
          label: "Network Name"
        },
        {
          key: "portDefinitions",
          render(portDefinitions, appDefinition) {
            const keys = {
              name: "name",
              port: "port",
              protocol: "protocol",
              labels: "labels",
              service: "servicePort"
            };

            const networkType = getNetworkType(
              findNestedPropertyInObject(
                appDefinition,
                "container.docker.network"
              ),
              appDefinition
            );

            const containerPortMappings = findNestedPropertyInObject(
              appDefinition,
              "container.docker.portMappings"
            );

            if (
              containerPortMappings != null &&
              containerPortMappings.length !== 0
            ) {
              portDefinitions = containerPortMappings;
              keys.port = "hostPort";
            }

            // Make sure to have something to render, even if there is no data
            if (!portDefinitions) {
              portDefinitions = [];
            }

            const columns = [
              {
                heading: getColumnHeadingFn("Name"),
                prop: keys.name,
                render(prop, row) {
                  return getDisplayValue(row[prop]);
                },
                className: getColumnClassNameFn(),
                sortable: true
              },
              {
                heading: getColumnHeadingFn("Protocol"),
                prop: keys.protocol,
                className: getColumnClassNameFn(),
                render(prop, row) {
                  let protocol = row[prop] || "";
                  protocol = protocol.replace(/,\s*/g, ", ");

                  return getDisplayValue(protocol);
                },
                sortable: true
              },
              {
                heading: getColumnHeadingFn("Host Port"),
                prop: keys.port,
                className: getColumnClassNameFn(),
                render(prop, row) {
                  return getDisplayValue(row[prop]);
                },
                sortable: true
              },
              {
                heading: getColumnHeadingFn("Load Balanced Address"),
                prop: "",
                className: getColumnClassNameFn(),
                render(prop, row) {
                  const { port, labels } = row;
                  const vipLabel = ServiceConfigUtil.findVIPLabel(labels);

                  if (vipLabel) {
                    return ServiceConfigUtil.buildHostNameFromVipLabel(
                      labels[vipLabel],
                      port
                    );
                  }

                  return Not Enabled;
                },
                sortable: true
              }
            ];

            // We add the container port column if the network type is anything
            // but HOST.
            if (networkType !== Networking.type.HOST) {
              const hostPortIndex = columns.findIndex(column => {
                return column.prop === keys.port;
              });

              columns.splice(hostPortIndex, 0, {
                heading: getColumnHeadingFn("Container Port"),
                prop: "containerPort",
                className: getColumnClassNameFn(),
                render(prop, row) {
                  return getDisplayValue(row[prop]);
                },
                sortable: true
              });
            }

            const containsServicePorts = portDefinitions.some(function(
              portDefinition
            ) {
              return (
                portDefinition.servicePort && portDefinition.servicePort !== 0
              );
            });

            if (containsServicePorts) {
              const hostPortIndex = columns.findIndex(column => {
                return column.prop === keys.port;
              });
              const servicePortsPosition = hostPortIndex + 1;

              columns.splice(servicePortsPosition, 0, {
                heading: getColumnHeadingFn("Service Port"),
                prop: keys.service,
                className: getColumnClassNameFn(),
                render(prop, row) {
                  return getDisplayValue(row[prop]);
                },
                sortable: true
              });
            }

            if (onEditClick) {
              columns.push({
                heading() {
                  return null;
                },
                className: "configuration-map-action",
                prop: "edit",
                render() {
                  return (
                    <ConfigurationMapEditAction
                      onEditClick={onEditClick}
                      tabViewID="networking"
                    />
                  );
                }
              });
            }

            if (ValidatorUtil.isEmpty(portDefinitions)) {
              return;
            }

            return [
              <ConfigurationMapHeading
                key="service-endpoints-heading"
                level={2}
              >

                Service Endpoints
              </ConfigurationMapHeading>,

            ];
          }
        }
      ]
    };
  }
}

module.exports = ServiceNetworkingConfigSection;
<|endoftext|>


<commit_before>var assert = require('assert');
var sinon  = require('sinon');
var rewire = require('rewire');

var DeptimeUpdater = rewire("../lib/codebase/deptimeupdater");

suite('dependency mtime updater', function(){
	setup(function(){

		DeptimeUpdater.__set__("log", { verbose: function () {} });

	});

	teardown(function(){

	});

	suite('run', function () {

		test('simple dep tree, all dependents are timed to the freshest dependency', function (done) {

			var modules = [
				{
					module: 'mod/Foo',
					dependencies: ['mod/Bar'],
					transitive_dependencies: ['deps/Baz', 'mod/Bar'],
					mtime: new Date("2014-05-13T14:57:32.000Z"),
					requirecalls: []
				},
				{
					module: 'mod/Bar',
					dependencies: ['deps/Baz'],
					transitive_dependencies: ['deps/Baz'],
					mtime: new Date("2014-05-13T14:57:32.000Z"),
					requirecalls: []
				},
				{
					module: 'deps/Baz',
					dependencies: [],
					transitive_dependencies: [],
					mtime: new Date("2014-05-14T14:57:32.000Z"),
					requirecalls: []
				}
			];

			try {

				var next = sinon.spy();
				var deps = new DeptimeUpdater();

				deps.on('end', function (modules, cb) {
					modules.forEach(function (module) {
						assert.equal(+new Date(module.mtime), 1400079452000);
					});
					done();
				});

				deps.run(modules, next);

			} catch (e) {
				done(e);
			}
		});

	});

});<commit_msg>add tests #12<commit_after>var assert = require('assert');
var sinon  = require('sinon');
var rewire = require('rewire');

var DeptimeUpdater = rewire("../lib/codebase/deptimeupdater");

suite('dependency mtime updater', function(){
	setup(function(){

		DeptimeUpdater.__set__("log", { verbose: function () {} });

	});

	teardown(function(){

	});

	suite('run', function () {

		test('simple dep tree, all dependents are timed to the freshest dependency', function (done) {

			var modules = [
				{
					module: 'mod/Foo',
					dependencies: ['mod/Bar'],
					transitive_dependencies: ['deps/Baz', 'mod/Bar'],
					mtime: new Date("2014-05-13T14:57:32.000Z"),
					requirecalls: []
				},
				{
					module: 'mod/Bar',
					dependencies: ['deps/Baz'],
					transitive_dependencies: ['deps/Baz'],
					mtime: new Date("2014-05-13T14:57:32.000Z"),
					requirecalls: []
				},
				{
					module: 'deps/Baz',
					dependencies: [],
					transitive_dependencies: [],
					mtime: new Date("2014-05-14T14:57:32.000Z"),
					requirecalls: []
				}
			];

			try {

				var next = sinon.spy();
				var deps = new DeptimeUpdater();

				deps.on('end', function (modules, cb) {
					modules.forEach(function (module) {
						assert.equal(+new Date(module.mtime), 1400079452000);
					});
					done();
				});

				deps.run(modules, next);

			} catch (e) {
				done(e);
			}
		});

		test('multiple dep tree, one does not affect the other', function (done) {

			var modules = [
				{
					module: 'mod/Foo',
					dependencies: ['mod/Bar'],
					transitive_dependencies: ['deps/Baz', 'mod/Bar'],
					mtime: new Date("2014-05-13T14:57:32.000Z"),
					requirecalls: []
				},
				{
					module: 'mod/Bar',
					dependencies: ['deps/Baz'],
					transitive_dependencies: ['deps/Baz'],
					mtime: new Date("2014-05-14T14:57:32.000Z"),
					requirecalls: []
				},
				{
					module: 'deps/Baz',
					dependencies: [],
					transitive_dependencies: [],
					mtime: new Date("2014-05-1314:57:32.000Z"),
					requirecalls: []
				},
				{
					module: 'mod/Lorem',
					dependencies: ['mod/Ipsum'],
					transitive_dependencies: ['deps/Baz', 'mod/Ipsum'],
					mtime: new Date("2014-05-13T14:57:32.000Z"),
					requirecalls: []
				},
				{
					module: 'mod/Ipsum',
					dependencies: ['deps/Baz'],
					transitive_dependencies: ['deps/Baz'],
					mtime: new Date("2014-05-13T14:57:32.000Z"),
					requirecalls: []
				}
			];

			try {

				var next = sinon.spy();
				var deps = new DeptimeUpdater();

				deps.on('end', function (modules, cb) {
					modules.forEach(function (module) {
						if (module.module == 'mod/Bar' || module.module == 'mod/Foo') {
							assert.equal(+new Date(module.mtime), 1400079452000);
						} else {
							assert.notEqual(+new Date(module.mtime), 1400079452000);
						}
					});
					done();
				});

				deps.run(modules, next);

			} catch (e) {
				done(e);
			}
		});

	});

});<|endoftext|>


<commit_before>/*-
 * #%L
 * Eureka! Clinical User Webapp
 * %%
 * Copyright (C) 2016 Emory University
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */
// get the namespace, or declare it here
window.eureka = (typeof window.eureka == "undefined" || !window.eureka ) ? {} : window.eureka;

// add in the namespace
window.eureka.registration = new function () {
	var self = this;

	self.setup = function (registrationForm, agreementAnchor, agreementModal) {
		$(registrationForm).submit(this.submit);
		$(agreementAnchor).click(function () {
			$(agreementModal).modal('show');
		});
		$.validator.addMethod("passwordCheck",
			function (value, element) {
				return value.length >= 8 && /[0-9]+/.test(value) && /[a-zA-Z]+/.test(value);
			},
			"Please enter at least 8 characters with at least 1 digit."
		);
	};

	self.validator = $("#signupForm").validate({
		errorElement: 'span',
		errorClass: null,
		rules: {
			firstName: "required",
			lastName: "required",
			password: {
				required: true,
				minlength: 8,
				passwordCheck: true
			},
			organization: {
				required: true
			},
			verifyPassword: {
				required: true,
				equalTo: "#password"
			},
			email: {
				required: true,
				email: true
			},
			verifyEmail: {
				required: true,
				email: true,
				equalTo: "#email"
			},
			agreement: {
				required: true
			},
			title: {
				required: true
			},
			department: {
				required: true
			}
		},
		messages: {
			firstName: "Enter your firstname",
			lastName: "Enter your lastname",
			organization: "Enter your organization",
			password: {
				required: "Provide a password",
				rangelength: $.validator.format("Please enter at least {0} characters")
			},
			verifyPassword: {
				required: "Repeat your password",
				minlength: $.validator.format("Please enter at least {0} characters"),
				equalTo: "Enter the same password as above"
			},
			email: {
				required: "Please enter a valid email address",
				minlength: "Please enter a valid email address"
			},
			verifyEmail: {
				required: "Please enter a valid email address",
				minlength: "Please enter a valid email address",
				equalTo: "Enter the same email as above"
			},
			agreement: {
				required: "Please check the agreement checkbox"
			},
			title: "Enter your title",
			department: "Enter your department"
		},
		errorPlacement: function (error, element) {
			$(element).closest('.form-group').find('.help-block').empty();
			error.appendTo($(element).closest('.form-group').find('.help-block'));
		},
		highlight: function (element) {
			$(element).closest('.form-group').addClass('has-error');
			$(element).closest('.form-group').find('.help-block').removeClass('default-hidden');
		},
		unhighlight: function (element) {
			$(element).closest('.form-group').removeClass('has-error');
			$(element).closest('.form-group').find('.help-block').addClass('default-hidden');
		},
		// set this class to error-labels to indicate valid fields
		success: function (label) {
			// set   as text for IE
			label.html(" ").addClass("checked");
		}
	});

	self.submit = function () {
		if (self.validator.valid()) {
			var username = $('#username').val();
			var firstName = $('#firstName').val();
			var lastName = $('#lastName').val();
			var organization = $('#organization').val();
			var password = $('#password').val();
			var verifyPassword = $('#verifyPassword').val();
			var email = $('#email').val();
			var verifyEmail = $('#verifyEmail').val();
			var title = $('#title').val();
			var department = $('#department').val();
			var providerUsername = $('#providerUsername').val();
			var authenticationMethod = $('#authenticationMethod').val();
			var oauthProvider = $('#oauthProvider').val();

			var dataString = 'firstName=' + firstName + '&lastName=' + lastName + '&organization=' + organization +
				'&password=' + password + '&verifyPassword=' + verifyPassword +
				'&email=' + email + '&verifyEmail=' + verifyEmail + '&title=' + title + '&department=' + department +
				(username ? '&username=' + username : '') +
				(providerUsername ? '&providerUsername=' + providerUsername : '') +
				'&authenticationMethod=' + authenticationMethod +
				(oauthProvider ? '&oauthProvider=' + oauthProvider : '');
			$.ajax({
				type: 'POST',
				url: 'register',
				data: dataString,
				success: function () {
					$('#passwordChangeFailure').hide();
					$('#signupForm').hide();
					$('#registerHeading').hide();
					$('#registrationComplete').show();
				},
				error: function (xhr, err) {
					$('#passwordChangeFailure').show();
                                        if (xhr.status == "409") {
                                                $('#passwordErrorMessage').html("Account already exists! You may go ahead and login.");
                                        } else if (xhr.status == "400"){
                                                $('#passwordErrorMessage').html("Please review your profile and complete all required fields.");
                                        } else {
                                                $('#passwordErrorMessage').html("An internal error has occurred. Please contact the technical team for further assistance.");
                                        }

				}
			});
		}
		return false;
	}
};
<commit_msg>Fix bug#1 by directing page to eureka-webapp/protected/login, and redirecting it to eureka home page after successful login<commit_after>/*-
 * #%L
 * Eureka! Clinical User Webapp
 * %%
 * Copyright (C) 2016 Emory University
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */
// get the namespace, or declare it here
window.eureka = (typeof window.eureka == "undefined" || !window.eureka ) ? {} : window.eureka;

// add in the namespace
window.eureka.registration = new function () {
	var self = this;

	self.setup = function (registrationForm, agreementAnchor, agreementModal) {
		$(registrationForm).submit(this.submit);
		$(agreementAnchor).click(function () {
			$(agreementModal).modal('show');
		});
		$.validator.addMethod("passwordCheck",
			function (value, element) {
				return value.length >= 8 && /[0-9]+/.test(value) && /[a-zA-Z]+/.test(value);
			},
			"Please enter at least 8 characters with at least 1 digit."
		);
	};

	self.validator = $("#signupForm").validate({
		errorElement: 'span',
		errorClass: null,
		rules: {
			firstName: "required",
			lastName: "required",
			password: {
				required: true,
				minlength: 8,
				passwordCheck: true
			},
			organization: {
				required: true
			},
			verifyPassword: {
				required: true,
				equalTo: "#password"
			},
			email: {
				required: true,
				email: true
			},
			verifyEmail: {
				required: true,
				email: true,
				equalTo: "#email"
			},
			agreement: {
				required: true
			},
			title: {
				required: true
			},
			department: {
				required: true
			}
		},
		messages: {
			firstName: "Enter your firstname",
			lastName: "Enter your lastname",
			organization: "Enter your organization",
			password: {
				required: "Provide a password",
				rangelength: $.validator.format("Please enter at least {0} characters")
			},
			verifyPassword: {
				required: "Repeat your password",
				minlength: $.validator.format("Please enter at least {0} characters"),
				equalTo: "Enter the same password as above"
			},
			email: {
				required: "Please enter a valid email address",
				minlength: "Please enter a valid email address"
			},
			verifyEmail: {
				required: "Please enter a valid email address",
				minlength: "Please enter a valid email address",
				equalTo: "Enter the same email as above"
			},
			agreement: {
				required: "Please check the agreement checkbox"
			},
			title: "Enter your title",
			department: "Enter your department"
		},
		errorPlacement: function (error, element) {
			$(element).closest('.form-group').find('.help-block').empty();
			error.appendTo($(element).closest('.form-group').find('.help-block'));
		},
		highlight: function (element) {
			$(element).closest('.form-group').addClass('has-error');
			$(element).closest('.form-group').find('.help-block').removeClass('default-hidden');
		},
		unhighlight: function (element) {
			$(element).closest('.form-group').removeClass('has-error');
			$(element).closest('.form-group').find('.help-block').addClass('default-hidden');
		},
		// set this class to error-labels to indicate valid fields
		success: function (label) {
			// set   as text for IE
			label.html(" ").addClass("checked");
		}
	});

	self.submit = function () {
		if (self.validator.valid()) {
			var username = $('#username').val();
			var firstName = $('#firstName').val();
			var lastName = $('#lastName').val();
			var organization = $('#organization').val();
			var password = $('#password').val();
			var verifyPassword = $('#verifyPassword').val();
			var email = $('#email').val();
			var verifyEmail = $('#verifyEmail').val();
			var title = $('#title').val();
			var department = $('#department').val();
			var providerUsername = $('#providerUsername').val();
			var authenticationMethod = $('#authenticationMethod').val();
			var oauthProvider = $('#oauthProvider').val();

			var dataString = 'firstName=' + firstName + '&lastName=' + lastName + '&organization=' + organization +
				'&password=' + password + '&verifyPassword=' + verifyPassword +
				'&email=' + email + '&verifyEmail=' + verifyEmail + '&title=' + title + '&department=' + department +
				(username ? '&username=' + username : '') +
				(providerUsername ? '&providerUsername=' + providerUsername : '') +
				'&authenticationMethod=' + authenticationMethod +
				(oauthProvider ? '&oauthProvider=' + oauthProvider : '');
			$.ajax({
				type: 'POST',
				url: 'register',
				data: dataString,
				success: function () {
					$('#passwordChangeFailure').hide();
					$('#signupForm').hide();
					$('#registerHeading').hide();
					$('#registrationComplete').show();
				},
				error: function (xhr, err) {
					$('#passwordChangeFailure').show();
                                        if (xhr.status == "409") {
                                                $('#passwordErrorMessage').html("Account already exists! You may go ahead and login.");
                                        } else if (xhr.status == "400"){
                                                $('#passwordErrorMessage').html("Please review your profile and complete all required fields.");
                                        } else {
                                                $('#passwordErrorMessage').html("An internal error has occurred. Please contact the technical team for further assistance.");
                                        }

				}
			});
		}
		return false;
	}
};
<|endoftext|>


<commit_before>define(
    ['jquery'],
    function($) {
        var cssFile = "/styles.css";
        var emtpyFunc = function() {};

        var currentBaseUrl = window.location.href.replace(/\/[^\/]+\.html/ig, "");
        var jsonUrl, customCssUrl;
        var allQueryParams;

        function getQueryParams() {
            var vars = {};
            var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,
                function(m,key,value) {
                    vars[key] = decodeURIComponent(value);
                });
            allQueryParams = vars;
        }

        var getUrlVar = function(name) {
            if (!allQueryParams) {
                getQueryParams();
            }
            return allQueryParams[name];
        };

        var setUrlVar = function(name, value) {
            if (!allQueryParams) {
                getQueryParams();
            }
            allQueryParams[name] = value;
            var newUrl = window.location.href.replace(/\?\S*/g, "");
            var first = true;
            for (paramName in allQueryParams) {
                if (allQueryParams[paramName]) {
                    newUrl += first ? "?" : "&";
                    first = false;
                    newUrl += paramName + "=" + encodeURIComponent(allQueryParams[paramName]);
                }
            }
            // write modified querystring without reloading the page
            if (history.pushState) {
                window.history.pushState({path:newUrl},'',newUrl);
            }
        };

        function setUrls(newUrl, allowOverride) {
             jsonUrl = newUrl;
             if (allowOverride && getUrlVar("conference") != undefined) {
                 jsonUrl = jsonUrl.replace(/\d+$/g, getUrlVar("conference"));
                 console.log('detected conference id from url parameter: ' + getUrlVar("conference"))
             }
             customCssUrl = jsonUrl + cssFile;
         }

        // temporarily for retrieving conference id from url parameter for switching between conferences,
        // can be removed when conference switch is implemented in html5 client

        function loadInitData(callback) {
            $.ajax({
                url: currentBaseUrl + '/rest/init.json',
                dataType: 'json',
                success: function (data) {
                    if (data.id != undefined) {
                        setUrls(jsonUrl.replace(/\d+$/g, data.id), false);
                        console.log('detected conference id from init call: ' + data.id)
                    }
                    if (callback) {
                        callback(jsonUrl, customCssUrl);
                    }
                },
                error: function() {
                }
            });
        }

        setUrls("${dukecon.server.jsonUrl}", true);
        loadInitData();

        return {
            getJsonUrl: function(callback) {
                callback = callback || emptyFunc;
                if (!jsonUrl) {
                    loadInitData(function(jsonUrl, unused) {
                        callback(jsonUrl);
                    });
                }
                else {
                    callback(jsonUrl);
                }
            },
            getCustomCssUrl: function(callback) {
                callback = callback || emptyFunc;
                if (!customCssUrl) {
                    loadInitData(function(unused, customCssUrl) {
                        callback(customCssUrl);
                    });
                }
                else {
                    callback(customCssUrl);
                }
            },
            getUrlParam: getUrlVar,
            setUrlParam: setUrlVar
        };
    }
);
<commit_msg>revert accidentely pushed changes<commit_after>define(
    ['jquery'],
    function($) {
        var cssFile = "/styles.css";
        var emtpyFunc = function() {};

        var currentBaseUrl = window.location.href.replace(/\/[^\/]+\.html/ig, "").replace(/\/$/ig, "");
        console.log('Using currentBaseUrl: "' + currentBaseUrl + '"');
        var jsonUrl, customCssUrl;
        var allQueryParams;

        function getQueryParams() {
            var vars = {};
            var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,
                function(m,key,value) {
                    vars[key] = decodeURIComponent(value);
                });
            allQueryParams = vars;
        }

        var getUrlVar = function(name) {
            if (!allQueryParams) {
                getQueryParams();
            }
            return allQueryParams[name];
        };

        var setUrlVar = function(name, value) {
            if (!allQueryParams) {
                getQueryParams();
            }
            allQueryParams[name] = value;
            var newUrl = window.location.href.replace(/\?\S*/g, "");
            var first = true;
            for (paramName in allQueryParams) {
                if (allQueryParams[paramName]) {
                    newUrl += first ? "?" : "&";
                    first = false;
                    newUrl += paramName + "=" + encodeURIComponent(allQueryParams[paramName]);
                }
            }
            // write modified querystring without reloading the page
            if (history.pushState) {
                window.history.pushState({path:newUrl},'',newUrl);
            }
        };

        function setUrls(newUrl, allowOverride) {
             jsonUrl = newUrl;
             if (allowOverride && getUrlVar("conference") != undefined) {
                 jsonUrl = jsonUrl.replace(/\d+$/g, getUrlVar("conference"));
                 console.log('detected conference id from url parameter: ' + getUrlVar("conference"));
             }
             customCssUrl = jsonUrl + cssFile;
         }

        // temporarily for retrieving conference id from url parameter for switching between conferences,
        // can be removed when conference switch is implemented in html5 client

        function loadInitData(callback) {
            $.ajax({
                url: currentBaseUrl + '/rest/init.json',
                dataType: 'json',
                success: function (data) {
                    if (data.id != undefined) {
                        setUrls(jsonUrl.replace(/\d+$/g, data.id), false);
                        console.log('detected conference id from init call: ' + data.id)
                    }
                    if (callback) {
                        callback(jsonUrl, customCssUrl);
                    }
                },
                error: function() {
                }
            });
        }

        setUrls("${dukecon.server.jsonUrl}", true);
        loadInitData();

        return {
            getJsonUrl: function(callback) {
                callback = callback || emptyFunc;
                if (!jsonUrl) {
                    loadInitData(function(jsonUrl, unused) {
                        callback(jsonUrl);
                    });
                }
                else {
                    callback(jsonUrl);
                }
            },
            getCustomCssUrl: function(callback) {
                callback = callback || emptyFunc;
                if (!customCssUrl) {
                    loadInitData(function(unused, customCssUrl) {
                        callback(customCssUrl);
                    });
                }
                else {
                    callback(customCssUrl);
                }
            },
            getUrlParam: getUrlVar,
            setUrlParam: setUrlVar
        };
    }
);
<|endoftext|>


<commit_before>define([
  // Application.
  "app"
],

// Map dependencies from above array.
function(app) {

  // Create a new module.
  var ParkingNonDowntown = app.module();

  ParkingNonDowntown.Views.Calculator = Backbone.View.extend({

      tagName:    "section",
      className:  "content",
      template:   "panels/requirements/city/parking_non_downtown",

    serialize: function() {
      var model;
      var answers = {};

      for (m in this.collection.models) {
        model = this.collection.models[m];
        answers[model.get("name")] = model.get("value");
      }
      return {
        answers: answers
        // formatted fee
      };
    },

    cleanup: function() {
      this.collection.off(null, null, this);
    },

    // Calculates the number of spaces a business must provide.
    // Require the business sub-type and other fields specific to that business.
    calculateSpaces: function (business_subtype) {

      //console.log('calculating spaces for ', business_subtype);

      var spaces;

      switch (business_subtype) {
        case 'parking_auto':
          var square_feet = this.collection.getAnswer("square_feet"),
            spaces = Math.round(square_feet / 400);
          return spaces;
          break;

        case 'parking_service_stations':
          var service_bays = this.collection.getAnswer("service_bays"),
            employees = this.collection.getAnswer("employees"),
            spaces = Math.round(service_bays * 3) + employees;
          return spaces;
          break;

        case 'parking_banks_with_atms':
          var square_feet = this.collection.getAnswer("square_feet"),
            atms = this.collection.getAnswer("ATMs"),
            spaces = Math.round((square_feet / 400) + (atms * 1.5));
          return spaces;
          break;

        case 'parking_banks_no_atms':
          var square_feet = this.collection.getAnswer("square_feet"),
            spaces = Math.round(square_feet / 400);
          return spaces;
          break;

        case 'parking_billiard':
          var tables = this.collection.getAnswer("tables"),
            spaces = Math.round(tables * 1.5);
          return spaces;
          break;

        case 'parking_child_homes':
          var beds = this.collection.getAnswer("beds"),
            employees = this.collection.getAnswer("employees"),
            spaces = Math.round(beds / 5) + employees;
          return spaces;
          break;

        case 'parking_daycare_foster':
          var guests = this.collection.getAnswer("guests"),
            spaces = Math.round(guests / 5) + 1;
          return spaces;
          break;

        case 'parking_communication':
          var square_feet = this.collection.getAnswer("square_feet"),
            // the following line contained a reference to field_1, swapped out for square_feet
            spaces = Math.round(square_feet / 1000);
          return spaces;
          break;

        case 'parking_lower_schools':
          var employees = this.collection.getAnswer("employees"),
            spaces = employees;
          return spaces;
          break;

        case 'parking_high_schools':
          var students = this.collection.getAnswer("students"),
            employees = this.collection.getAnswer("employees"),
            spaces = Math.round(students / 10) + employees;
          return spaces;
          break;

        case 'parking_colleges':
          var students = this.collection.getAnswer("students"),
            employees = this.collection.getAnswer("employees"),
            spaces = Math.round(students / 3) + employees;
          return spaces;
          break;

        case 'parking_multi_program_fitness':
          var square_feet = this.collection.getAnswer("square_feet"),
            spaces = (square_feet / 100),
            spaces = (square_feet > 15000) ? Math.round(spaces * 1.1) : Math.round(spaces);
          return spaces;
          break;

        case 'parking_single_program_fitness':
          var aerobics_area = this.collection.getAnswer("aerobics_area"),
            basketball_volleyball_occupancy = this.collection.getAnswer("basketball_volleyball_occupancy"),
            pool_lanes = this.collection.getAnswer("pool_lanes"),
            pool_non_water_area = this.collection.getAnswer("pool_non_water_area"),
            weights_area = this.collection.getAnswer("weights_area"),
            square_feet = this.collection.getAnswer("square_feet"),
            spaces = (aerobics_area / 50) + (basketball_volleyball_occupancy / 3) + (pool_lanes * 2) + (pool_non_water_area / 300) + (weights_area / 250),
            spaces = (square_feet > 15000) ? Math.round(spaces * 1.1) : Math.round(spaces);
          return spaces;
          break;

        case 'parking_food':
          var square_feet = this.collection.getAnswer("square_feet"),
            spaces = Math.round(square_feet / 120);
          return spaces;
          break;

        case 'parking_take_out':
          var square_feet = this.collection.getAnswer("square_feet"),
            take_out_area = this.collection.getAnswer("take_out_area"),
            spaces = Math.round((square_feet / 120) + (take_out_area / 50));
          return spaces;
          break;

        case 'parking_funeral':
          var seats = this.collection.getAnswer("seats"),
            spaces = Math.round(seats / 5);
          return spaces;
          break;

        case 'parking_furn_repair':
          var square_feet = this.collection.getAnswer("square_feet"),
            spaces = Math.round(square_feet / 500);
          return spaces;
          break;

        case 'parking_halls_with_seats':
          var seats = this.collection.getAnswer("seats"),
            spaces = Math.round(seats / 3.5);
          return spaces;
          break;

        case 'parking_halls_no_seats':
          var max_occupancy_load = this.collection.getAnswer("max_occupancy_load"),
            spaces = Math.round(max_occupancy_load / 3);
          return spaces;
          break;

        case 'parking_household':
          var sales_area = this.collection.getAnswer("sales_area"),
            spaces = Math.round(sales_area / 800);
          return spaces;
          break;

        case 'parking_laundry':
          var square_feet = this.collection.getAnswer("square_feet"),
            spaces = Math.round(square_feet / 200);
          return spaces;
          break;

        case 'parking_community_care':
          var guests = this.collection.getAnswer("guests"),
            employees = this.collection.getAnswer("employees"),
            spaces = Math.round((guests / 5) + 1 + employees);
          return spaces;
          break;

        case 'parking_hotels':
          var hotel_units = this.collection.getAnswer("hotel_units"),
            spaces = hotel_units + 1;
          return spaces;
          break;

        case 'parking_convalescent':
          var beds = this.collection.getAnswer("beds"),
            employees = this.collection.getAnswer("employees"),
            spaces = Math.round((beds / 5) + employees);
          return spaces;
          break;

        case 'parking_hospitals':
          var beds = this.collection.getAnswer("beds"),
            employees = this.collection.getAnswer("employees"),
            spaces = Math.round((beds / 5) + employees);
          return spaces;
          break;

        case 'parking_medical_offices':
          var square_feet = this.collection.getAnswer("square_feet"),
            spaces = Math.round(square_feet / 200);
          return spaces;
          break;

        case 'parking_physical_therapy':
          var square_feet = this.collection.getAnswer("square_feet"),
            pool_water_area = this.collection.getAnswer("pool_water_area"),
            spaces = Math.round((square_feet / 200) + (pool_water_area / 50));
          return spaces;
          break;

        case 'parking_office':
          var square_feet = this.collection.getAnswer("square_feet"),
            spaces = Math.round(square_feet / 300);
          return spaces;
          break;

        case 'parking_plants':
          var square_feet = this.collection.getAnswer("square_feet"),
            spaces = Math.round(square_feet / 500);
          return spaces;
          break;

        case 'parking_research':
          var square_feet = this.collection.getAnswer("square_feet"),
            employees = this.collection.getAnswer("employees"),
            spaces_by_square_footage = Math.round(square_feet / 325),
            spaces_by_employees = Math.round(employees / 2);
          return (spaces_by_square_footage >= spaces_by_employees) ? spaces_by_square_footage : spaces_by_employees;
          break;

        case 'parking_retail':
          var square_feet = this.collection.getAnswer("square_feet"),
            spaces = Math.round(square_feet / 250);
          return spaces;
          break;

        case 'parking_boarding':
          var beds = this.collection.getAnswer("beds"),
            employees = this.collection.getAnswer("employees"),
            spaces = Math.round((beds / 5) + employees);
          return spaces;
          break;

        case 'parking_institutions':
          var guests = this.collection.getAnswer("guests"),
            employees = this.collection.getAnswer("employees"),
            spaces = Math.round((guests / 5) + employees);
          return spaces;
          break;

        case 'parking_nursing':
          var guests = this.collection.getAnswer("guests"),
            employees = this.collection.getAnswer("employees"),
            spaces = Math.round((guests / 5) + employees + 1);
          return spaces;
          break;

        case 'parking_theaters':
          var seats = this.collection.getAnswer("seats");
          if ((seats - 350) > 0) {
            // if 351+ seats
            spaces = Math.round(350 / 3.5) + Math.round((seats - 350) / 5);
          } else {
            // if 0-350 seats
            spaces = Math.round(seats / 3.5);
          }
          return spaces;
          break;

        case 'parking_warehouses':
          var square_feet = this.collection.getAnswer("square_feet"),
            spaces = Math.round(square_feet / 1000);
          return spaces;
          break;

        case 'parking_worship':
          var seats = this.collection.getAnswer("seats"),
            spaces = Math.round(seats / 3.5);
          return spaces;
          break;

        default:
          return "Unable to calculate.";
          break;
      }
    },

    initialize: function(options) {
      this.collection.on("reset", this.render, this);

      _.bindAll(this, 'beforeRender', 'render', 'afterRender');
      var _this = this;
      this.render = _.wrap(this.render, function(render) {
        _this.beforeRender();
        render();
        _this.afterRender();
        return _this;
      });
    },

    beforeRender: function() {
    },

    render: function() {
      return this;
    },

    clearAnswer: function(field_name) {
      this.collection.addAnswer(field_name, null);
    },

    afterRender: function(o) {
      // hide all the forms by default
      $('.business-type-rule').hide();
      $('.business-sub-type-rule').hide();

      var self = this;

      // When the applicant selects a business category
      $('#business_type').change(function() {
        self.clearAnswer('business_type');
        self.clearAnswer('required_parking_spaces');
        $('.business-type-rule').hide();
        selected_option = '#business_type_' + $(this).val() || '';
        $(selected_option).show();
      });

      // When the applicant selects a business sub-category
      $('.business_subtype').change(function() {
        $('.business-sub-type-rule').hide();
        selected_option = "#subtype_" + $(this).val() || '';
        $(selected_option).show();
      });

    },

    events: {
      "change select,input":"saveInput",
    },

    saveInput:function(ev) {
      ev.preventDefault();
      var $elem = $(ev.target);
      this.collection.addAnswer($elem.attr("name"), $elem.val());
      this.calculate();
    },

    calculate:function() {
      var type = 'parking_' + this.collection.getAnswer('business_type');
      var subtype = this.collection.getAnswer('business_subtype');
      var business_subtype = subtype || type;

      var spaces = this.calculateSpaces(business_subtype);

      this.collection.addAnswer('required_parking_spaces', spaces);

      var display_text = "
You must provide "
      + spaces
      + " car parking space"
      + ((spaces !== 1) ? "s" : "")
      + ".
";

      if ( !(isNaN(spaces) || spaces == null) ) {
		$("#parking_spaces")
		.html(display_text)
		.show();
	  }
    }

  });

  // Return the module for AMD compliance.
  return ParkingNonDowntown;
});
<commit_msg>Remove tabs<commit_after>define([
  // Application.
  "app"
],

// Map dependencies from above array.
function(app) {

  // Create a new module.
  var ParkingNonDowntown = app.module();

  ParkingNonDowntown.Views.Calculator = Backbone.View.extend({

      tagName:    "section",
      className:  "content",
      template:   "panels/requirements/city/parking_non_downtown",

    serialize: function() {
      var model;
      var answers = {};

      for (m in this.collection.models) {
        model = this.collection.models[m];
        answers[model.get("name")] = model.get("value");
      }
      return {
        answers: answers
        // formatted fee
      };
    },

    cleanup: function() {
      this.collection.off(null, null, this);
    },

    // Calculates the number of spaces a business must provide.
    // Require the business sub-type and other fields specific to that business.
    calculateSpaces: function (business_subtype) {

      //console.log('calculating spaces for ', business_subtype);

      var spaces;

      switch (business_subtype) {
        case 'parking_auto':
          var square_feet = this.collection.getAnswer("square_feet"),
            spaces = Math.round(square_feet / 400);
          return spaces;
          break;

        case 'parking_service_stations':
          var service_bays = this.collection.getAnswer("service_bays"),
            employees = this.collection.getAnswer("employees"),
            spaces = Math.round(service_bays * 3) + employees;
          return spaces;
          break;

        case 'parking_banks_with_atms':
          var square_feet = this.collection.getAnswer("square_feet"),
            atms = this.collection.getAnswer("ATMs"),
            spaces = Math.round((square_feet / 400) + (atms * 1.5));
          return spaces;
          break;

        case 'parking_banks_no_atms':
          var square_feet = this.collection.getAnswer("square_feet"),
            spaces = Math.round(square_feet / 400);
          return spaces;
          break;

        case 'parking_billiard':
          var tables = this.collection.getAnswer("tables"),
            spaces = Math.round(tables * 1.5);
          return spaces;
          break;

        case 'parking_child_homes':
          var beds = this.collection.getAnswer("beds"),
            employees = this.collection.getAnswer("employees"),
            spaces = Math.round(beds / 5) + employees;
          return spaces;
          break;

        case 'parking_daycare_foster':
          var guests = this.collection.getAnswer("guests"),
            spaces = Math.round(guests / 5) + 1;
          return spaces;
          break;

        case 'parking_communication':
          var square_feet = this.collection.getAnswer("square_feet"),
            // the following line contained a reference to field_1, swapped out for square_feet
            spaces = Math.round(square_feet / 1000);
          return spaces;
          break;

        case 'parking_lower_schools':
          var employees = this.collection.getAnswer("employees"),
            spaces = employees;
          return spaces;
          break;

        case 'parking_high_schools':
          var students = this.collection.getAnswer("students"),
            employees = this.collection.getAnswer("employees"),
            spaces = Math.round(students / 10) + employees;
          return spaces;
          break;

        case 'parking_colleges':
          var students = this.collection.getAnswer("students"),
            employees = this.collection.getAnswer("employees"),
            spaces = Math.round(students / 3) + employees;
          return spaces;
          break;

        case 'parking_multi_program_fitness':
          var square_feet = this.collection.getAnswer("square_feet"),
            spaces = (square_feet / 100),
            spaces = (square_feet > 15000) ? Math.round(spaces * 1.1) : Math.round(spaces);
          return spaces;
          break;

        case 'parking_single_program_fitness':
          var aerobics_area = this.collection.getAnswer("aerobics_area"),
            basketball_volleyball_occupancy = this.collection.getAnswer("basketball_volleyball_occupancy"),
            pool_lanes = this.collection.getAnswer("pool_lanes"),
            pool_non_water_area = this.collection.getAnswer("pool_non_water_area"),
            weights_area = this.collection.getAnswer("weights_area"),
            square_feet = this.collection.getAnswer("square_feet"),
            spaces = (aerobics_area / 50) + (basketball_volleyball_occupancy / 3) + (pool_lanes * 2) + (pool_non_water_area / 300) + (weights_area / 250),
            spaces = (square_feet > 15000) ? Math.round(spaces * 1.1) : Math.round(spaces);
          return spaces;
          break;

        case 'parking_food':
          var square_feet = this.collection.getAnswer("square_feet"),
            spaces = Math.round(square_feet / 120);
          return spaces;
          break;

        case 'parking_take_out':
          var square_feet = this.collection.getAnswer("square_feet"),
            take_out_area = this.collection.getAnswer("take_out_area"),
            spaces = Math.round((square_feet / 120) + (take_out_area / 50));
          return spaces;
          break;

        case 'parking_funeral':
          var seats = this.collection.getAnswer("seats"),
            spaces = Math.round(seats / 5);
          return spaces;
          break;

        case 'parking_furn_repair':
          var square_feet = this.collection.getAnswer("square_feet"),
            spaces = Math.round(square_feet / 500);
          return spaces;
          break;

        case 'parking_halls_with_seats':
          var seats = this.collection.getAnswer("seats"),
            spaces = Math.round(seats / 3.5);
          return spaces;
          break;

        case 'parking_halls_no_seats':
          var max_occupancy_load = this.collection.getAnswer("max_occupancy_load"),
            spaces = Math.round(max_occupancy_load / 3);
          return spaces;
          break;

        case 'parking_household':
          var sales_area = this.collection.getAnswer("sales_area"),
            spaces = Math.round(sales_area / 800);
          return spaces;
          break;

        case 'parking_laundry':
          var square_feet = this.collection.getAnswer("square_feet"),
            spaces = Math.round(square_feet / 200);
          return spaces;
          break;

        case 'parking_community_care':
          var guests = this.collection.getAnswer("guests"),
            employees = this.collection.getAnswer("employees"),
            spaces = Math.round((guests / 5) + 1 + employees);
          return spaces;
          break;

        case 'parking_hotels':
          var hotel_units = this.collection.getAnswer("hotel_units"),
            spaces = hotel_units + 1;
          return spaces;
          break;

        case 'parking_convalescent':
          var beds = this.collection.getAnswer("beds"),
            employees = this.collection.getAnswer("employees"),
            spaces = Math.round((beds / 5) + employees);
          return spaces;
          break;

        case 'parking_hospitals':
          var beds = this.collection.getAnswer("beds"),
            employees = this.collection.getAnswer("employees"),
            spaces = Math.round((beds / 5) + employees);
          return spaces;
          break;

        case 'parking_medical_offices':
          var square_feet = this.collection.getAnswer("square_feet"),
            spaces = Math.round(square_feet / 200);
          return spaces;
          break;

        case 'parking_physical_therapy':
          var square_feet = this.collection.getAnswer("square_feet"),
            pool_water_area = this.collection.getAnswer("pool_water_area"),
            spaces = Math.round((square_feet / 200) + (pool_water_area / 50));
          return spaces;
          break;

        case 'parking_office':
          var square_feet = this.collection.getAnswer("square_feet"),
            spaces = Math.round(square_feet / 300);
          return spaces;
          break;

        case 'parking_plants':
          var square_feet = this.collection.getAnswer("square_feet"),
            spaces = Math.round(square_feet / 500);
          return spaces;
          break;

        case 'parking_research':
          var square_feet = this.collection.getAnswer("square_feet"),
            employees = this.collection.getAnswer("employees"),
            spaces_by_square_footage = Math.round(square_feet / 325),
            spaces_by_employees = Math.round(employees / 2);
          return (spaces_by_square_footage >= spaces_by_employees) ? spaces_by_square_footage : spaces_by_employees;
          break;

        case 'parking_retail':
          var square_feet = this.collection.getAnswer("square_feet"),
            spaces = Math.round(square_feet / 250);
          return spaces;
          break;

        case 'parking_boarding':
          var beds = this.collection.getAnswer("beds"),
            employees = this.collection.getAnswer("employees"),
            spaces = Math.round((beds / 5) + employees);
          return spaces;
          break;

        case 'parking_institutions':
          var guests = this.collection.getAnswer("guests"),
            employees = this.collection.getAnswer("employees"),
            spaces = Math.round((guests / 5) + employees);
          return spaces;
          break;

        case 'parking_nursing':
          var guests = this.collection.getAnswer("guests"),
            employees = this.collection.getAnswer("employees"),
            spaces = Math.round((guests / 5) + employees + 1);
          return spaces;
          break;

        case 'parking_theaters':
          var seats = this.collection.getAnswer("seats");
          if ((seats - 350) > 0) {
            // if 351+ seats
            spaces = Math.round(350 / 3.5) + Math.round((seats - 350) / 5);
          } else {
            // if 0-350 seats
            spaces = Math.round(seats / 3.5);
          }
          return spaces;
          break;

        case 'parking_warehouses':
          var square_feet = this.collection.getAnswer("square_feet"),
            spaces = Math.round(square_feet / 1000);
          return spaces;
          break;

        case 'parking_worship':
          var seats = this.collection.getAnswer("seats"),
            spaces = Math.round(seats / 3.5);
          return spaces;
          break;

        default:
          return "Unable to calculate.";
          break;
      }
    },

    initialize: function(options) {
      this.collection.on("reset", this.render, this);

      _.bindAll(this, 'beforeRender', 'render', 'afterRender');
      var _this = this;
      this.render = _.wrap(this.render, function(render) {
        _this.beforeRender();
        render();
        _this.afterRender();
        return _this;
      });
    },

    beforeRender: function() {
    },

    render: function() {
      return this;
    },

    clearAnswer: function(field_name) {
      this.collection.addAnswer(field_name, null);
    },

    afterRender: function(o) {
      // hide all the forms by default
      $('.business-type-rule').hide();
      $('.business-sub-type-rule').hide();

      var self = this;

      // When the applicant selects a business category
      $('#business_type').change(function() {
        self.clearAnswer('business_type');
        self.clearAnswer('required_parking_spaces');
        $('.business-type-rule').hide();
        selected_option = '#business_type_' + $(this).val() || '';
        $(selected_option).show();
      });

      // When the applicant selects a business sub-category
      $('.business_subtype').change(function() {
        $('.business-sub-type-rule').hide();
        selected_option = "#subtype_" + $(this).val() || '';
        $(selected_option).show();
      });

    },

    events: {
      "change select,input":"saveInput",
    },

    saveInput:function(ev) {
      ev.preventDefault();
      var $elem = $(ev.target);
      this.collection.addAnswer($elem.attr("name"), $elem.val());
      this.calculate();
    },

    calculate:function() {
      var type = 'parking_' + this.collection.getAnswer('business_type');
      var subtype = this.collection.getAnswer('business_subtype');
      var business_subtype = subtype || type;

      var spaces = this.calculateSpaces(business_subtype);

      this.collection.addAnswer('required_parking_spaces', spaces);

      var display_text = "
You must provide "
      + spaces
      + " car parking space"
      + ((spaces !== 1) ? "s" : "")
      + ".
";

      if ( !(isNaN(spaces) || spaces == null) ) {
        $("#parking_spaces")
        .html(display_text)
        .show();
	  }
    }

  });

  // Return the module for AMD compliance.
  return ParkingNonDowntown;
});
<|endoftext|>


<commit_before>import React from 'react';
import ReactDOM from 'react-dom';
import fetchMock from 'fetch-mock/es5/client';
import LoginActivityPage from './LoginActivityPage';
import loginActivityJson from './loginActivityJson.fixture';

function mockFetch(props = {}) {
  fetchMock.restore();

  const {queryStartTimestamp, queryEndTimestamp} = props;
  const url = `/api/login_activity?created_at_or_before=${queryEndTimestamp}&created_after=${queryStartTimestamp}`;
  fetchMock.get(url, loginActivityJson);
}

function testProps(props = {}) {
  return {
    queryStartTimestamp: '1529513716',
    queryEndTimestamp: '1532105716',
    ...props
  };
}

it('renders without crashing', () => {
  const props = testProps();
  mockFetch(props);
  const el = document.createElement('div');
  ReactDOM.render(<LoginActivityPage {...props} />, el);
});

it('renders after fetching', done => {
  const props = testProps();
  mockFetch(props);
  const el = document.createElement('div');
  ReactDOM.render(<LoginActivityPage {...props} />, el);

  setTimeout(() => {
    expect(el.innerHTML).toContain('Login Attempts, Past 30 days');
    expect(el.querySelectorAll('div.tooltip').length).toEqual(47);
    done();
  }, 0);
});
<commit_msg>Add debug log in test<commit_after>import React from 'react';
import ReactDOM from 'react-dom';
import fetchMock from 'fetch-mock/es5/client';
import LoginActivityPage from './LoginActivityPage';
import loginActivityJson from './loginActivityJson.fixture';

function mockFetch(props = {}) {
  fetchMock.restore();

  const {queryStartTimestamp, queryEndTimestamp} = props;
  const url = `/api/login_activity?created_at_or_before=${queryEndTimestamp}&created_after=${queryStartTimestamp}`;
  fetchMock.get(url, loginActivityJson);
}

function testProps(props = {}) {
  return {
    queryStartTimestamp: '1529513716',
    queryEndTimestamp: '1532105716',
    ...props
  };
}

it('renders without crashing', () => {
  const props = testProps();
  mockFetch(props);
  const el = document.createElement('div');
  ReactDOM.render(<LoginActivityPage {...props} />, el);
});

it('renders after fetching', done => {
  const props = testProps();
  mockFetch(props);
  const el = document.createElement('div');
  ReactDOM.render(<LoginActivityPage {...props} />, el);

  setTimeout(() => {
    expect(el.innerHTML).toContain('Login Attempts, Past 30 days');
    expect(el.querySelectorAll('div.tooltip').length).toEqual(47);
    console.log('debug:', el.innerHTML); // eslint-disable-line no-console
    done();
  }, 0);
});
<|endoftext|>