<commit_before>"use strict";

// HTML elements for future use
var stateImgEl = document.getElementById("state-img");
var currentStateEl = document.getElementById("current-state");
var detailsEl = document.getElementById("details");

/**
 * Searches an array of objects for the first object with a specific key value
 * pair and returns its index. If an object can not be found then an error is thrown with the provided
 * text.

 * @param targets {object} Object to search
 * @param targetKey {string} Key to look for
 * @param targetValue {*} Value to look for, could be anything
 * @param errorText {string} Text of error thrown if key cannot be found
 */
function kvSearchOrThrow(targets, targetKey, targetValue, errorText) {
    console.log(targets, targetKey, targetValue, errorText);
    for (var i = 0; i < targets.length; i++) {
        if (targets[i][targetKey] === targetValue) {
            return i;
        }
    }

    throw new Error(errorText);
}

/**
 * An object which holds the configuration for one state
 *
 * @typedef {object} StateConf
 * @property {string} id - State identifier
 * @property {float} weight - Multiplied times probabilities.self, used to create dynamic behavior
 * @property {object} probabilities - Object which holds probabilities that machine will transition
 *                                    from its current state to a new one.
 *                                    Keys = State id, value: probability 0.0 - 1.0
 *
 *                                    All values must add up to 1.0, ignoring the mandatory "self"
 *                                    value which may be from 0.0 - 1.0 and is not included in the
 *                                    grand total.
 *
 *                                    The "self" key is required and represents the probability
 *                                    (from 0.0 - 1.0) that the machine will stay on the current state
 * @property {string} uiColor - Hex color code of color that represents state in
 * the ui
 */

/**
 * List of state configurations
 * @type {StateConf[]}
 */
var states = [
    {
        id: "hungry",
        probabilities: {
            self: 0.8,
            thirsty: 0.35,
            happy: 0.1,
            sad: 0.2,
            tired: 0.35
        },
        uiColor: "#0BE560"
    },
    {
        id: "thirsty",
        probabilities: {
            self: 0.7,
            hungry: 0.4,
            happy: 0.1,
            sad: 0.3,
            tired: 0.2
        },
        uiColor: "#0BB1E5"
    },
    {
        id: "happy",
        probabilities: {
            self: 0.5,
            hungry: 0.3,
            thirsty: 0.2,
            sad: 0.1,
            tired: 0.4
        },
        uiColor: "#23E726"
    },
    {
        id: "sad",
        probabilities: {
            self: 0.3,
            hungry: 0.25,
            thirsty: 0.25,
            happy: 0.1,
            tired: 0.4
        },
        uiColor: "#490BE5"
    },
    {
        id: "tired",
        probabilities: {
            self: 0.5,
            hungry: 0.4,
            thirsty: 0.1,
            happy: 0.1,
            sad: 0.4
        },
        uiColor: "#E50BB3"
    }
];

/**
 * Configuration for a stimulus
 * @typedef {object} StimulusConf
 * @property {string} id - Stimulus identifier
 * @property {string} state - State this stimulus effects
 * @property {string} uiVerb - Verb to describe effect stimulus has on state.
 * Used in the UI.
 * @property {string} conjugatedState - Name of state conjugated to use with uiVerb.
 * @property {float} effect - How much the stimulus effects the state
 */

/**
 * List of stimuli config
 * @type {StimulusConf[]}
 */
var stimuli = [
    {
        id: "food",
        state: "hungry",
        uiVerb: "helps",
        conjugatedState: "hunger",
        effect: -0.2
    },
    {
        id: "drink",
        state: "thirsty",
        uiVerb: "helps",
        conjugatedState: "thirst",
        effect: -0.4
    },
    {
        id: "election-results",
        state: "sad",
        uiVerb: "causes",
        conjugatedState: "sadness",
        effect: -0.7,
    },
    {
        id: "balloons",
        state: "happy",
        uiVerb: "causes",
        conjugatedState: "happyness",
        effect: -0.3
    },
    {
        id: "energy-drink",
        state: "tired",
        uiVerb: "helps",
        conjugatedState: "tiredness",
        effect: -0.35
    }
];

/**
 * Class which represents Virtual Pest's state
 * @param (StateConf[]} statesConf Array of states configuration
 * @param {StimulusConf[]} stimuliConf Array of stimuli configuration
 * @constructor
 */
function State(statesConf, stimuliConf) {
    var self = this;

    if (statesConf === undefined || stimuliConf === undefined) {
        throw new Error("Two arguments expected in State constructor");
    }

    // Interpret config
    self.states = [];
    for (var i = 0; i < statesConf.length; i++) {
        var conf = statesConf[i];

        // State object to be added
        var state = {
            // State Id
            id: conf.id,

            // Color to display in UI
            uiColor: conf.uiColor,

            // All values for probabilities
            probabilities: {

                // Values used to calculate the actual probability values
                parameters: {

                    // Probability that state will stay the same (Change to its *self*)
                     self: {
                         // Probability is calculated with value * modifier
                         value: conf.probabilities.self,
                         modifier: 1.0
                    },

                    // Holds probability values that state will *switch*
                    switch: {}
                },

                // Calculated probability values go here
                ranges: {},

                // Keep track of the `probabilities.parameters.self.modifier` value so we
                // don't have to update if there isn't a change
                _lastRangesCalcModVal: -1
            }
        };

        for (var key in conf.probabilities) {
            if (key === "self") continue;
            state.probabilities.parameters.switch[key] = conf.probabilities[key];
        }

        self.states.push(state);
    }

    self.stimuli = stimuliConf;

    // State
    // These two variables should be kept consistent
    self.currentStateId = "happy";
    self.currentStateI = 2;

    /**
     * Step simulation of state once. This will look at the current
     * state and determine the next state.
     */
    self.step = function() {
        // Calculate probability ranges
        self.calcRanges();

        // Find next state
        var state = self.states[self.currentStateI];

        var random = Math.random();

        var lastValue = 0;// Used as lower bound
        var nextStateId = "";
        for (var key in state.probabilities.ranges) {
            var value = state.probabilities.ranges[key];// Used as upper bound

            // If value is within range
            if (random > lastValue && random <= value) {
                // Save key and exit loop
                nextStateId = key;
                break;
            }

            lastValue = value;
        }

        // Set next state
        if (nextStateId !== "self") {// If next state is "self" than don't change a thing
            self.currentStateId = nextStateId;
            var nextStateI = -1;

            var i = 0;
            for (var key in self.states) {
                if (key === nextStateId) {
                    self.currentStateI = i;
                }

                i++;
            }

            self._mapDOM();
        }
    };

    /**
     * Calculates a set of ranges that are used to determine the
     * probability of the state changing to another state or staying
     * the same.

     * Note: The term "self" is used to describe the next state
     * being the same as the current state (Because the next state turns into
     * its "self").
     *
     * This function looks at the current state object, more
     * particularly the values in `probabilities.parameters`. It uses those
     * values to compute the values for `probabilities.ranges`.
     *
     * Explanation of values:
     * - `probabilities` - Values related to state changes
     *     - `parameters` - Values that tune the generation process
     *     for the values in `ranges`
     *         - `self` - Values related to the next state being
     *         the same as the current
     *             - `modifier` - Value that program tweaks to make `self`
     *             range change on user input
     *             - `value` - Probability (0.0 - 1.0) that next state will
     *             be "self"
     *         - `switch` - Values related to the next state being
     *         different from the current state
     *             - This is a object which contains a key for every other mood
     *             (ex., "happy" or "sad" if state is "hungry")
     *             - The values of these keys is the same as the `self.value`
     *             value. It is the probability (0.0 - 1.0) that the next state
     *             will be the state identified in the key
     *     - `ranges` - An object which holds a series of values, 0.0 from
     *     1.0,
     */
    self.calcRanges = function(id) {
        // Convenience vars
        var state = self.states[self.currentStateI];
        var parameters = state.probabilities.parameters;

        // Make sure we haven't already calculated the values
        if (state.probabilities._lastRangesCalcModVal !== parameters.self.modifier) {
            // Calculate self value
            var selfValue = parameters.self.value * parameters.self.modifier;

            // Calculate switch values
            var switchSpace = 1 - selfValue;// Space available for range after big switch value
            var switchValues = {};

            for (var key in parameters.switch) {
                switchValues[key] = parameters.switch[key] * switchSpace;
            }

            // Assign values
            var runningRange = 0;
            for (var key in switchValues) {
                runningRange += switchValues[key];
                state.probabilities.ranges[key] = runningRange;
            }

            state.probabilities.ranges["self"] = 1.0;

            // Mark that we have calculated the values for this case
            state.probabilities._lastRangesCalcModVal = parameters.self.modifier;

            // Store most recent version of state
            self.states[self.currentStateI] = state;
        }
    };

    /**
     * Maps values for current state onto DOM
     */
    self._mapDOM = function() {
        // State image
        stateImgEl.src = "img/states/" + self.currentStateId + "/"  + self.currentStateId + ".png";

        // Current state label
        currentStateEl.innerText = prettifyString(self.currentStateId);

        // Details
        var html = "";

        // States UI Color key (As in map key)
        html += "
";
        html += "
Key
";

        for (var i = 0; i < self.states.length; i++) {
            var state = self.states[i];
            var color = state.uiColor;
            var name = prettifyString(state.id);

            html += "
";

            html += "

";
            html += "
" + name + "
";

            html += "
";
        }

        html += "
";

        for (var i = 0; i < self.states.length; i++) {
            var state = self.states[i];

            html += "
";

            html += "
" + prettifyString(state.id) + "
";

            html += "
";
            for (var key in state.probabilities.ranges) {
                var widthValue = state.probabilities.ranges[key] * 100;
                //html += "<div style=\"width: " + widthValue + "%\""
            }
            html += "
";

            html += "
";
        }

        detailsEl.innerHTML = html;
    };

    /**
     * Apply the effects of the given stimulus to the state
     * @param id Stimulus id
     */
    self.applyStimulus = function(id) {
        console.log("applied", id);

        // Find stimulus config that we clicked on
        console.log("applied - 1", id);
        var stimulus = kvSearchOrThrow(self.stimuli, "id", id, "Cannot find stimulus with id: \"" + id + "\"");

        // Find state stimulus refers to
        console.log("applied - 2", id);
        var state = kvSearchOrThrow(self.states, "id", stimulus.state, "Cannot find state specified in stimulus with id: \"" + id + "\"");

        /* Apply state effect
        The State self probability is multiplied by the modifier

        Adding the effect to the modifier will then output the result of the
        state self probability
        */
        state.probabilities.parameters.self.modifier += stimulus.effect;

    };

    // Map first state
    self._mapDOM();
}

function prettifyString(text) {
    text = text.replace("-", " ");

    var parts = text.split(" ");
    for (var i = 0; i < parts.length; i++) {
        var part = parts[i];
        parts[i] = part[0].toUpperCase() + part.slice(1);
    }

    return parts.join(" ");
}

// Create state instance
var state = new State(states, stimuli);

var interval = setInterval(function() {
    state.step();
}, 1000);

// Generate HTML for stimuli menu
var html = "";
for (var i = 0; i < stimuli.length; i++) {
    var stimulus = stimuli[i];

    html += "
";

    var stimulusImgUrl = "img/stimuli/" + stimulus.id + "/" + stimulus.id + ".png";
    html += "";

    html += "
";
    html += prettifyString(stimulus.id);
    html += "
";

    html += "
";

    html += "
";
    html += prettifyString(stimulus.uiVerb);
    html += "
";

    html += " " + prettifyString(stimulus.conjugatedState) + " (" + (-1 * stimulus.effect) + ")";

    html += "
";

    html += "
";
}

document.getElementById("stimuli-content").innerHTML = html;

// Click listener for stimuli
function onStimulusElClick(self) {
    var id = self.getAttribute("data-stimulus-id");

    console.log("clicked", id);

    state.applyStimulus(id);
}
<commit_msg>Fixed applyStimulus error<commit_after>"use strict";

// HTML elements for future use
var stateImgEl = document.getElementById("state-img");
var currentStateEl = document.getElementById("current-state");
var detailsEl = document.getElementById("details");

/**
 * Searches an array of objects for the first object with a specific key value
 * pair and returns its index. If an object can not be found then an error is thrown with the provided
 * text.

 * @param targets {object} Object to search
 * @param targetKey {string} Key to look for
 * @param targetValue {*} Value to look for, could be anything
 * @param errorText {string} Text of error thrown if key cannot be found
 */
function kvSearchOrThrow(targets, targetKey, targetValue, errorText) {
    for (var i = 0; i < targets.length; i++) {
        if (targets[i][targetKey] === targetValue) {
            return i;
        }
    }

    throw new Error(errorText);
}

/**
 * An object which holds the configuration for one state
 *
 * @typedef {object} StateConf
 * @property {string} id - State identifier
 * @property {float} weight - Multiplied times probabilities.self, used to create dynamic behavior
 * @property {object} probabilities - Object which holds probabilities that machine will transition
 *                                    from its current state to a new one.
 *                                    Keys = State id, value: probability 0.0 - 1.0
 *
 *                                    All values must add up to 1.0, ignoring the mandatory "self"
 *                                    value which may be from 0.0 - 1.0 and is not included in the
 *                                    grand total.
 *
 *                                    The "self" key is required and represents the probability
 *                                    (from 0.0 - 1.0) that the machine will stay on the current state
 * @property {string} uiColor - Hex color code of color that represents state in
 * the ui
 */

/**
 * List of state configurations
 * @type {StateConf[]}
 */
var states = [
    {
        id: "hungry",
        probabilities: {
            self: 0.8,
            thirsty: 0.35,
            happy: 0.1,
            sad: 0.2,
            tired: 0.35
        },
        uiColor: "#0BE560"
    },
    {
        id: "thirsty",
        probabilities: {
            self: 0.7,
            hungry: 0.4,
            happy: 0.1,
            sad: 0.3,
            tired: 0.2
        },
        uiColor: "#0BB1E5"
    },
    {
        id: "happy",
        probabilities: {
            self: 0.5,
            hungry: 0.3,
            thirsty: 0.2,
            sad: 0.1,
            tired: 0.4
        },
        uiColor: "#23E726"
    },
    {
        id: "sad",
        probabilities: {
            self: 0.3,
            hungry: 0.25,
            thirsty: 0.25,
            happy: 0.1,
            tired: 0.4
        },
        uiColor: "#490BE5"
    },
    {
        id: "tired",
        probabilities: {
            self: 0.5,
            hungry: 0.4,
            thirsty: 0.1,
            happy: 0.1,
            sad: 0.4
        },
        uiColor: "#E50BB3"
    }
];

/**
 * Configuration for a stimulus
 * @typedef {object} StimulusConf
 * @property {string} id - Stimulus identifier
 * @property {string} state - State this stimulus effects
 * @property {string} uiVerb - Verb to describe effect stimulus has on state.
 * Used in the UI.
 * @property {string} conjugatedState - Name of state conjugated to use with uiVerb.
 * @property {float} effect - How much the stimulus effects the state
 */

/**
 * List of stimuli config
 * @type {StimulusConf[]}
 */
var stimuli = [
    {
        id: "food",
        state: "hungry",
        uiVerb: "helps",
        conjugatedState: "hunger",
        effect: -0.2
    },
    {
        id: "drink",
        state: "thirsty",
        uiVerb: "helps",
        conjugatedState: "thirst",
        effect: -0.4
    },
    {
        id: "election-results",
        state: "sad",
        uiVerb: "causes",
        conjugatedState: "sadness",
        effect: -0.7,
    },
    {
        id: "balloons",
        state: "happy",
        uiVerb: "causes",
        conjugatedState: "happyness",
        effect: -0.3
    },
    {
        id: "energy-drink",
        state: "tired",
        uiVerb: "helps",
        conjugatedState: "tiredness",
        effect: -0.35
    }
];

/**
 * Class which represents Virtual Pest's state
 * @param (StateConf[]} statesConf Array of states configuration
 * @param {StimulusConf[]} stimuliConf Array of stimuli configuration
 * @constructor
 */
function State(statesConf, stimuliConf) {
    var self = this;

    if (statesConf === undefined || stimuliConf === undefined) {
        throw new Error("Two arguments expected in State constructor");
    }

    // Interpret config
    self.states = [];
    for (var i = 0; i < statesConf.length; i++) {
        var conf = statesConf[i];

        // State object to be added
        var state = {
            // State Id
            id: conf.id,

            // Color to display in UI
            uiColor: conf.uiColor,

            // All values for probabilities
            probabilities: {

                // Values used to calculate the actual probability values
                parameters: {

                    // Probability that state will stay the same (Change to its *self*)
                     self: {
                         // Probability is calculated with value * modifier
                         value: conf.probabilities.self,
                         modifier: 1.0
                    },

                    // Holds probability values that state will *switch*
                    switch: {}
                },

                // Calculated probability values go here
                ranges: {},

                // Keep track of the `probabilities.parameters.self.modifier` value so we
                // don't have to update if there isn't a change
                _lastRangesCalcModVal: -1
            }
        };

        for (var key in conf.probabilities) {
            if (key === "self") continue;
            state.probabilities.parameters.switch[key] = conf.probabilities[key];
        }

        self.states.push(state);
    }

    self.stimuli = stimuliConf;

    // State
    // These two variables should be kept consistent
    self.currentStateId = "happy";
    self.currentStateI = 2;

    /**
     * Step simulation of state once. This will look at the current
     * state and determine the next state.
     */
    self.step = function() {
        // Calculate probability ranges
        self.calcRanges();

        // Find next state
        var state = self.states[self.currentStateI];

        var random = Math.random();

        var lastValue = 0;// Used as lower bound
        var nextStateId = "";
        for (var key in state.probabilities.ranges) {
            var value = state.probabilities.ranges[key];// Used as upper bound

            // If value is within range
            if (random > lastValue && random <= value) {
                // Save key and exit loop
                nextStateId = key;
                break;
            }

            lastValue = value;
        }

        // Set next state
        if (nextStateId !== "self") {// If next state is "self" than don't change a thing
            self.currentStateId = nextStateId;
            var nextStateI = -1;

            var i = 0;
            for (var key in self.states) {
                if (key === nextStateId) {
                    self.currentStateI = i;
                }

                i++;
            }

            self._mapDOM();
        }
    };

    /**
     * Calculates a set of ranges that are used to determine the
     * probability of the state changing to another state or staying
     * the same.

     * Note: The term "self" is used to describe the next state
     * being the same as the current state (Because the next state turns into
     * its "self").
     *
     * This function looks at the current state object, more
     * particularly the values in `probabilities.parameters`. It uses those
     * values to compute the values for `probabilities.ranges`.
     *
     * Explanation of values:
     * - `probabilities` - Values related to state changes
     *     - `parameters` - Values that tune the generation process
     *     for the values in `ranges`
     *         - `self` - Values related to the next state being
     *         the same as the current
     *             - `modifier` - Value that program tweaks to make `self`
     *             range change on user input
     *             - `value` - Probability (0.0 - 1.0) that next state will
     *             be "self"
     *         - `switch` - Values related to the next state being
     *         different from the current state
     *             - This is a object which contains a key for every other mood
     *             (ex., "happy" or "sad" if state is "hungry")
     *             - The values of these keys is the same as the `self.value`
     *             value. It is the probability (0.0 - 1.0) that the next state
     *             will be the state identified in the key
     *     - `ranges` - An object which holds a series of values, 0.0 from
     *     1.0,
     */
    self.calcRanges = function(id) {
        // Convenience vars
        var state = self.states[self.currentStateI];
        var parameters = state.probabilities.parameters;

        // Make sure we haven't already calculated the values
        if (state.probabilities._lastRangesCalcModVal !== parameters.self.modifier) {
            // Calculate self value
            var selfValue = parameters.self.value * parameters.self.modifier;

            // Calculate switch values
            var switchSpace = 1 - selfValue;// Space available for range after big switch value
            var switchValues = {};

            for (var key in parameters.switch) {
                switchValues[key] = parameters.switch[key] * switchSpace;
            }

            // Assign values
            var runningRange = 0;
            for (var key in switchValues) {
                runningRange += switchValues[key];
                state.probabilities.ranges[key] = runningRange;
            }

            state.probabilities.ranges["self"] = 1.0;

            // Mark that we have calculated the values for this case
            state.probabilities._lastRangesCalcModVal = parameters.self.modifier;

            // Store most recent version of state
            self.states[self.currentStateI] = state;
        }
    };

    /**
     * Maps values for current state onto DOM
     */
    self._mapDOM = function() {
        // State image
        stateImgEl.src = "img/states/" + self.currentStateId + "/"  + self.currentStateId + ".png";

        // Current state label
        currentStateEl.innerText = prettifyString(self.currentStateId);

        // Details
        var html = "";

        // States UI Color key (As in map key)
        html += "
";
        html += "
Key
";

        for (var i = 0; i < self.states.length; i++) {
            var state = self.states[i];
            var color = state.uiColor;
            var name = prettifyString(state.id);

            html += "
";

            html += "

";
            html += "
" + name + "
";

            html += "
";
        }

        html += "
";

        for (var i = 0; i < self.states.length; i++) {
            var state = self.states[i];

            html += "
";

            html += "
" + prettifyString(state.id) + "
";

            html += "
";
            console.log(state.probabilities.ranges);
            for (var key in state.probabilities.ranges) {
                var widthValue = state.probabilities.ranges[key] * 100;
                html += "

";
            }
            html += "
";

            html += "
";
        }

        detailsEl.innerHTML = html;
    };

    /**
     * Apply the effects of the given stimulus to the state
     * @param id Stimulus id
     */
    self.applyStimulus = function(id) {
        // Find stimulus config that we clicked on
        var stimulusI = kvSearchOrThrow(self.stimuli, "id", id, "Cannot find stimulus with id: \"" + id + "\"");
        var stimulus = self.stimuli[stimulusI];

        // Find state stimulus refers to
        var stateI = kvSearchOrThrow(self.states, "id", stimulus.state, "Cannot find state specified in stimulus with id: \"" + id + "\"");
        var state = self.states[stateI];

        /* Apply state effect
        The State self probability is multiplied by the modifier

        Adding the effect to the modifier will then output the result of the
        state self probability
        */
        state.probabilities.parameters.self.modifier += stimulus.effect;

    };

    // Map first state
    self._mapDOM();
}

function prettifyString(text) {
    text = text.replace("-", " ");

    var parts = text.split(" ");
    for (var i = 0; i < parts.length; i++) {
        var part = parts[i];
        parts[i] = part[0].toUpperCase() + part.slice(1);
    }

    return parts.join(" ");
}

// Create state instance
var state = new State(states, stimuli);

var interval = setInterval(function() {
    state.step();
}, 1000);

// Generate HTML for stimuli menu
var html = "";
for (var i = 0; i < stimuli.length; i++) {
    var stimulus = stimuli[i];

    html += "
";

    var stimulusImgUrl = "img/stimuli/" + stimulus.id + "/" + stimulus.id + ".png";
    html += "";

    html += "
";
    html += prettifyString(stimulus.id);
    html += "
";

    html += "
";

    html += "
";
    html += prettifyString(stimulus.uiVerb);
    html += "
";

    html += " " + prettifyString(stimulus.conjugatedState) + " (" + (-1 * stimulus.effect) + ")";

    html += "
";

    html += "
";
}

document.getElementById("stimuli-content").innerHTML = html;

// Click listener for stimuli
function onStimulusElClick(self) {
    var id = self.getAttribute("data-stimulus-id");

    state.applyStimulus(id);
}
<|endoftext|>


<commit_before>/* global define */

(function (root, factory) {
  /* istanbul ignore next */
  if (typeof define === 'function' && define.amd) {
    define([], factory)
  } else if (typeof exports === 'object') {
    module.exports = factory()
  } else {
    root.freeStyle = factory()
  }
})(this, function () {
  /**
   * Unit-less CSS properties.
   *
   * @type {Object}
   */
  var CSS_NUMBER = {
    'column-count': true,
    'fill-opacity': true,
    'flex': true,
    'flex-grow': true,
    'flex-shrink': true,
    'font-weight': true,
    'line-clamp': true,
    'line-height': true,
    'opacity': true,
    'order': true,
    'orphans': true,
    'stroke-opacity': true,
    'widows': true,
    'z-index': true,
    'zoom': true
  }

  /**
   * Hyphenate the CSS property.
   *
   * @param  {String} str
   * @return {String}
   */
  function hyphenate (str) {
    return str
      .replace(/([A-Z])/g, '-$1')
      .replace(/^ms-/, '-ms-')
      .toLowerCase()
  }

  /**
   * Check if a property will render at the top level.
   *
   * @param  {String}  property
   * @return {Boolean}
   */
  function isTopLevelProperty (property) {
    return property.charAt(0) === '@'
  }

  /**
   * Check if a value is a nested style definition.
   *
   * @param  {*}       value
   * @return {Boolean}
   */
  function isNestedDefinition (value) {
    return value != null && typeof value === 'object' && !Array.isArray(value)
  }

  /**
   * Normalize a CSS property.
   *
   * @param  {String} str
   * @return {String}
   */
  function normalizeProperty (str) {
    return hyphenate(str.trim())
  }

  /**
   * Normalize a CSS value string.
   *
   * @param  {String} value
   * @param  {String} property
   * @return {String}
   */
  function normalizeValueString (value, property) {
    if (value == null) {
      return null
    }

    value = String(value)

    if (!isNaN(value) && !CSS_NUMBER[property]) {
      value += 'px'
    }

    return value.replace(/([\{\}\[\]])/g, '\\$1')
  }

  /**
   * Normalize a CSS value.
   *
   * @param  {(String|Array)} value
   * @param  {String}         property
   * @return {(String|Array)}
   */
  function normalizeValue (value, property) {
    if (Array.isArray(value)) {
      return value.map(function (str) {
        return normalizeValueString(str, property)
      })
    }

    return normalizeValueString(value, property)
  }

  /**
   * Copy styles from one object to another.
   *
   * @param  {Object} dest
   * @param  {Object} src
   * @return {Object}
   */
  function copyStyles (dest, src) {
    Object.keys(src).forEach(function (key) {
      var prop = normalizeProperty(key)
      var value = src[key]

      if (isNestedDefinition(value)) {
        dest[prop] = normalizeStyles(dest[prop] || {}, value)

        return
      }

      if (value != null) {
        dest[prop] = normalizeValue(value, prop)
      }
    })

    return dest
  }

  /**
   * Sort an object keys.
   *
   * @param  {Object} obj
   * @return {Object}
   */
  function sortKeys (obj) {
    var sorted = {}

    Object.keys(obj).sort().forEach(function (key) {
      sorted[key] = obj[key]
    })

    return sorted
  }

  /**
   * Normalize one or more objects.
   *
   * @param  {Object} ...src
   * @return {Object}
   */
  function normalizeStyles (/* ...src */) {
    var dest = {}

    for (var i = 0; i < arguments.length; i++) {
      copyStyles(dest, arguments[i])
    }

    return sortKeys(dest)
  }

  /**
   * Turn a single style into a string.
   *
   * @param  {String} property
   * @param  {String} value
   * @return {String}
   */
  function styleStringToString (property, value) {
    return value == null ? '' : property + ':' + value + ';'
  }

  /**
   * Turn a style declaration into a rule.
   *
   * @param  {String} property
   * @param  {String} value
   * @return {String}
   */
  function styleToString (property, value) {
    if (Array.isArray(value)) {
      return value.map(function (value) {
        return styleStringToString(property, value)
      }).join('')
    }

    return styleStringToString(property, value)
  }

  /**
   * Turn a style object into a string.
   *
   * @param  {Object} styles
   * @param  {String} selector
   * @return {String}
   */
  function stylesToString (styles, selector) {
    var rules = ''
    var toplevel = ''

    Object.keys(styles).forEach(function (key) {
      var value = styles[key]

      // Support CSS @-rules (`@media`, `@supports`, etc)
      if (isTopLevelProperty(key)) {
        toplevel += key + '{' + stylesToString(value, selector) + '}'

        return
      }

      // Support LESS-style nested syntax.
      if (isNestedDefinition(value)) {
        if (key.indexOf('&') > -1) {
          key = key.replace(/&/g, selector)
        } else {
          key = selector + ' ' + key
        }

        toplevel += stylesToString(value, key)

        return
      }

      rules += styleToString(key, value)
    })

    if (rules) {
      rules = selector + '{' + rules + '}'
    }

    return rules + toplevel
  }

  /**
   * Create a style object at the root.
   *
   * @param  {Object} styles
   * @return {String}
   */
  function nestedStylesToString (styles, identifier) {
    var rules = ''
    var toplevel = ''

    Object.keys(styles).forEach(function (key) {
      var value = styles[key]

      // Support CSS @-rules inside keyframes (`@supports`)
      if (isTopLevelProperty(key)) {
        toplevel += key + '{' + nestedStylesToString(value, identifier) + '}'

        return
      }

      if (isNestedDefinition(value)) {
        rules += nestedStylesToString(value, key)

        return
      }

      rules += styleToString(key, value)
    })

    if (rules) {
      rules = identifier + '{' + rules + '}'
    }

    return rules + toplevel
  }

  /**
   * Hash a string for use as the class name.
   *
   * @param  {String} str
   * @param  {String} [seed]
   * @return {String}
   */
  function hash (str, seed) {
    var value = seed || 0x811c9dc5

    for (var i = 0; i < str.length; i++) {
      value ^= str.charCodeAt(i)
      value += (value << 1) + (value << 4) + (value << 7) + (value << 8) + (value << 24)
    }

    return (value >>> 0).toString(16)
  }

  /**
   * Hash a style object.
   *
   * @param  {Object} style
   * @return {String}
   */
  function hashStyle (style) {
    return hash(JSON.stringify(style))
  }

  /**
   * Create a namespaced CSS instance.
   *
   * @param {Object} style
   */
  function Namespace (style) {
    this.style = style
    this.className = 'n' + hashStyle(this.style)
    this.selector = '.' + this.className
  }

  /**
   * Get the unique hash.
   *
   * @return {String}
   */
  Namespace.prototype.getHash = function () {
    return this.className
  }

  /**
   * Return styles as a string.
   *
   * @return {String}
   */
  Namespace.prototype.getStyles = function () {
    return stylesToString(this.style, this.selector)
  }

  /**
   * Create keyframes object.
   *
   * @param {Object} style
   */
  function Keyframes (style) {
    this.style = style
    this.name = 'k' + hashStyle(this.style)
  }

  /**
   * Get the unique hash.
   *
   * @return {String}
   */
  Keyframes.prototype.getHash = function () {
    return this.name
  }

  /**
   * Return keyframes style string.
   *
   * @return {String}
   */
  Keyframes.prototype.getStyles = function () {
    return [
      nestedStylesToString(this.style, '@-webkit-keyframes ' + this.name),
      nestedStylesToString(this.style, '@keyframes ' + this.name)
    ].join('')
  }

  /**
   * Create a new stylesheet object.
   */
  function StyleSheet () {
    this.styles = ''
  }

  /**
   * Set the styles string.
   *
   * @param {String} styles
   */
  StyleSheet.prototype.setStyles = function (styles) {
    if (this.node) {
      this.node.innerHTML = styles
    }

    this.styles = styles
  }

  /**
   * Attach the stylesheet to the DOM.
   *
   * @param  {Element}    target
   * @return {StyleSheet}
   */
  StyleSheet.prototype.attach = function (target) {
    var node = document.createElement('style')
    node.innerHTML = this.styles
    target.appendChild(node)

    this.node = node

    return this
  }

  /**
   * Detach the stylesheet from the DOM.
   *
   * @return {StyleSheet}
   */
  StyleSheet.prototype.detach = function () {
    if (this.node) {
      if (this.node.parentNode) {
        this.node.parentNode.removeChild(this.node)
      }

      this.node = undefined
    }

    return this
  }

  /**
   * Global style constructor.
   */
  function FreeStyle () {
    this.cache = {}
  }

  /**
   * Create a fresh instance.
   *
   * @return {FreeStyle}
   */
  FreeStyle.prototype.fresh = function () {
    return new FreeStyle()
  }

  /**
   * Add an object to the style cache.
   *
   * @param {Object} o
   */
  FreeStyle.prototype.add = function (o) {
    this.cache[o.getHash()] = o

    return o
  }

  /**
   * Check if the style exists in the cache.
   *
   * @param  {Object}  o
   * @return {Boolean}
   */
  FreeStyle.prototype.has = function (o) {
    return !!this.cache[o.getHash()]
  }

  /**
   * Remove item from the cache.
   *
   * @param {Object} o
   */
  FreeStyle.prototype.remove = function (o) {
    delete this.cache[o.getHash()]
  }

  /**
   * Clear the cache.
   */
  FreeStyle.prototype.empty = function () {
    this.cache = {}
  }

  /**
   * Create a new style class.
   *
   * @param  {Object}    ...style
   * @return {Namespace}
   */
  FreeStyle.prototype.createClass = function (/* ...style */) {
    return new Namespace(normalizeStyles.apply(null, arguments))
  }

  /**
   * Create and register a new style class.
   *
   * @param  {Object}    ...style
   * @return {Namespace}
   */
  FreeStyle.prototype.registerClass = function (/* ...style */) {
    return this.add(this.createClass.apply(this, arguments))
  }

  /**
   * Create a keyframes object.
   *
   * @param  {Object}    ...style
   * @return {Keyframes}
   */
  FreeStyle.prototype.createKeyframes = function (/* ...style */) {
    return new Keyframes(normalizeStyles.apply(null, arguments))
  }

  /**
   * Create and register a keyframes object.
   *
   * @param  {Object}    ...style
   * @return {Keyframes}
   */
  FreeStyle.prototype.registerKeyframes = function (/* ...style */) {
    return this.add(this.createKeyframes.apply(this, arguments))
  }

  /**
   * Create a valid CSS url string.
   *
   * @param  {String} url
   * @return {String}
   */
  FreeStyle.prototype.url = function (url) {
    return 'url("' + encodeURI(url) + '")'
  }

  /**
   * Join a list of class names together.
   *
   * @param  {String} ...class
   * @return {String}
   */
  FreeStyle.prototype.join = function (/* ...class */) {
    var classNames = []

    for (var i = 0; i < arguments.length; i++) {
      var value = arguments[i]

      if (typeof value === 'string') {
        classNames.push(value)
      } else if (value != null) {
        Object.keys(value).forEach(function (key) {
          if (value[key]) {
            classNames.push(key)
          }
        })
      }
    }

    return classNames.join(' ')
  }

  /**
   * Create a CSS string from styles.
   *
   * @return {String}
   */
  FreeStyle.prototype.getStyles = function () {
    var cache = this.cache

    return Object.keys(cache).map(function (key) {
      return cache[key].getStyles()
    }).join('')
  }

  /**
   * Return a stylesheet interface for browsers.
   *
   * @return {Stylesheet}
   */
  FreeStyle.prototype.createStyleSheet = function () {
    var styleSheet = new StyleSheet()

    styleSheet.setStyles(this.getStyles())

    return styleSheet
  }

  /**
   * Inject the styles into the DOM.
   *
   * @param {Element} [target]
   */
  FreeStyle.prototype.inject = function (target) {
    return this.createStyleSheet().attach(target)
  }

  /**
   * Export a `FreeStyle` instance.
   */
  return new FreeStyle()
})
<commit_msg>provide default attach target<commit_after>/* global define */

(function (root, factory) {
  /* istanbul ignore next */
  if (typeof define === 'function' && define.amd) {
    define([], factory)
  } else if (typeof exports === 'object') {
    module.exports = factory()
  } else {
    root.freeStyle = factory()
  }
})(this, function () {
  /**
   * Unit-less CSS properties.
   *
   * @type {Object}
   */
  var CSS_NUMBER = {
    'column-count': true,
    'fill-opacity': true,
    'flex': true,
    'flex-grow': true,
    'flex-shrink': true,
    'font-weight': true,
    'line-clamp': true,
    'line-height': true,
    'opacity': true,
    'order': true,
    'orphans': true,
    'stroke-opacity': true,
    'widows': true,
    'z-index': true,
    'zoom': true
  }

  /**
   * Hyphenate the CSS property.
   *
   * @param  {String} str
   * @return {String}
   */
  function hyphenate (str) {
    return str
      .replace(/([A-Z])/g, '-$1')
      .replace(/^ms-/, '-ms-')
      .toLowerCase()
  }

  /**
   * Check if a property will render at the top level.
   *
   * @param  {String}  property
   * @return {Boolean}
   */
  function isTopLevelProperty (property) {
    return property.charAt(0) === '@'
  }

  /**
   * Check if a value is a nested style definition.
   *
   * @param  {*}       value
   * @return {Boolean}
   */
  function isNestedDefinition (value) {
    return value != null && typeof value === 'object' && !Array.isArray(value)
  }

  /**
   * Normalize a CSS property.
   *
   * @param  {String} str
   * @return {String}
   */
  function normalizeProperty (str) {
    return hyphenate(str.trim())
  }

  /**
   * Normalize a CSS value string.
   *
   * @param  {String} value
   * @param  {String} property
   * @return {String}
   */
  function normalizeValueString (value, property) {
    if (value == null) {
      return null
    }

    value = String(value)

    if (!isNaN(value) && !CSS_NUMBER[property]) {
      value += 'px'
    }

    return value.replace(/([\{\}\[\]])/g, '\\$1')
  }

  /**
   * Normalize a CSS value.
   *
   * @param  {(String|Array)} value
   * @param  {String}         property
   * @return {(String|Array)}
   */
  function normalizeValue (value, property) {
    if (Array.isArray(value)) {
      return value.map(function (str) {
        return normalizeValueString(str, property)
      })
    }

    return normalizeValueString(value, property)
  }

  /**
   * Copy styles from one object to another.
   *
   * @param  {Object} dest
   * @param  {Object} src
   * @return {Object}
   */
  function copyStyles (dest, src) {
    Object.keys(src).forEach(function (key) {
      var prop = normalizeProperty(key)
      var value = src[key]

      if (isNestedDefinition(value)) {
        dest[prop] = normalizeStyles(dest[prop] || {}, value)

        return
      }

      if (value != null) {
        dest[prop] = normalizeValue(value, prop)
      }
    })

    return dest
  }

  /**
   * Sort an object keys.
   *
   * @param  {Object} obj
   * @return {Object}
   */
  function sortKeys (obj) {
    var sorted = {}

    Object.keys(obj).sort().forEach(function (key) {
      sorted[key] = obj[key]
    })

    return sorted
  }

  /**
   * Normalize one or more objects.
   *
   * @param  {Object} ...src
   * @return {Object}
   */
  function normalizeStyles (/* ...src */) {
    var dest = {}

    for (var i = 0; i < arguments.length; i++) {
      copyStyles(dest, arguments[i])
    }

    return sortKeys(dest)
  }

  /**
   * Turn a single style into a string.
   *
   * @param  {String} property
   * @param  {String} value
   * @return {String}
   */
  function styleStringToString (property, value) {
    return value == null ? '' : property + ':' + value + ';'
  }

  /**
   * Turn a style declaration into a rule.
   *
   * @param  {String} property
   * @param  {String} value
   * @return {String}
   */
  function styleToString (property, value) {
    if (Array.isArray(value)) {
      return value.map(function (value) {
        return styleStringToString(property, value)
      }).join('')
    }

    return styleStringToString(property, value)
  }

  /**
   * Turn a style object into a string.
   *
   * @param  {Object} styles
   * @param  {String} selector
   * @return {String}
   */
  function stylesToString (styles, selector) {
    var rules = ''
    var toplevel = ''

    Object.keys(styles).forEach(function (key) {
      var value = styles[key]

      // Support CSS @-rules (`@media`, `@supports`, etc)
      if (isTopLevelProperty(key)) {
        toplevel += key + '{' + stylesToString(value, selector) + '}'

        return
      }

      // Support LESS-style nested syntax.
      if (isNestedDefinition(value)) {
        if (key.indexOf('&') > -1) {
          key = key.replace(/&/g, selector)
        } else {
          key = selector + ' ' + key
        }

        toplevel += stylesToString(value, key)

        return
      }

      rules += styleToString(key, value)
    })

    if (rules) {
      rules = selector + '{' + rules + '}'
    }

    return rules + toplevel
  }

  /**
   * Create a style object at the root.
   *
   * @param  {Object} styles
   * @return {String}
   */
  function nestedStylesToString (styles, identifier) {
    var rules = ''
    var toplevel = ''

    Object.keys(styles).forEach(function (key) {
      var value = styles[key]

      // Support CSS @-rules inside keyframes (`@supports`)
      if (isTopLevelProperty(key)) {
        toplevel += key + '{' + nestedStylesToString(value, identifier) + '}'

        return
      }

      if (isNestedDefinition(value)) {
        rules += nestedStylesToString(value, key)

        return
      }

      rules += styleToString(key, value)
    })

    if (rules) {
      rules = identifier + '{' + rules + '}'
    }

    return rules + toplevel
  }

  /**
   * Hash a string for use as the class name.
   *
   * @param  {String} str
   * @param  {String} [seed]
   * @return {String}
   */
  function hash (str, seed) {
    var value = seed || 0x811c9dc5

    for (var i = 0; i < str.length; i++) {
      value ^= str.charCodeAt(i)
      value += (value << 1) + (value << 4) + (value << 7) + (value << 8) + (value << 24)
    }

    return (value >>> 0).toString(16)
  }

  /**
   * Hash a style object.
   *
   * @param  {Object} style
   * @return {String}
   */
  function hashStyle (style) {
    return hash(JSON.stringify(style))
  }

  /**
   * Create a namespaced CSS instance.
   *
   * @param {Object} style
   */
  function Namespace (style) {
    this.style = style
    this.className = 'n' + hashStyle(this.style)
    this.selector = '.' + this.className
  }

  /**
   * Get the unique hash.
   *
   * @return {String}
   */
  Namespace.prototype.getHash = function () {
    return this.className
  }

  /**
   * Return styles as a string.
   *
   * @return {String}
   */
  Namespace.prototype.getStyles = function () {
    return stylesToString(this.style, this.selector)
  }

  /**
   * Create keyframes object.
   *
   * @param {Object} style
   */
  function Keyframes (style) {
    this.style = style
    this.name = 'k' + hashStyle(this.style)
  }

  /**
   * Get the unique hash.
   *
   * @return {String}
   */
  Keyframes.prototype.getHash = function () {
    return this.name
  }

  /**
   * Return keyframes style string.
   *
   * @return {String}
   */
  Keyframes.prototype.getStyles = function () {
    return [
      nestedStylesToString(this.style, '@-webkit-keyframes ' + this.name),
      nestedStylesToString(this.style, '@keyframes ' + this.name)
    ].join('')
  }

  /**
   * Create a new stylesheet object.
   */
  function StyleSheet () {
    this.styles = ''
  }

  /**
   * Set the styles string.
   *
   * @param {String} styles
   */
  StyleSheet.prototype.setStyles = function (styles) {
    if (this.node) {
      this.node.innerHTML = styles
    }

    this.styles = styles
  }

  /**
   * Attach the stylesheet to the DOM.
   *
   * @param  {Element}    [target]
   * @return {StyleSheet}
   */
  StyleSheet.prototype.attach = function (target) {
    target = target || document.head

    var node = document.createElement('style')
    node.innerHTML = this.styles
    target.appendChild(node)

    this.node = node

    return this
  }

  /**
   * Detach the stylesheet from the DOM.
   *
   * @return {StyleSheet}
   */
  StyleSheet.prototype.detach = function () {
    if (this.node) {
      if (this.node.parentNode) {
        this.node.parentNode.removeChild(this.node)
      }

      this.node = undefined
    }

    return this
  }

  /**
   * Global style constructor.
   */
  function FreeStyle () {
    this.cache = {}
  }

  /**
   * Create a fresh instance.
   *
   * @return {FreeStyle}
   */
  FreeStyle.prototype.fresh = function () {
    return new FreeStyle()
  }

  /**
   * Add an object to the style cache.
   *
   * @param {Object} o
   */
  FreeStyle.prototype.add = function (o) {
    this.cache[o.getHash()] = o

    return o
  }

  /**
   * Check if the style exists in the cache.
   *
   * @param  {Object}  o
   * @return {Boolean}
   */
  FreeStyle.prototype.has = function (o) {
    return !!this.cache[o.getHash()]
  }

  /**
   * Remove item from the cache.
   *
   * @param {Object} o
   */
  FreeStyle.prototype.remove = function (o) {
    delete this.cache[o.getHash()]
  }

  /**
   * Clear the cache.
   */
  FreeStyle.prototype.empty = function () {
    this.cache = {}
  }

  /**
   * Create a new style class.
   *
   * @param  {Object}    ...style
   * @return {Namespace}
   */
  FreeStyle.prototype.createClass = function (/* ...style */) {
    return new Namespace(normalizeStyles.apply(null, arguments))
  }

  /**
   * Create and register a new style class.
   *
   * @param  {Object}    ...style
   * @return {Namespace}
   */
  FreeStyle.prototype.registerClass = function (/* ...style */) {
    return this.add(this.createClass.apply(this, arguments))
  }

  /**
   * Create a keyframes object.
   *
   * @param  {Object}    ...style
   * @return {Keyframes}
   */
  FreeStyle.prototype.createKeyframes = function (/* ...style */) {
    return new Keyframes(normalizeStyles.apply(null, arguments))
  }

  /**
   * Create and register a keyframes object.
   *
   * @param  {Object}    ...style
   * @return {Keyframes}
   */
  FreeStyle.prototype.registerKeyframes = function (/* ...style */) {
    return this.add(this.createKeyframes.apply(this, arguments))
  }

  /**
   * Create a valid CSS url string.
   *
   * @param  {String} url
   * @return {String}
   */
  FreeStyle.prototype.url = function (url) {
    return 'url("' + encodeURI(url) + '")'
  }

  /**
   * Join a list of class names together.
   *
   * @param  {String} ...class
   * @return {String}
   */
  FreeStyle.prototype.join = function (/* ...class */) {
    var classNames = []

    for (var i = 0; i < arguments.length; i++) {
      var value = arguments[i]

      if (typeof value === 'string') {
        classNames.push(value)
      } else if (value != null) {
        Object.keys(value).forEach(function (key) {
          if (value[key]) {
            classNames.push(key)
          }
        })
      }
    }

    return classNames.join(' ')
  }

  /**
   * Create a CSS string from styles.
   *
   * @return {String}
   */
  FreeStyle.prototype.getStyles = function () {
    var cache = this.cache

    return Object.keys(cache).map(function (key) {
      return cache[key].getStyles()
    }).join('')
  }

  /**
   * Return a stylesheet interface for browsers.
   *
   * @return {Stylesheet}
   */
  FreeStyle.prototype.createStyleSheet = function () {
    var styleSheet = new StyleSheet()

    styleSheet.setStyles(this.getStyles())

    return styleSheet
  }

  /**
   * Inject the styles into the DOM.
   *
   * @param {Element} [target]
   */
  FreeStyle.prototype.inject = function (target) {
    return this.createStyleSheet().attach(target)
  }

  /**
   * Export a `FreeStyle` instance.
   */
  return new FreeStyle()
})
<|endoftext|>


<commit_before>// Initialize
Parse.initialize("gRgG6rXH59W6J19MrqWtiAWAdEGqjoZjEs0GsH6H", "viwxKM3bX10rDDpGpdc3U0kDCr9eJm4WDhhrlPR3");
$(document).ready(function(){

  $('.controlPanel').hide();
  $('.menu').hide();
  $('.UserSignUpForm').hide();
  $('.hlForm').hide();
  $('.classForm').hide();
  $('#allClassesBox').hide();
  $('.classSetup').hide();

  $(".submit").click(function(event){
              event.preventDefault();
              signIn();
            });

          function signIn(){

              var username = $('#username').val();
              var password = $('#password').val();

              window.Usersname = username;

              $.cookie("cookie_Username", username);
              $.cookie("cookie_Psw", password);
              $.cookie("isCached", true);

             Parse.User.logIn(username, password, {
            success: function(user) {
              //Authentication
              var Auth = Parse.Object.extend("User");
              var query = new Parse.Query(Auth);
              query.equalTo("username", Usersname);
              query.find
              ({
                success: function(results)
                {
                  for (var i = 0; i < results.length; i++){
                    var object = results[i];
                    var auth = object.get('isUsrTeacher')
                    if (auth) {
                      $('.userType').text(Usersname);
                      goHome();
                    }
                    else
                    {
                      alert("You are not a teacher!");
                    }

                  }
                },
                error: function(error){
                  alert("Error: " + error.code + " " + error.message);
                }

                });
              //End Authentication

            },

            error: function(user, error) {

                  alert("Error: " + error.code + " " + error.message);
                }
            });

          };

          function goHome(){
            $('.greenboard').fadeOut( 1000, homeRedir());
            var isFloorActive = false;
            window.IsFloorActive = isFloorActive
          };

          function homeRedir(){
            $( ".controlPanel" ).fadeIn( 1000, function() {
            // Animation complete
            });
            $('.menu').show();
            $('.menu').stop().animate({
                'width':'20%'
              }, 500);

          };
  $("#UserSignInSubmit").click(function(event){
    event.preventDefault();
    signUp();
    });

    function signUp (){

        var name = $('#Username').val();
        var passcode = $('#Password').val();
        var email =  $('Email').val(); //Will not use email auth methods for this app for version 1.

        var user = new Parse.User();

        user.set("username", name);
        user.set("password", passcode);
        user.set("email", email);

        user.signUp(null, {
              success: function(user) {

                alert("User has been successfully signed up.");
              },
              error: function(user, error) {

                alert(error.message)
              }
            });
    };
      function ClearFloor(){
      $('.UserSignUpForm').hide();
      $('.hlForm').hide();
      $('#GroupSelect').hide();
      $('#indivForm').hide();
      $('.classForm').hide();
      $('#allClassesBox').hide();
      IsFloorActive = false;
      }
  $('#newUser').click(function newusr(){
    if (IsFloorActive) {
      ClearFloor();
      newusr();
    }
    else{
      $('.UserSignUpForm').fadeIn( 1000, function(){
      //done
    });
      IsFloorActive = true;
    };

  });

  $('#indivSelect').click(function(){
    $('#GroupSelect').hide();
    $('#indivForm').fadeIn( 200 );

  });

  $('#classSelect').click(function(){
    $('#GroupSelect').hide();
    $('.classForm').fadeIn( 200 );
  });

  function finishedClassCreation(){
    $('.classSetup').fadeOut( 200 );
    $('.mainClassData').fadeIn( 200 );
    $('.teacherNameWelcome').fadeIn( 200 );

  }

  $('.newClassSubmit').click(function(){

    $('.student').each(function(){
        if($(this).is(':checked')){

        var PutClass = Parse.Object.extend("Class");
        var query = new Parse.Query(PutClass);
        var classToUser = $(this).prev();
        alert( classToUser.html() );
        query.equalTo("usersname", classToUser.html());
        query.first({
          success: function(object) {

            object.set("clsNme", $('.className').val() );
            object.set("setByTeacher", Usersname);
            object.save();

          },
          error: function(error) {
            alert("Error: " + error.code + " " + error.message);
          }
        });

        finishedClassCreation();

        }
        else{
        //Do nothing
        }
    });

  });

  $('#classChecker').click(function clsschkr(){
      if (IsFloorActive) {
        ClearFloor();
        clsschkr();
      }
      else{
        $('.tNWBox').text("Here are your classes, " + Usersname + ".");
        $('#allClassesBox').fadeIn( 200 );
        $('.hasNoClass').hide();
        IsFloorActive = true;
      }
  });

  $('.classMakeTrigger').click( function(){
    $('.mainClassData').fadeOut( 200 );
    $('.teacherNameWelcome').fadeOut( 200 );
    $('.classSetup').fadeIn( 200 );
    GetUsers();

  });

  $('#hltrigger').click(function hltriggr(){
    if (IsFloorActive) {
      ClearFloor();
      hltriggr();
    }
    else{
      $('#indivForm').hide();
      $('.hlForm').fadeIn( 80 );
      $('#GroupSelect').fadeIn( 80 );

      IsFloorActive = true;
    };

  });

  //Function to get all users from the server
  function GetUsers(){
    var studentQuery = Parse.Object.extend("User");
    var query = new Parse.Query(studentQuery);
    query.notContainedIn("username",
                     ["Admin", "ExpandDong", "crawford.j", "Isaacs", "yearwood"])
    query.find
    ({
      success: function(results)
            {
            // Do something with the returned Parse.Object values
            for (var i = 0; i < results.length; i++) {
            var object = results[i];
            $('.studentPicker').append( '
' + '
' + object.get('username') + '
' + '<input type="checkbox" class="student" name="studentsName" value="StudentsUser">' + '
')

            }
            },
            error: function(error)
            {
            alert("Error: " + error.code + " " + error.message);
            }
    })
  };

  //Function to save a homework object

       $('#hlSubmit').click(
        function (){
       var Homework = Parse.Object.extend("Homework");
       var homework = new Homework();

       var subject = $('#subjectSelector').val();
       var studentName = $('#StudentName').val();
       var hlcontent = $('#hltext').val();

        homework.set("Subject", subject);
        homework.set("UserName", studentName);
        homework.set("Content", hlcontent);

        homework.save(null, {
          success: function(tableobject) {
            // Execute any logic that should take place after the object is saved.
            alert('New object created with objectId: ' + tableobject.id);
            var SubjectSaveId = tableobject.id
          },
          error: function(tableobject, error) {
            // Execute any logic that should take place if the save fails.
            // error is a Parse.Error with an error code and description.
            alert('Failed to create new object, with error code: ' + error.description);
          }
        });
    });

    $('#logout').click(function(){
      $.cookie("isCached", false);
    });

});
<commit_msg>try again<commit_after>// Initialize
Parse.initialize("gRgG6rXH59W6J19MrqWtiAWAdEGqjoZjEs0GsH6H", "viwxKM3bX10rDDpGpdc3U0kDCr9eJm4WDhhrlPR3");
$(document).ready(function(){

  $('.controlPanel').hide();
  $('.menu').hide();
  $('.UserSignUpForm').hide();
  $('.hlForm').hide();
  $('.classForm').hide();
  $('#allClassesBox').hide();
  $('.classSetup').hide();
  $('.hasNoClass').hide();

  $(".submit").click(function(event){
              event.preventDefault();
              signIn();
            });

          function signIn(){

              var username = $('#username').val();
              var password = $('#password').val();

              window.Usersname = username;

              $.cookie("cookie_Username", username);
              $.cookie("cookie_Psw", password);
              $.cookie("isCached", true);

             Parse.User.logIn(username, password, {
            success: function(user) {
              //Authentication
              var Auth = Parse.Object.extend("User");
              var query = new Parse.Query(Auth);
              query.equalTo("username", Usersname);
              query.find
              ({
                success: function(results)
                {
                  for (var i = 0; i < results.length; i++){
                    var object = results[i];
                    var auth = object.get('isUsrTeacher')
                    if (auth) {
                      $('.userType').text(Usersname);
                      goHome();
                    }
                    else
                    {
                      alert("You are not a teacher!");
                    }

                  }
                },
                error: function(error){
                  alert("Error: " + error.code + " " + error.message);
                }

                });
              //End Authentication

            },

            error: function(user, error) {

                  alert("Error: " + error.code + " " + error.message);
                }
            });

          };

          function goHome(){
            $('.greenboard').fadeOut( 1000, homeRedir());
            var isFloorActive = false;
            window.IsFloorActive = isFloorActive
          };

          function homeRedir(){
            $( ".controlPanel" ).fadeIn( 1000, function() {
            // Animation complete
            });
            $('.menu').show();
            $('.menu').stop().animate({
                'width':'20%'
              }, 500);

          };

  $("#UserSignInSubmit").click(function(event){
    event.preventDefault();
    signUp();
    });

    function signUp (){

        var name = $('#Username').val();
        var passcode = $('#Password').val();
        var email =  $('Email').val(); //Will not use email auth methods for this app for version 1.

        var user = new Parse.User();

        user.set("username", name);
        user.set("password", passcode);
        user.set("email", email);

        user.signUp(null, {
              success: function(user) {

                alert("User has been successfully signed up.");
              },
              error: function(user, error) {

                alert(error.message)
              }
            });
    };
      function ClearFloor(){
      $('.UserSignUpForm').hide();
      $('.hlForm').hide();
      $('#GroupSelect').hide();
      $('#indivForm').hide();
      $('.classForm').hide();
      $('#allClassesBox').hide();
      IsFloorActive = false;
      }

  $('#newUser').click(function newusr(){
    if (IsFloorActive) {
      ClearFloor();
      newusr();
    }
    else{
      $('.UserSignUpForm').fadeIn( 1000, function(){
      //done
    });
      IsFloorActive = true;
    };

  });

  $('#indivSelect').click(function(){
    $('#GroupSelect').hide();
    $('#indivForm').fadeIn( 200 );

  });

  $('#classSelect').click(function(){
    $('#GroupSelect').hide();
    $('.classForm').fadeIn( 200 );
  });

  function finishedClassCreation(){
    $('.classSetup').fadeOut( 200 );
    $('.mainClassData').fadeIn( 200 );
<<<<<<>>>>>> origin/gh-pages

  }

  $('.newClassSubmit').click(function(){

    $('.student').each(function(){
        if($(this).is(':checked')){

        var PutClass = Parse.Object.extend("Class");
        var query = new Parse.Query(PutClass);
        var classToUser = $(this).prev();
        alert( classToUser.html() );
        query.equalTo("usersname", classToUser.html());
        query.first({
          success: function(object) {

            object.set("clsNme", $('.className').val() );
            object.set("setByTeacher", Usersname);
            object.save();

          },
          error: function(error) {
            alert("Error: " + error.code + " " + error.message);
          }
        });

        finishedClassCreation();

        }
        else{
        //Do nothing
        }
    });

  });

<<<<<<< HEAD

=======
  function noClassesFound(){
    $('.hasNoClass').fadeIn( 200 );
  };

  function classesFound(){
    var classPut = Parse.Object.extend("Class");
    var query = new Parse.Query(classPut);
    query.equalTo("setByTeacher", Usersname);
    query.find
    ({
      success: function(results){
        for (var i = 0; i < results.length; i++) {
          var object = results[i];
          var teacherClass1 = object.get('clsNme');
          $('.Classes').append( '<button>' + teacherClass1 + '</button>');
        }
      },
      error: function(error){
        alert("Error: " + error.code + " " + error.message);
      }
    });
  };
  function getClasses(){
    var teacherClassQuery = Parse.Object.extend("User");
    var query = new Parse.Query(teacherClassQuery);
    query.equalTo("username", Usersname);
    query.find
    ({
      success: function(results)
            {
            // Do something with the returned Parse.Object values
            for (var i = 0; i < results.length; i++) {
            var object = results[i];
            var teacherHasClass = object.get('teacherHasClass');
            if (teacherHasClass){
              classesFound();

            }
            else{
              noClassesFound();
            }
            }
            },
            error: function(error)
            {
            alert("Error: " + error.code + " " + error.message);
            }
    });
  };
>>>>>>> origin/gh-pages

  $('#classChecker').click(function clsschkr(){
      if (IsFloorActive) {
        ClearFloor();
        clsschkr();
      }
      else{
        $('.tNWBox').text("Here are your classes, " + Usersname + ".");
        $('#allClassesBox').fadeIn( 200 );
        $('.hasNoClass').hide();
        IsFloorActive = true;
      }
  });

  $('.classMakeTrigger').click( function(){
    $('.mainClassData').fadeOut( 200 );
    $('.teacherNameWelcome').fadeOut( 200 );
    $('.classSetup').fadeIn( 200 );
    GetUsers();

  });

  $('#hltrigger').click(function hltriggr(){
    if (IsFloorActive) {
      ClearFloor();
      hltriggr();
    }
    else{
      $('#indivForm').hide();
      $('.hlForm').fadeIn( 80 );
      $('#GroupSelect').fadeIn( 80 );

      IsFloorActive = true;
    };

  });

  function putStudents(){
    var getStudents = Parse.Object.extend("User");
    var query = new Parse.Query(getStudents);
    query.equalTo("clsNme", $('.Classes.button').html() );
    query.find
    ({
      success: function(results){
        for (var i = 0; i < results.length; i++){
          var object = results[i];

        }
      }, error: function(){}
    });
  };

  $('.Classes.button').click(function(){
    putStudents();
  });

  //Function to get all users from the server
  function GetUsers(){
    var studentQuery = Parse.Object.extend("User");
    var query = new Parse.Query(studentQuery);
    query.notContainedIn("username",
                     ["Admin", "ExpandDong", "crawford.j", "Isaacs", "yearwood"])
    query.find
    ({
      success: function(results)
            {
            // Do something with the returned Parse.Object values
            for (var i = 0; i < results.length; i++) {
            var object = results[i];
            $('.studentPicker').append( '
' + '
' + object.get('username') + '
' + '<input type="checkbox" class="student" name="studentsName" value="StudentsUser">' + '
')

            }
            },
            error: function(error)
            {
            alert("Error: " + error.code + " " + error.message);
            }
    })
  };

  //Function to save a homework object

       $('#hlSubmit').click(
        function (){
       var Homework = Parse.Object.extend("Homework");
       var homework = new Homework();

       var subject = $('#subjectSelector').val();
       var studentName = $('#StudentName').val();
       var hlcontent = $('#hltext').val();

        homework.set("Subject", subject);
        homework.set("UserName", studentName);
        homework.set("Content", hlcontent);

        homework.save(null, {
          success: function(tableobject) {
            // Execute any logic that should take place after the object is saved.
            alert('New object created with objectId: ' + tableobject.id);
            var SubjectSaveId = tableobject.id
          },
          error: function(tableobject, error) {
            // Execute any logic that should take place if the save fails.
            // error is a Parse.Error with an error code and description.
            alert('Failed to create new object, with error code: ' + error.description);
          }
        });
    });

    $('#logout').click(function(){
      $.cookie("isCached", false);
    });

});
<|endoftext|>


<commit_before>/**
 * Widget component.
 *
 * Site Kit by Google, Copyright 2020 Google LLC
 *
 * 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
 *
 *     https://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.
 */

/**
 * External dependencies
 */
import classnames from 'classnames';
import { node, string } from 'prop-types';

/**
 * WordPress dependencies
 */
import { Children } from '@wordpress/element';

const Widget = ( { children, className, slug } ) => {
	if ( ! Children.count( children ) ) {
		return null;
	}

	return (
		<div className={ classnames( 'googlesitekit-widget', `googlesitekit-widget--${ slug }`, className ) }>
			{ children }

	);
};

Widget.defaultProps = {
	children: undefined,
};

Widget.propTypes = {
	children: node,
	slug: string.isRequired,
};

export default Widget;
<commit_msg>Do not count children in Widget because it does not work as expected and will not cover our needs either way.<commit_after>/**
 * Widget component.
 *
 * Site Kit by Google, Copyright 2020 Google LLC
 *
 * 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
 *
 *     https://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.
 */

/**
 * External dependencies
 */
import classnames from 'classnames';
import { node, string } from 'prop-types';

const Widget = ( { children, className, slug } ) => {
	return (
		<div className={ classnames( 'googlesitekit-widget', `googlesitekit-widget--${ slug }`, className ) }>
			{ children }

	);
};

Widget.defaultProps = {
	children: undefined,
};

Widget.propTypes = {
	children: node,
	slug: string.isRequired,
};

export default Widget;
<|endoftext|>


<commit_before>/* eslint-disable flowtype/require-valid-file-annotation */

export NodeGroup from './NodeGroup';
export TickGroup from './TickGroup';
<commit_msg>add Animate to index<commit_after>/* eslint-disable flowtype/require-valid-file-annotation */

export Animate from './Animate';
export NodeGroup from './NodeGroup';
export TickGroup from './TickGroup';
<|endoftext|>


<commit_before>/*jslint browser: true */
/*globals Mustache: false, ace: false, require: false */

(function (mustache, ace, require, document, localStorage, Worker, console, setInterval) {
    'use strict';

    var SAVE_INTERVAL = 5000,
        activeEngine = 'mustache',
        renderingWorker,
        JSONMode = require('ace/mode/json').Mode,
        HTMLMode = require('ace/mode/html').Mode,
        templateEditor = ace.edit('template'),
        viewEditor = ace.edit('view'),
        resultEditor = ace.edit('result'),
        templateElement = document.getElementById('template'),
        viewElement = document.getElementById('view'),
        engineElement = document.getElementById('engine'),
        engineTemplate = document.getElementById('engine-template').innerHTML,
        defaultTemplate = document.getElementById('default-template').innerHTML,
        defaultView = document.getElementById('default-view').innerHTML,
        i,
        selectHtml = '',
        engines = {
            dot: {
                name: 'doT.js',
                version: '0.1.7',
                size: '2.2',
                url: 'https://github.com/olado/doT'
            },
            ejs: {
                name: 'EJS',
                version: '0.6.1',
                size: '6.1',
                url: 'https://github.com/visionmedia/ejs'
            },
            haml: {
                name: 'Haml.js',
                version: '0.4.2',
                size: '8.6',
                url: 'https://github.com/creationix/haml-js'
            },
            handlebars: {
                name: 'Handlebars.js',
                version: '1.0.6beta',
                size: '30.3',
                url: 'https://github.com/wycats/handlebars.js'
            },
            hogan: {
                name: 'Hogan.js',
                version: '2.0.0',
                size: '5.9',
                url: 'https://github.com/twitter/hogan.js'
            },
            jade: {
                name: 'Jade',
                version: '0.21.0',
                size: '34.6',
                url: 'https://github.com/visionmedia/jade'
            },
            mustache: {
                name: 'Mustache.js',
                version: '0.4.2',
                size: '4.5',
                url: 'https://github.com/janl/mustache.js'
            },
            underscore: {
                name: 'Underscore.js',
                version: '1.3.1',
                size: '12.1',
                url: 'https://github.com/documentcloud/underscore'
            }
        };

    function EventEmitter() {
        if (!(this instanceof EventEmitter)) {
            return new EventEmitter();
        }

        var listeners = {};

        this.on = function (topic, callback) {
            if (!listeners[topic]) {
                listeners[topic] = [];
            }

            listeners[topic].push(callback);
        };

        this.emit = function (topic, data) {
            if (listeners[topic]) {
                listeners[topic].forEach(function (callback) {
                    callback(data);
                });
            }
        };
    }

    function RenderingWorker(initEngine) {
        if (!(this instanceof RenderingWorker)) {
            return new RenderingWorker(initEngine);
        }

        var engine = initEngine,
            worker = new Worker('js/worker.js'),
            events = new EventEmitter(),
            commands = {
                init: function () {
                    worker.postMessage({
                        cmd: 'init',
                        id: engine
                    });
                },
                render: function (template, view) {
                    worker.postMessage({
                        cmd: 'render',
                        template: template,
                        view: view
                    });
                }
            };

        function init() {
            worker.addEventListener('message', function (event) {
                events.emit('message', event.data);
            }, false);

            commands.init();
        }

        this.changeEngine = function (newEngine) {
            engine = newEngine;

            worker.terminate();
            worker = new Worker('js/worker.js');
            init();
        };

        this.render = function (template, view) {
            commands.render(template, view);
        };

        this.on = function (topic, callback) {
            events.on.call(events, topic, callback);
        };

        init();
    }

    renderingWorker = new RenderingWorker(activeEngine);

    // Restore application state
    try {
        defaultTemplate = localStorage.getItem('architect.template') || defaultTemplate;
        defaultView = localStorage.getItem('architect.view') || defaultView;
    } catch (error) {}

    // Initialise the engine select
    for (i in engines) {
        if (engines.hasOwnProperty(i)) {
            selectHtml += mustache.to_html(engineTemplate, {
                id: i,
                name: engines[i].name,
                selected: i === activeEngine
            });
        }
    }
    engineElement.innerHTML = selectHtml;

    // Initialise the editors
    templateEditor.getSession().setMode(new HTMLMode());
    templateEditor.getSession().setValue(defaultTemplate);
    viewEditor.getSession().setMode(new JSONMode());
    viewEditor.getSession().setValue(defaultView);
    resultEditor.getSession().setMode(new HTMLMode());
    resultEditor.setReadOnly(true);

    function render() {
        var json = {},
            view = viewEditor.getSession().getValue(),
            template = templateEditor.getSession().getValue();

        try {
            json = JSON.parse(view);
            viewElement.classList.remove('error');
        } catch (error) {
            viewElement.classList.add('error');
        }

        renderingWorker.render(template, json);
    }

    // Event handlers
    templateEditor.getSession().on('change', render);
    viewEditor.getSession().on('change', render);

    engineElement.addEventListener('change', function () {
        activeEngine = engineElement.value;
        renderingWorker.changeEngine(activeEngine);
        render();
    }, false);

    renderingWorker.on('message', function (data) {
        if (data.error) {
            if (console) {
                console.error(data.error);
            }
            templateElement.classList.add('error');
            resultEditor.getSession().setValue('');
        } else {
            templateElement.classList.remove('error');
            resultEditor.getSession().setValue(data.result);
        }
    });

    // Initial render
    render();

    // Save application state
    setInterval(function () {
        var view = viewEditor.getSession().getValue(),
            template = templateEditor.getSession().getValue();

        try {
            localStorage.setItem('architect.template', template);
            localStorage.setItem('architect.view', view);
        } catch (error) {}
    }, SAVE_INTERVAL);
}(Mustache, ace, require, document, localStorage, Worker, console, setInterval));
<commit_msg>Add saving of the selected templating engine.<commit_after>/*jslint browser: true */
/*globals Mustache: false, ace: false, require: false */

(function (mustache, ace, require, document, localStorage, Worker, console, setInterval) {
    'use strict';

    var SAVE_INTERVAL = 5000,
        activeEngine = 'mustache',
        renderingWorker,
        JSONMode = require('ace/mode/json').Mode,
        HTMLMode = require('ace/mode/html').Mode,
        templateEditor = ace.edit('template'),
        viewEditor = ace.edit('view'),
        resultEditor = ace.edit('result'),
        templateElement = document.getElementById('template'),
        viewElement = document.getElementById('view'),
        engineElement = document.getElementById('engine'),
        engineTemplate = document.getElementById('engine-template').innerHTML,
        defaultTemplate = document.getElementById('default-template').innerHTML,
        defaultView = document.getElementById('default-view').innerHTML,
        i,
        selectHtml = '',
        engines = {
            dot: {
                name: 'doT.js',
                version: '0.1.7',
                size: '2.2',
                url: 'https://github.com/olado/doT'
            },
            ejs: {
                name: 'EJS',
                version: '0.6.1',
                size: '6.1',
                url: 'https://github.com/visionmedia/ejs'
            },
            haml: {
                name: 'Haml.js',
                version: '0.4.2',
                size: '8.6',
                url: 'https://github.com/creationix/haml-js'
            },
            handlebars: {
                name: 'Handlebars.js',
                version: '1.0.6beta',
                size: '30.3',
                url: 'https://github.com/wycats/handlebars.js'
            },
            hogan: {
                name: 'Hogan.js',
                version: '2.0.0',
                size: '5.9',
                url: 'https://github.com/twitter/hogan.js'
            },
            jade: {
                name: 'Jade',
                version: '0.21.0',
                size: '34.6',
                url: 'https://github.com/visionmedia/jade'
            },
            mustache: {
                name: 'Mustache.js',
                version: '0.4.2',
                size: '4.5',
                url: 'https://github.com/janl/mustache.js'
            },
            underscore: {
                name: 'Underscore.js',
                version: '1.3.1',
                size: '12.1',
                url: 'https://github.com/documentcloud/underscore'
            }
        };

    function EventEmitter() {
        if (!(this instanceof EventEmitter)) {
            return new EventEmitter();
        }

        var listeners = {};

        this.on = function (topic, callback) {
            if (!listeners[topic]) {
                listeners[topic] = [];
            }

            listeners[topic].push(callback);
        };

        this.emit = function (topic, data) {
            if (listeners[topic]) {
                listeners[topic].forEach(function (callback) {
                    callback(data);
                });
            }
        };
    }

    function RenderingWorker(initEngine) {
        if (!(this instanceof RenderingWorker)) {
            return new RenderingWorker(initEngine);
        }

        var engine = initEngine,
            worker = new Worker('js/worker.js'),
            events = new EventEmitter(),
            commands = {
                init: function () {
                    worker.postMessage({
                        cmd: 'init',
                        id: engine
                    });
                },
                render: function (template, view) {
                    worker.postMessage({
                        cmd: 'render',
                        template: template,
                        view: view
                    });
                }
            };

        function init() {
            worker.addEventListener('message', function (event) {
                events.emit('message', event.data);
            }, false);

            commands.init();
        }

        this.changeEngine = function (newEngine) {
            engine = newEngine;

            worker.terminate();
            worker = new Worker('js/worker.js');
            init();
        };

        this.render = function (template, view) {
            commands.render(template, view);
        };

        this.on = function (topic, callback) {
            events.on.call(events, topic, callback);
        };

        init();
    }

    // Restore application state
    try {
        activeEngine = localStorage.getItem('architect.engine') || activeEngine;
        defaultTemplate = localStorage.getItem('architect.template') || defaultTemplate;
        defaultView = localStorage.getItem('architect.view') || defaultView;
    } catch (error) {}

    // Initialise the web worker
    renderingWorker = new RenderingWorker(activeEngine);

    // Initialise the engine select
    for (i in engines) {
        if (engines.hasOwnProperty(i)) {
            selectHtml += mustache.to_html(engineTemplate, {
                id: i,
                name: engines[i].name,
                selected: i === activeEngine
            });
        }
    }
    engineElement.innerHTML = selectHtml;

    // Initialise the editors
    templateEditor.getSession().setMode(new HTMLMode());
    templateEditor.getSession().setValue(defaultTemplate);
    viewEditor.getSession().setMode(new JSONMode());
    viewEditor.getSession().setValue(defaultView);
    resultEditor.getSession().setMode(new HTMLMode());
    resultEditor.setReadOnly(true);

    function render() {
        var json = {},
            view = viewEditor.getSession().getValue(),
            template = templateEditor.getSession().getValue();

        try {
            json = JSON.parse(view);
            viewElement.classList.remove('error');
        } catch (error) {
            viewElement.classList.add('error');
        }

        renderingWorker.render(template, json);
    }

    // Event handlers
    templateEditor.getSession().on('change', render);
    viewEditor.getSession().on('change', render);

    engineElement.addEventListener('change', function () {
        activeEngine = engineElement.value;
        renderingWorker.changeEngine(activeEngine);
        render();
    }, false);

    renderingWorker.on('message', function (data) {
        if (data.error) {
            if (console) {
                console.error(data.error);
            }
            templateElement.classList.add('error');
            resultEditor.getSession().setValue('');
        } else {
            templateElement.classList.remove('error');
            resultEditor.getSession().setValue(data.result);
        }
    });

    // Initial render
    render();

    // Save application state
    setInterval(function () {
        var view = viewEditor.getSession().getValue(),
            template = templateEditor.getSession().getValue();

        try {
            localStorage.setItem('architect.engine', activeEngine);
            localStorage.setItem('architect.template', template);
            localStorage.setItem('architect.view', view);
        } catch (error) {}
    }, SAVE_INTERVAL);
}(Mustache, ace, require, document, localStorage, Worker, console, setInterval));
<|endoftext|>


<commit_before>// -----------------------------------------------------------
// MEDIUM
// -----------------------------------------------------------
$(function() {
    rangy.init();

    $('.medium-editable').each(function(index, item) {
        item = $(item);
        if (!item.data('Medium')) {
            item.data('Medium', new Medium(item));
        }
    });
});

var Medium = function(element) {
    this.element = element;
    this.required = this.element.hasClass('js-required');

    this.editorOptions = mediumAttributeOptions();
    this.editor = new MediumEditor(this.element, this.editorOptions);
    this.editor.subscribe('blur', this.blur.bind(this));
    this.element.data('MediumEditor', this.editor);

    this.elements = $(this.editor.elements);
    this.elements.data('MediumEditor', this.editor);

    this.insertOptions = mediumInsertOptions();
    this.insertOptions.editor = this.editor;
    this.element.mediumInsert(this.insertOptions);

    this.blur();
};

Medium.prototype.blur = function(e) {
    if (!e || !$(e.target).is('#colorbox')) {
        this.elements.find('.medium-insert-buttons, .medium-insert-active, .medium-insert-embeds').remove();
        this.elements.find('p,h2,h3,ul,ol,a,strong,b,i,em').each(function(index, item) {
            item = $(item);
            if (!$.trim(item.text()).length) {
                item.remove();
            }
        }.bind(this));

        setTimeout(function() {
            this.editor.checkContentChanged(this.elements.get(0));

            if (!this.elements.children().length) {
                this.elements.addClass('medium-editor-placeholder');
            }

            if (this.required) {
                Required.change(e);
            }
        }.bind(this), 100);
    }
};

Medium.prototype.validate = function() {
    return !!this.elements.text().length;
};

var MediumButton = MediumEditor.extensions.button.extend({
    'init': function () {
        this.contentFA = this.label;
        this.tagNames = [this.tag];
        var classes = this.class ? this.class.split(' ') : [];
        var name = classes.length ? classes.shift() : this.tag;

        MediumEditor.extensions.button.prototype.init.call(this);

        this.classApplier = rangy.createClassApplier(name, {
            'elementTagName': this.tag,
            'elementProperties': classes.length ? {
                'className': classes.join(' ')
            } : null,
            'normalize': true
        });
    },

    'handleClick': function () {
        this.classApplier.toggleSelection();
        if (this.classApplier.isAppliedToSelection()) {
            this.setActive();
        } else {
            this.setInactive();
        }
        this.base.checkContentChanged();
    },

    'isAlreadyApplied': function (node) {
        node = $(node);
        return (node.is(this.tag) && (!this.class || node.hasClass(this.class)));
    }
});<commit_msg>Bugfix: prevent Medium blur when pasting<commit_after>// -----------------------------------------------------------
// MEDIUM
// -----------------------------------------------------------
$(function() {
    rangy.init();

    $('.medium-editable').each(function(index, item) {
        item = $(item);
        if (!item.data('Medium')) {
            item.data('Medium', new Medium(item));
        }
    });
});

var Medium = function(element) {
    this.element = element;
    this.required = this.element.hasClass('js-required');

    this.editorOptions = mediumAttributeOptions();
    this.editor = new MediumEditor(this.element, this.editorOptions);
    this.editor.subscribe('blur', this.blur.bind(this));
    this.element.data('MediumEditor', this.editor);

    this.elements = $(this.editor.elements);
    this.elements.data('MediumEditor', this.editor);

    this.insertOptions = mediumInsertOptions();
    this.insertOptions.editor = this.editor;
    this.element.mediumInsert(this.insertOptions);

    this.keys = 0;
    $window.on('keyup keydown', this.key.bind(this));

    this.blur();
};

Medium.prototype.key = function(e) {
    this.keys = Math.max(0, this.keys + (e.type == 'keydown' ? 1 : -1));
};

Medium.prototype.blur = function(e) {
    if (!this.keys && (!e || !$(e.target).is('#colorbox'))) {
        this.elements.find('.medium-insert-buttons, .medium-insert-active, .medium-insert-embeds').remove();
        this.elements.find('p,h2,h3,ul,ol,a,strong,b,i,em').each(function(index, item) {
            item = $(item);
            if (!$.trim(item.text()).length) {
                item.remove();
            }
        }.bind(this));

        setTimeout(function() {
            this.editor.checkContentChanged(this.elements.get(0));

            if (!this.elements.children().length) {
                this.elements.addClass('medium-editor-placeholder');
            }

            if (this.required) {
                Required.change(e);
            }
        }.bind(this), 100);
    }
};

Medium.prototype.validate = function() {
    return !!this.elements.text().length;
};

var MediumButton = MediumEditor.extensions.button.extend({
    'init': function () {
        this.contentFA = this.label;
        this.tagNames = [this.tag];
        var classes = this.class ? this.class.split(' ') : [];
        var name = classes.length ? classes.shift() : this.tag;

        MediumEditor.extensions.button.prototype.init.call(this);

        this.classApplier = rangy.createClassApplier(name, {
            'elementTagName': this.tag,
            'elementProperties': classes.length ? {
                'className': classes.join(' ')
            } : null,
            'normalize': true
        });
    },

    'handleClick': function () {
        this.classApplier.toggleSelection();
        if (this.classApplier.isAppliedToSelection()) {
            this.setActive();
        } else {
            this.setInactive();
        }
        this.base.checkContentChanged();
    },

    'isAlreadyApplied': function (node) {
        node = $(node);
        return (node.is(this.tag) && (!this.class || node.hasClass(this.class)));
    }
});<|endoftext|>