<commit_before>/**
 * Created by jorgep on 4/17/14.
 */
$(function() {

    // We use an inline data source in the example, usually data would
    // be fetched from a server

    var data = [];

    function getRandomData() {

        var res = [];

        function parseData(json){
            for (var i = 0; i < json.data.length; i++) {
                var year = parseInt(json.data[i].sdatarecordeddate.substring(0,4));
                var month = parseInt(json.data[i].sdatarecordeddate.substring(5,7));
                var day = parseInt(json.data[i].sdatarecordeddate.substring(8,10));
                var hour = parseInt(json.data[i].sdatarecordeddate.substring(11,13));
                var min = parseInt(json.data[i].sdatarecordeddate.substring(14,16));
                var second = parseInt(json.data[i].sdatarecordeddate.substring(17,19));

                res.push([Date.UTC(year, month, day, hour, min, second), json.data[i].sdatavalue]);
            }
        }

        var sensor = document.URL.split('/')[5];
        $.ajax({
            url: '/api/get/temperature/data/' + sensor,
            method: "GET",
            success: parseData
        });

        return res;
    }

    // Set up the control widget

    var updateInterval = 30;

    var plot = $.plot("#placeholder", [ getRandomData() ], {
        series: {
            shadowSize: 0	// Drawing is faster without shadows
        },
        yaxis: {
            min: 0,
            max: 100
        },
        xaxis: {
            mode: "time",
            timezone: "browser"
        }
    });

    function update() {

        plot.setData([getRandomData()]);

        plot.setupGrid()

        plot.draw();
        setTimeout(update, updateInterval);
    }

    update();

    // Add the Flot version string to the footer

    $("#footer").prepend("Flot " + $.plot.version + " – ");
});<commit_msg>getting dates on the graph<commit_after>/**
 * Created by jorgep on 4/17/14.
 */
$(function() {

    // We use an inline data source in the example, usually data would
    // be fetched from a server

    var data = [];

    function getRandomData() {

        if (data.length > 0)
            data = data.slice(1);

        function parseData(json){
            for (var i = 0; i < json.data.length; i++) {
                var year = parseInt(json.data[i].sdatarecordeddate.substring(0,4));
                var month = parseInt(json.data[i].sdatarecordeddate.substring(5,7));
                var day = parseInt(json.data[i].sdatarecordeddate.substring(8,10));
                var hour = parseInt(json.data[i].sdatarecordeddate.substring(11,13));
                var min = parseInt(json.data[i].sdatarecordeddate.substring(14,16));
                var second = parseInt(json.data[i].sdatarecordeddate.substring(17,19));

                data.push([Date.UTC(year, month, day, hour, min, second), json.data[i].sdatavalue]);
            }

        }

        var sensor = document.URL.split('/')[5];
        $.ajax({
            url: '/api/get/temperature/data/' + sensor,
            method: "GET",
            success: parseData
        });

        var res = [];
        for (var i = 0; i < data.length; ++i) {
            res.push(data[i])
        }

        return res;
    }

    // Set up the control widget

    var updateInterval = 30;

    var plot = $.plot("#placeholder", [ getRandomData() ], {
        series: {
            shadowSize: 0	// Drawing is faster without shadows
        },
        yaxis: {
            min: 0,
            max: 100
        },
        xaxis: {
            mode: "time",
            timezone: "browser"
        }
    });

    function update() {

        plot.setData([getRandomData()]);

        plot.setupGrid()

        plot.draw();
        setTimeout(update, updateInterval);
    }

    update();

    // Add the Flot version string to the footer

    $("#footer").prepend("Flot " + $.plot.version + " – ");
});<|endoftext|>


<commit_before>// various utility kinds

enyo.kind({
    name: "StatefulImage",
    kind: "Image",
    published: {
        state: "", // State to set
        stateImages: { } // list of StateName:ImageFilename pairs
    },
    stateChanged: function()
    {
        var x;
        if(x = this.stateImages[this.state]) // yes = is intentional
        {
            this.setSrc(x);
        } else {
            this.log("* Warning: Unknown state", this.state);
        }
    }
});

enyo.kind({
    name: "starImage",
    kind: "StatefulImage",
    stateImages: { "starred": !window.PalmSystem ? "mainApp/images/star.png" : "images/star.png", "unstarred": !window.PalmSystem ? "mainApp/images/unstar.png" : "images/unstar.png" },
    published: {
        "messageId": "",
        "messageIndex": "",
    }
});

enyo.kind({
    name: "noteImage",
    kind: "StatefulImage",
    stateImages: { "noted": !window.PalmSystem ? "mainApp/images/note.png" : "images/note.png", "unnoted": !window.PalmSystem ? "mainApp/images/unnote.png" : "images/unnote.png" },
    published: {
        "messageId": "",
        "messageIndex": "",
    }
})

enyo.kind({
    name: "autoCompleteInput",
    kind: "VFlexBox",
    published: {
        "suggestlist": [ ],
        "numericOnly": true,
        "hint": "",
        "alwaysLooksFocused": false,
        "autoKeyModifier": "",
    },
    suggestions: [ ],
    components: [
        { name: "InputBox", kind: "Input", onkeyup: "keyInput", },
        { name: "AutocompleteBox", kind: "VFlexBox", style: "height: 100px; max-height: 100px;", components:
            [
                { name: "Scroller", kind: "Scroller", flex:1, /*onScroll: "scrolled",*/ components:
                    [
                        { name: "AutocompleteRepeater", kind: "VirtualRepeater", onSetupRow: "getSuggestion", onclick: "rowClicked", components:
                            [
                                { name: "Suggestion", kind: "Item", },
                            ]
                        },
                    ]
                }
            ]
        },
    ],
    create: function()
    {
        this.inherited(arguments);
        this.$.InputBox.setHint(this.hint);
        this.$.InputBox.setAlwaysLooksFocused(this.alwaysLooksFocused);
        this.$.InputBox.setAutoKeyModifier(this.autoKeyModifier);
        //this.$.Scroller.createComponent( { kind: "ScrollFades", name:"fades", isChrome:true, owner:this });
    },
    forceFocus: function() {
        this.$.InputBox.forceFocus();
    },
    forceBlur: function() {
        this.$.InputBox.forceBlur();
    },
    /*scrolled: function(sender) {
        this.$.fades.showHideFades(this.$.Scroller);
    },*/
    keyInput: function(inSender, inEvent)
    {
        var str = this.$.InputBox.getValue().toLowerCase();
        this.suggestions = new Array();
        var testcase = str;

        if(this.numericOnly)
            testcase = str.replace(/[^0-9]/g, '');
        for (var s in this.suggestlist)
        {
            var suggestiontest = this.suggestlist[s];
            if(this.numericOnly) {
                suggestiontest = suggestiontest.replace(/[^0-9]/g, '');
            }
            if(suggestiontest.indexOf(testcase) != -1)
            {
                this.suggestions.push(this.suggestlist[s]);
            }
        }
        if(this.suggestions.length == 0)
            this.$.AutocompleteBox.hide();
        else
            this.$.AutocompleteBox.show();
        this.$.AutocompleteRepeater.render();
        return true;
    },
    getSuggestion: function(inSender, inRow)
    {
        if(this.suggestions[inRow])
        {
            this.$.Suggestion.setContent(this.suggestions[inRow]);
            return true;
        }
        return false;
    },
    getValue: function()
    {
        return this.$.InputBox.getValue();
    },
    setValue: function(str)
    {
        this.$.AutocompleteBox.hide();
        this.$.InputBox.setValue(str);
    },
    rowClicked: function(inSender, inEvent)
    {
        this.setValue(this.suggestions[inEvent.rowIndex]);
    }
});

enyo.kind({
    name: "messageListRepeater",
    kind: "VFlexBox",
    components:
    [
        { kind: "VirtualRepeater", onSetupRow: "renderItem", accelerated: true, onclick: "repeaterClick", components:
            [
                { kind: "Control", layoutKind: "VFlexLayout", className: "noborders", onclick: "listClick", components:
                    [
                        { name: "message", kind: "HFlexBox", components:
                            [
                                { name: "timestampleft", kind: "HtmlContent", style: "padding-right: 5px;", allowHtml: false, className: "enyo-item-ternary", showing: false },
                                { name: "listItem", kind: "HtmlContent", flex: 1, allowHtml: true, onLinkClick: "linkClicked", },
                                { name: "timestamp", kind: "HtmlContent", allowHtml: false, style: "padding-left: 5px;", className: "enyo-item-ternary", },
                            ]
                        },
                    ]
                }
            ]
        }
    ],
    published: {
        messageId: "",
    },
    events: {
        "onMessageClick": "",
        "onLinkClick": "",
    },
    linkClicked: function(inSender, inUrl, inEvent)
    {
        // TODO: HAX! linkClicked in main app is expecting (sender, url, event), we by calling doLinkClick give it inSender, inEvent, inUrl .. grrr..
        this.doLinkClick(inUrl, inEvent)
        //enyo.application.mainApp.linkClicked(inSender, inUrl, inEvent);
        inEvent.stopPropagation();
    },
    listClick: function(inSender, inEvent)
    {
        //this.log(inSender, ".", inEvent, ".", this.messageId);
        this.doMessageClick(inEvent, this.messageId);
        //inEvent.preventDefault();
        //inEvent.stopPropagation();
    },
    repeaterClick: function(inSender, inEvent)
    {
        //this.log(inSender, ".", inEvent, ".", this.messageId);
        inEvent.preventDefault();
    },
    renderItem: function(inSender, inRow) // TODO: reflow this so we aren't returning half a dozen times from it
    {
        var overviewMsg = enyo.application.mainApp ? enyo.application.mainApp.overviewMsg : -1;

        if(overviewMsg == -1) // no messages at all!
        {
            if(inRow == 0)
            {
                //this.$.overviewTitle.hide();
                this.$.listItem.setContent("No messages found in this view.  Send and ye shall receive!");
                return true;
            }
            return false;
        }

        var index = inRow - 1;

        if(index == -1)
        {
            return true;
        }

        var messageIndex = enyo.application.mainApp.MessageIndex[overviewMsg];
        var title = "";
        var str = "";
        var message = enyo.application.mainApp.Messages && enyo.application.mainApp.Messages[overviewMsg] ? enyo.application.mainApp.Messages[overviewMsg][index] : undefined;

        //this.log(overviewMsg);
        //this.log(index);
        //this.log(messageIndex);
        //this.log(message);

        if(message)
        {
            if(prefs.get("smallFonts") === true && !this.$.listItem.hasClass("enyo-item-secondary"))
            {
                this.$.listItem.addClass("enyo-item-secondary");
            }
            if(message.SentBy == "Me:")
            {
                if(!this.$.message.hasClass("gvoice-inbox-message-self"))
                {
                    this.$.message.addClass("gvoice-inbox-message-self");
                }
                this.$.timestamp.setShowing(false);
                this.$.timestampleft.setShowing(true);
                this.$.timestampleft.setContent(message.SentTime);
            }
            else
            {
                if(!this.$.message.hasClass("gvoice-inbox-message-alt"))
                {
                    this.$.message.addClass("gvoice-inbox-message-alt");
                }
            }

            if(messageIndex.isVoicemail) // TODO: our dumb asses can search "MessageIndex[index].labels" for this such as "missed", "voicemail", etc, rather than parsing the fucking html
            {
                if(message.VoicemailTranscript) {
                    str = message.VoicemailTranscript;
                }
                else {
                    str = "Transcript not available.";
                }
            } else {
                if(message.SentMessage)
                    str = message.SentMessage;
                else
                    str = "Message not available.";
                if(this.$.timestamp)
                    this.$.timestamp.setContent(message.SentTime);
                //str += " (" + message.SentTime + ")";
            }
            this.$.listItem.setContent(str);
            return true;
        } else
        if(index == 0) {
            this.$.listItem.addClass("gvoice-inbox-message-alt");
            this.$.listItem.setContent("No information available");
            return true;
        }
        return false;
    },

});

enyo.kind({
    name: "ThreeWaySlidingView",
    kind: "SlidingView",
});
<commit_msg>force dialpad input to remain focused after typign into autocomplete input on non weboS<commit_after>// various utility kinds

enyo.kind({
    name: "StatefulImage",
    kind: "Image",
    published: {
        state: "", // State to set
        stateImages: { } // list of StateName:ImageFilename pairs
    },
    stateChanged: function()
    {
        var x;
        if(x = this.stateImages[this.state]) // yes = is intentional
        {
            this.setSrc(x);
        } else {
            this.log("* Warning: Unknown state", this.state);
        }
    }
});

enyo.kind({
    name: "starImage",
    kind: "StatefulImage",
    stateImages: { "starred": !window.PalmSystem ? "mainApp/images/star.png" : "images/star.png", "unstarred": !window.PalmSystem ? "mainApp/images/unstar.png" : "images/unstar.png" },
    published: {
        "messageId": "",
        "messageIndex": "",
    }
});

enyo.kind({
    name: "noteImage",
    kind: "StatefulImage",
    stateImages: { "noted": !window.PalmSystem ? "mainApp/images/note.png" : "images/note.png", "unnoted": !window.PalmSystem ? "mainApp/images/unnote.png" : "images/unnote.png" },
    published: {
        "messageId": "",
        "messageIndex": "",
    }
})

enyo.kind({
    name: "autoCompleteInput",
    kind: "VFlexBox",
    published: {
        "suggestlist": [ ],
        "numericOnly": true,
        "hint": "",
        "alwaysLooksFocused": false,
        "autoKeyModifier": "",
    },
    suggestions: [ ],
    components: [
        { name: "InputBox", kind: "Input", onkeyup: "keyInput", },
        { name: "AutocompleteBox", kind: "VFlexBox", style: "height: 100px; max-height: 100px;", components:
            [
                { name: "Scroller", kind: "Scroller", flex:1, /*onScroll: "scrolled",*/ components:
                    [
                        { name: "AutocompleteRepeater", kind: "VirtualRepeater", onSetupRow: "getSuggestion", onclick: "rowClicked", components:
                            [
                                { name: "Suggestion", kind: "Item", },
                            ]
                        },
                    ]
                }
            ]
        },
    ],
    create: function()
    {
        this.inherited(arguments);
        this.$.InputBox.setHint(this.hint);
        this.$.InputBox.setAlwaysLooksFocused(this.alwaysLooksFocused);
        this.$.InputBox.setAutoKeyModifier(this.autoKeyModifier);
        //this.$.Scroller.createComponent( { kind: "ScrollFades", name:"fades", isChrome:true, owner:this });
    },
    forceFocus: function() {
        this.$.InputBox.forceFocus();
    },
    forceBlur: function() {
        this.$.InputBox.forceBlur();
    },
    /*scrolled: function(sender) {
        this.$.fades.showHideFades(this.$.Scroller);
    },*/
    keyInput: function(inSender, inEvent)
    {
        var str = this.$.InputBox.getValue().toLowerCase();
        this.suggestions = new Array();
        var testcase = str;

        if(this.numericOnly)
            testcase = str.replace(/[^0-9]/g, '');
        for (var s in this.suggestlist)
        {
            var suggestiontest = this.suggestlist[s];
            if(this.numericOnly) {
                suggestiontest = suggestiontest.replace(/[^0-9]/g, '');
            }
            if(suggestiontest.indexOf(testcase) != -1)
            {
                this.suggestions.push(this.suggestlist[s]);
            }
        }
        if(this.suggestions.length == 0)
            this.$.AutocompleteBox.hide();
        else
            this.$.AutocompleteBox.show();
        this.$.AutocompleteRepeater.render();
        if(!window.PalmSystem)
            this.forceFocus();
        return true;
    },
    getSuggestion: function(inSender, inRow)
    {
        if(this.suggestions[inRow])
        {
            this.$.Suggestion.setContent(this.suggestions[inRow]);
            return true;
        }
        return false;
    },
    getValue: function()
    {
        return this.$.InputBox.getValue();
    },
    setValue: function(str)
    {
        this.$.AutocompleteBox.hide();
        this.$.InputBox.setValue(str);
    },
    rowClicked: function(inSender, inEvent)
    {
        this.setValue(this.suggestions[inEvent.rowIndex]);
    }
});

enyo.kind({
    name: "messageListRepeater",
    kind: "VFlexBox",
    components:
    [
        { kind: "VirtualRepeater", onSetupRow: "renderItem", accelerated: true, onclick: "repeaterClick", components:
            [
                { kind: "Control", layoutKind: "VFlexLayout", className: "noborders", onclick: "listClick", components:
                    [
                        { name: "message", kind: "HFlexBox", components:
                            [
                                { name: "timestampleft", kind: "HtmlContent", style: "padding-right: 5px;", allowHtml: false, className: "enyo-item-ternary", showing: false },
                                { name: "listItem", kind: "HtmlContent", flex: 1, allowHtml: true, onLinkClick: "linkClicked", },
                                { name: "timestamp", kind: "HtmlContent", allowHtml: false, style: "padding-left: 5px;", className: "enyo-item-ternary", },
                            ]
                        },
                    ]
                }
            ]
        }
    ],
    published: {
        messageId: "",
    },
    events: {
        "onMessageClick": "",
        "onLinkClick": "",
    },
    linkClicked: function(inSender, inUrl, inEvent)
    {
        // TODO: HAX! linkClicked in main app is expecting (sender, url, event), we by calling doLinkClick give it inSender, inEvent, inUrl .. grrr..
        this.doLinkClick(inUrl, inEvent)
        //enyo.application.mainApp.linkClicked(inSender, inUrl, inEvent);
        inEvent.stopPropagation();
    },
    listClick: function(inSender, inEvent)
    {
        //this.log(inSender, ".", inEvent, ".", this.messageId);
        this.doMessageClick(inEvent, this.messageId);
        //inEvent.preventDefault();
        //inEvent.stopPropagation();
    },
    repeaterClick: function(inSender, inEvent)
    {
        //this.log(inSender, ".", inEvent, ".", this.messageId);
        inEvent.preventDefault();
    },
    renderItem: function(inSender, inRow) // TODO: reflow this so we aren't returning half a dozen times from it
    {
        var overviewMsg = enyo.application.mainApp ? enyo.application.mainApp.overviewMsg : -1;

        if(overviewMsg == -1) // no messages at all!
        {
            if(inRow == 0)
            {
                //this.$.overviewTitle.hide();
                this.$.listItem.setContent("No messages found in this view.  Send and ye shall receive!");
                return true;
            }
            return false;
        }

        var index = inRow - 1;

        if(index == -1)
        {
            return true;
        }

        var messageIndex = enyo.application.mainApp.MessageIndex[overviewMsg];
        var title = "";
        var str = "";
        var message = enyo.application.mainApp.Messages && enyo.application.mainApp.Messages[overviewMsg] ? enyo.application.mainApp.Messages[overviewMsg][index] : undefined;

        //this.log(overviewMsg);
        //this.log(index);
        //this.log(messageIndex);
        //this.log(message);

        if(message)
        {
            if(prefs.get("smallFonts") === true && !this.$.listItem.hasClass("enyo-item-secondary"))
            {
                this.$.listItem.addClass("enyo-item-secondary");
            }
            if(message.SentBy == "Me:")
            {
                if(!this.$.message.hasClass("gvoice-inbox-message-self"))
                {
                    this.$.message.addClass("gvoice-inbox-message-self");
                }
                this.$.timestamp.setShowing(false);
                this.$.timestampleft.setShowing(true);
                this.$.timestampleft.setContent(message.SentTime);
            }
            else
            {
                if(!this.$.message.hasClass("gvoice-inbox-message-alt"))
                {
                    this.$.message.addClass("gvoice-inbox-message-alt");
                }
            }

            if(messageIndex.isVoicemail) // TODO: our dumb asses can search "MessageIndex[index].labels" for this such as "missed", "voicemail", etc, rather than parsing the fucking html
            {
                if(message.VoicemailTranscript) {
                    str = message.VoicemailTranscript;
                }
                else {
                    str = "Transcript not available.";
                }
            } else {
                if(message.SentMessage)
                    str = message.SentMessage;
                else
                    str = "Message not available.";
                if(this.$.timestamp)
                    this.$.timestamp.setContent(message.SentTime);
                //str += " (" + message.SentTime + ")";
            }
            this.$.listItem.setContent(str);
            return true;
        } else
        if(index == 0) {
            this.$.listItem.addClass("gvoice-inbox-message-alt");
            this.$.listItem.setContent("No information available");
            return true;
        }
        return false;
    },

});

enyo.kind({
    name: "ThreeWaySlidingView",
    kind: "SlidingView",
});
<|endoftext|>


<commit_before>'use strict';

var fs = require('fs'),
    path = require('path');

var Hogan = require('hogan.js'),
    _ = require('underscore'),
    moment = require('moment');

// This returns a middleware that places mixins against the `res.locals` object.
//
// It should be given:
// - t: a function that will translate a key into the correct language depending
//      on the locale selected.
// - fields: the data needed to generate mixins options, etc.
// - options:
//   - viewDirectory: the folder in which templates are found in.
//   - viewEngine: the type of view, defaults to 'html'.
//   - sharedTranslationsKey: used to find translations relatively within
//     the translations.json. Useful for field and button labels.
module.exports = function (t, fields, options) {

    // This code probably does not need this as the only time it is used
    // only a single key is passed in.
    var i18nLookup = require('./i18n-property')(t);

    fields = fields || {};

    var viewsDirectory = options && options.viewsDirectory || path.resolve(__dirname, '../');
    var viewEngine = options && options.viewEngine || 'html';
    var sharedTranslationsKey = options && options.sharedTranslationsKey || 'shared';

    var PARTIALS = [
        'partials/forms/input-text-group',
        'partials/forms/input-submit',
        'partials/forms/radio-group',
        'partials/forms/select',
        'partials/forms/checkbox'
    ];
    var compiled = _.chain(PARTIALS).map(function (relativeTemplatePath) {
        var viewExtension = '.' + viewEngine;
        var templatePath = path.join(viewsDirectory, relativeTemplatePath + viewExtension);
        var compiledTemplate = Hogan.compile(fs.readFileSync(templatePath).toString());

        return [relativeTemplatePath, compiledTemplate];
    }).object().value();

    function maxlength(key) {
        var validation = fields[key] && fields[key].validate || [];
        var ml = _.findWhere(validation, { type: 'maxlength' }) || _.findWhere(validation, { type: 'exactlength' });
        if (ml) {
            return _.isArray(ml.arguments) ? ml.arguments[0] : ml.arguments;
        } else {
            return null;
        }
    }

    function type(key) {
        return fields[key] && fields[key].type || 'text';
    }

    function display(key) {
        return fields[key] && fields[key].display;
    }

    function inputText(key, extension) {
        extension = extension || {};
        return _.extend(extension, {
            id: key,
            type: extension.type || type(key),
            value: this.values && this.values[key],
            label: t(sharedTranslationsKey + '.fields.' + key + '.label'),
            hint: i18nLookup(sharedTranslationsKey + '.fields.' + key + '.hint'),
            error: this.errors && this.errors[key],
            maxlength: extension.maxlength || maxlength(key),
            required: extension.required !== undefined ? extension.required : true,
            pattern: extension.pattern
        });
    }

    function optionGroup(key) {
        return {
            key: key,
            error: this.errors && this.errors[key],
            options: _.map(fields[key].options, function (label) {
                var selected = false, value;

                if (typeof label === 'string') {
                    value = label;
                } else {
                    value = label.value;
                    label = label.label;
                }

                if (this.values && this.values[key] !== undefined) {
                    selected = this.values[key] === value;
                }
                return {
                    label: t(label),
                    value: value,
                    selected: selected
                };
            }, this),
            display: display(key)
        };
    }

    function checkbox(key, options) {
        options = options || {};
        options.required = options.required || false;
        var selected = false;
        if (this.values && this.values[key] !== undefined) {
            selected = this.values[key].toString() === 'true';
        }
        return _.extend(options, {
            key: key,
            error: this.errors && this.errors[key],
            invalid: this.errors && this.errors[key] && options.required,
            label: t(sharedTranslationsKey + '.fields.' + key + '.label'),
            selected: selected
        });
    }

    return function (req, res, next) {

        res.locals['input-text'] = function () {
            return function (key) {
                return compiled['partials/forms/input-text-group'].render(inputText.call(this, key));
            };
        };

        res.locals['input-date'] = function () {
            return function (key) {
                var parts = [
                    compiled['partials/forms/input-text-group'].render(inputText.call(this, key + '-day', { pattern: '[0-9]*', min: 1, max: 31, maxlength: 2, class: 'date-input' })),
                    compiled['partials/forms/input-text-group'].render(inputText.call(this, key + '-month', { pattern: '[0-9]*', min: 1, max: 12, maxlength: 2, class: 'date-input' })),
                    compiled['partials/forms/input-text-group'].render(inputText.call(this, key + '-year', { pattern: '[0-9]*', maxlength: 4, class: 'date-input' }))
                ];
                return parts.join('\n');
            };
        };

        res.locals['input-text-compound'] = function () {
            return function (key) {
                var obj = { compound: true };
                return compiled['partials/forms/input-text-group'].render(inputText.call(this, key, obj));
            };
        };

        res.locals['input-text-hidden-label'] = function () {
            return function (key) {
                var obj = {
                    hiddenLabel: true,
                    required: false
                };
                return compiled['partials/forms/input-text-group'].render(inputText.call(this, key, obj));
            };
        };

        res.locals['input-text-postcode'] = function () {
            return function (key) {
                var obj = {
                    postcode: true,
                    class: 'uppercase'
                };
                return compiled['partials/forms/input-text-group'].render(inputText.call(this, key, obj));
            };
        };

        res.locals['input-phone'] = function () {
            return function (key) {
                return compiled['partials/forms/input-text-group'].render(inputText.call(this, key, { maxlength: 18 }));
            };
        };

        res.locals['radio-group'] = function () {
            return function (key) {
                return compiled['partials/forms/radio-group'].render(optionGroup.call(this, key));
            };
        };

        res.locals.select = function () {
            return function (key) {
                return compiled['partials/forms/select'].render(inputText.call(this, key, optionGroup.call(this, key)));
            };
        };

        res.locals.checkbox = function () {
            return function (key) {
                return compiled['partials/forms/checkbox'].render(checkbox.call(this, key));
            };
        };

        res.locals['checkbox-compound'] = function () {
            var options = { compound: true };
            return function (key) {
                return compiled['partials/forms/checkbox'].render(checkbox.call(this, key, options));
            };
        };

        res.locals['checkbox-required'] = function () {
            var options = { required: true };
            return function (key) {
                return compiled['partials/forms/checkbox'].render(checkbox.call(this, key, options));
            };
        };

        /**
        * props: '[value] [id]'
        */
        res.locals['input-submit'] = function () {
            return function (props) {
                props = props.split(' ');
                var def = 'next',
                    value = props[0] || def,
                    id = props[1];

                var obj = {
                    value: t(sharedTranslationsKey + '.buttons.' + value),
                    id: id
                };
                return compiled['partials/forms/input-submit'].render(obj);
            };
        };

        res.locals.currency = function () {
            return function (txt) {
                var value = parseFloat(Hogan.compile(txt).render(this));
                if (isNaN(value)) {
                    return txt;
                } else if (value % 1 === 0) {
                    value = value.toString();
                } else {
                    value = value.toFixed(2);
                }
                return '£' + value;
            };
        };

        res.locals.date = function () {
            return function (txt) {
                var value = Hogan.compile(txt).render(this);
                return moment(value).format('D MMMM YYYY');
            };
        };

        res.locals.hyphenate = function () {
            return function (txt) {
                txt = txt || '';
                return Hogan.compile(txt).render(this).toLowerCase().replace(' ', '-');
            };
        };

        res.locals.uppercase = function () {
            return function (txt) {
                txt = txt || '';
                return Hogan.compile(txt).render(this).toUpperCase();
            };
        };

        res.locals.lowercase = function () {
            return function (txt) {
                txt = txt || '';
                return Hogan.compile(txt).render(this).toLowerCase();
            };
        };

        res.locals.selected = function () {
            return function (txt) {
                var bits = txt.split('='),
                    val;
                if (this.values && this.values[bits[0]] !== undefined) {
                    val = this.values[bits[0]].toString();
                }
                return val === bits[1] ? ' checked="checked"' : '';
            };
        };

        /**
        * Use on whole sentences
        */
        res.locals.time = function () {
            return function (txt) {
                txt = txt || '';
                txt = Hogan.compile(txt).render(this);
                txt = txt.replace(/12:00am/i, 'midnight').replace(/^midnight/, 'Midnight');
                txt = txt.replace(/12:00pm/i, 'midday').replace(/^middday/, 'Midday');
                return txt;
            };
        };

        res.locals.t = function () {
            return function (txt) {
                txt = Hogan.compile(txt).render(this);
                return t.apply(req, [txt, this]);
            };
        };

        next();
    };

};
<commit_msg>Fallback to _.identity if there is no translation function passed in.<commit_after>'use strict';

var fs = require('fs'),
    path = require('path');

var Hogan = require('hogan.js'),
    _ = require('underscore'),
    moment = require('moment');

// This returns a middleware that places mixins against the `res.locals` object.
//
// It should be given:
// - t: a function that will translate a key into the correct language depending
//      on the locale selected.
// - fields: the data needed to generate mixins options, etc.
// - options:
//   - viewDirectory: the folder in which templates are found in.
//   - viewEngine: the type of view, defaults to 'html'.
//   - sharedTranslationsKey: used to find translations relatively within
//     the translations.json. Useful for field and button labels.
module.exports = function (t, fields, options) {

    t = t || _.identity;
    fields = fields || {};

    // This code probably does not need this as the only time it is used
    // only a single key is passed in.
    var i18nLookup = require('./i18n-property')(t);

    var viewsDirectory = options && options.viewsDirectory || path.resolve(__dirname, '../');
    var viewEngine = options && options.viewEngine || 'html';
    var sharedTranslationsKey = options && options.sharedTranslationsKey || 'shared';

    var PARTIALS = [
        'partials/forms/input-text-group',
        'partials/forms/input-submit',
        'partials/forms/radio-group',
        'partials/forms/select',
        'partials/forms/checkbox'
    ];
    var compiled = _.chain(PARTIALS).map(function (relativeTemplatePath) {
        var viewExtension = '.' + viewEngine;
        var templatePath = path.join(viewsDirectory, relativeTemplatePath + viewExtension);
        var compiledTemplate = Hogan.compile(fs.readFileSync(templatePath).toString());

        return [relativeTemplatePath, compiledTemplate];
    }).object().value();

    function maxlength(key) {
        var validation = fields[key] && fields[key].validate || [];
        var ml = _.findWhere(validation, { type: 'maxlength' }) || _.findWhere(validation, { type: 'exactlength' });
        if (ml) {
            return _.isArray(ml.arguments) ? ml.arguments[0] : ml.arguments;
        } else {
            return null;
        }
    }

    function type(key) {
        return fields[key] && fields[key].type || 'text';
    }

    function display(key) {
        return fields[key] && fields[key].display;
    }

    function inputText(key, extension) {
        extension = extension || {};
        return _.extend(extension, {
            id: key,
            type: extension.type || type(key),
            value: this.values && this.values[key],
            label: t(sharedTranslationsKey + '.fields.' + key + '.label'),
            hint: i18nLookup(sharedTranslationsKey + '.fields.' + key + '.hint'),
            error: this.errors && this.errors[key],
            maxlength: extension.maxlength || maxlength(key),
            required: extension.required !== undefined ? extension.required : true,
            pattern: extension.pattern
        });
    }

    function optionGroup(key) {
        return {
            key: key,
            error: this.errors && this.errors[key],
            options: _.map(fields[key].options, function (label) {
                var selected = false, value;

                if (typeof label === 'string') {
                    value = label;
                } else {
                    value = label.value;
                    label = label.label;
                }

                if (this.values && this.values[key] !== undefined) {
                    selected = this.values[key] === value;
                }
                return {
                    label: t(label),
                    value: value,
                    selected: selected
                };
            }, this),
            display: display(key)
        };
    }

    function checkbox(key, options) {
        options = options || {};
        options.required = options.required || false;
        var selected = false;
        if (this.values && this.values[key] !== undefined) {
            selected = this.values[key].toString() === 'true';
        }
        return _.extend(options, {
            key: key,
            error: this.errors && this.errors[key],
            invalid: this.errors && this.errors[key] && options.required,
            label: t(sharedTranslationsKey + '.fields.' + key + '.label'),
            selected: selected
        });
    }

    return function (req, res, next) {

        res.locals['input-text'] = function () {
            return function (key) {
                return compiled['partials/forms/input-text-group'].render(inputText.call(this, key));
            };
        };

        res.locals['input-date'] = function () {
            return function (key) {
                var parts = [
                    compiled['partials/forms/input-text-group'].render(inputText.call(this, key + '-day', { pattern: '[0-9]*', min: 1, max: 31, maxlength: 2, class: 'date-input' })),
                    compiled['partials/forms/input-text-group'].render(inputText.call(this, key + '-month', { pattern: '[0-9]*', min: 1, max: 12, maxlength: 2, class: 'date-input' })),
                    compiled['partials/forms/input-text-group'].render(inputText.call(this, key + '-year', { pattern: '[0-9]*', maxlength: 4, class: 'date-input' }))
                ];
                return parts.join('\n');
            };
        };

        res.locals['input-text-compound'] = function () {
            return function (key) {
                var obj = { compound: true };
                return compiled['partials/forms/input-text-group'].render(inputText.call(this, key, obj));
            };
        };

        res.locals['input-text-hidden-label'] = function () {
            return function (key) {
                var obj = {
                    hiddenLabel: true,
                    required: false
                };
                return compiled['partials/forms/input-text-group'].render(inputText.call(this, key, obj));
            };
        };

        res.locals['input-text-postcode'] = function () {
            return function (key) {
                var obj = {
                    postcode: true,
                    class: 'uppercase'
                };
                return compiled['partials/forms/input-text-group'].render(inputText.call(this, key, obj));
            };
        };

        res.locals['input-phone'] = function () {
            return function (key) {
                return compiled['partials/forms/input-text-group'].render(inputText.call(this, key, { maxlength: 18 }));
            };
        };

        res.locals['radio-group'] = function () {
            return function (key) {
                return compiled['partials/forms/radio-group'].render(optionGroup.call(this, key));
            };
        };

        res.locals.select = function () {
            return function (key) {
                return compiled['partials/forms/select'].render(inputText.call(this, key, optionGroup.call(this, key)));
            };
        };

        res.locals.checkbox = function () {
            return function (key) {
                return compiled['partials/forms/checkbox'].render(checkbox.call(this, key));
            };
        };

        res.locals['checkbox-compound'] = function () {
            var options = { compound: true };
            return function (key) {
                return compiled['partials/forms/checkbox'].render(checkbox.call(this, key, options));
            };
        };

        res.locals['checkbox-required'] = function () {
            var options = { required: true };
            return function (key) {
                return compiled['partials/forms/checkbox'].render(checkbox.call(this, key, options));
            };
        };

        /**
        * props: '[value] [id]'
        */
        res.locals['input-submit'] = function () {
            return function (props) {
                props = props.split(' ');
                var def = 'next',
                    value = props[0] || def,
                    id = props[1];

                var obj = {
                    value: t(sharedTranslationsKey + '.buttons.' + value),
                    id: id
                };
                return compiled['partials/forms/input-submit'].render(obj);
            };
        };

        res.locals.currency = function () {
            return function (txt) {
                var value = parseFloat(Hogan.compile(txt).render(this));
                if (isNaN(value)) {
                    return txt;
                } else if (value % 1 === 0) {
                    value = value.toString();
                } else {
                    value = value.toFixed(2);
                }
                return '£' + value;
            };
        };

        res.locals.date = function () {
            return function (txt) {
                var value = Hogan.compile(txt).render(this);
                return moment(value).format('D MMMM YYYY');
            };
        };

        res.locals.hyphenate = function () {
            return function (txt) {
                txt = txt || '';
                return Hogan.compile(txt).render(this).toLowerCase().replace(' ', '-');
            };
        };

        res.locals.uppercase = function () {
            return function (txt) {
                txt = txt || '';
                return Hogan.compile(txt).render(this).toUpperCase();
            };
        };

        res.locals.lowercase = function () {
            return function (txt) {
                txt = txt || '';
                return Hogan.compile(txt).render(this).toLowerCase();
            };
        };

        res.locals.selected = function () {
            return function (txt) {
                var bits = txt.split('='),
                    val;
                if (this.values && this.values[bits[0]] !== undefined) {
                    val = this.values[bits[0]].toString();
                }
                return val === bits[1] ? ' checked="checked"' : '';
            };
        };

        /**
        * Use on whole sentences
        */
        res.locals.time = function () {
            return function (txt) {
                txt = txt || '';
                txt = Hogan.compile(txt).render(this);
                txt = txt.replace(/12:00am/i, 'midnight').replace(/^midnight/, 'Midnight');
                txt = txt.replace(/12:00pm/i, 'midday').replace(/^middday/, 'Midday');
                return txt;
            };
        };

        res.locals.t = function () {
            return function (txt) {
                txt = Hogan.compile(txt).render(this);
                return t.apply(req, [txt, this]);
            };
        };

        next();
    };

};
<|endoftext|>


<commit_before>/**
 * Created by elijah on 6/21/15.
 */
var state = window.state;
function populateByCartId(){

    $.get(window.apiRoute + "/Carts/GetCartsByUser/don", function(res) {
        if(res && res.length) {
            var dropSelect = document.getElementById("selectDropDown");
            var results = JSON.parse(res)[0];
            var option1 =document.createElement("option");
            option1.text = 999;
            dropSelect.appendChild(option1);
            var option2 =document.createElement("option");
            option2.text = 42;
            dropSelect.appendChild(option2);
            var option3 =document.createElement("option");
            option3.text = 33;
            dropSelect.appendChild(option3);

            for(var i = 0; i < results.length; i++ ) {
                var option = document.createElement("option");
                option.value = results[i].CartID;
  /*              if(!(typeof state === 'undefined'))
                if(results[i].CartName == window.state.nameSelected){
                    option.attr("selected");
                }
    */            option.text = results[i].CartName;
                dropSelect.add(option);
            }
          /*  if(typeof state.nameSelected === 'undefined'){
            }
            else{
                var option = $(document.createElement("option"))
                    .attr("selected");
                dropSelect = state.nameSelected;
            }*/
        }
        else {
                $("#response").text("Error: Init: No response.");
            }
        }).fail(function(res) {
             $("#response").text("Error: Init: Connection error.");
        });
}

function displayCartInventory(){

    var cartContainer = $(".inventory-container");
    var cartList = $(document.createElement("div"))
        .appendTo(cartContainer);

//    state.nameSelected = $("#selectDropDown :selected").text();
//    navigation.saveState(window.state);
    var idSelected = $("#selectDropDown :selected").value;

    $.get(window.apiRoute + "/Carts/GetCartItems/" + idSelected, function(res) {
        if (res && res.length) {
            var items = JSON.parse(res)[0];
            for(var i = 0; i < items.length; i++){
                var name = items[i].ProductName.toString();
                var total = items[i].Total.toString();

                var cartItem = $(document.createElement("div"))
                    .appendTo(cartList);
                $(document.createElement("hr"))
                    .appendTo(cartItem);
                var productName = $(document.createElement("span"))
                    .text(name)
                    .appendTo(cartItem);
                var total = $(document.createElement("span"))
                    .text(total)
                    .addClass("float_right")
                    .appendTo(cartItem);
                cartList.append(cartItem);
            }
            cartContainer.append(cartList);

        }
        else {
            $("#response").text("Error: Init: No response.");
        }
    }).fail(function(res) {
        $("#response").text("Error: Init: Connection error.");
    });
}

/*function populateCartContainer(){
    for(var i = 0; i < cartStuff.length; i++){
        var productName = $(document.createElement("span"))
            .attr= cartStuff[i].Name;
        var cartItem = $(document.createElement("div"))
            .appendTo(cartList);

    }

}*/<commit_msg>display for each cart shows items in the cart selected! YAY, still need to: put the rest of the attributes into the display save state when needed change nav.vert back to how it was<commit_after>/**
 * Created by elijah on 6/21/15.
 */
var state = window.state;
function populateByCartId(){

    $.get(window.apiRoute + "/Carts/GetCartsByUser/don", function(res) {
        if(res && res.length) {
            var dropSelect = document.getElementById("selectDropDown");
            var results = JSON.parse(res)[0];
            var option1 =document.createElement("option");
            option1.text = 999;
            dropSelect.appendChild(option1);
            var option2 =document.createElement("option");
            option2.text = 42;
            dropSelect.appendChild(option2);
            var option3 =document.createElement("option");
            option3.text = 33;
            dropSelect.appendChild(option3);

            for(var i = 0; i < results.length; i++ ) {
                var option = document.createElement("option");
                option.value = results[i].CartID;
  /*              if(!(typeof state === 'undefined'))
                if(results[i].CartName == window.state.nameSelected){
                    option.attr("selected");
                }
    */            option.text = results[i].CartName;
                dropSelect.add(option);
            }
          /*  if(typeof state.nameSelected === 'undefined'){
            }
            else{
                var option = $(document.createElement("option"))
                    .attr("selected");
                dropSelect = state.nameSelected;
            }*/
        }
        else {
                $("#response").text("Error: Init: No response.");
            }
        }).fail(function(res) {
             $("#response").text("Error: Init: Connection error.");
        });
}

function displayCartInventory(){

    var cartContainer = $(".inventory-container");
    var cartList = $(document.createElement("div"))
        .appendTo(cartContainer);

//    state.nameSelected = $("#selectDropDown :selected").text();
//    navigation.saveState(window.state);
    var idSelected = $("#selectDropDown :selected").value;

    $.get(window.apiRoute + "/Carts/GetCartItems/" + idSelected, function(res) {
        if (res && res.length) {
            var items = JSON.parse(res)[0];
            for(var i = 0; i < items.length; i++){
                var name = items[i].ProductName.toString();
                var total = items[i].Total.toString();
                var sName  = items[i].SizeName.toString() + " of " + items[i].CountPerBatch.toString() + " * " + items[i].BatchCount.toString();

                var cartItem = $(document.createElement("div"))
                    .appendTo(cartList);
                $(document.createElement("hr"))
                    .appendTo(cartItem);
                var productName = $(document.createElement("span"))
                    .text(name)
                    .appendTo(cartItem);
                var total = $(document.createElement("span"))
                    .text(total)
                    .addClass("float_right")
                    .appendTo(cartItem);
                $(document.createElement("br"))
                    .appendTo(cartItem);
                var sizeName = $(document.createElement("span"))
                    .text(sName)
                    .appendTo(cartItem);
                cartList.append(cartItem);
            }
            cartContainer.append(cartList);

        }
        else {
            $("#response").text("Error: Init: No response.");
        }
    }).fail(function(res) {
        $("#response").text("Error: Init: Connection error.");
    });
}

/*function populateCartContainer(){
    for(var i = 0; i < cartStuff.length; i++){
        var productName = $(document.createElement("span"))
            .attr= cartStuff[i].Name;
        var cartItem = $(document.createElement("div"))
            .appendTo(cartList);

    }

}*/<|endoftext|>


<commit_before>var sku = "";

var cleanNames = {
    "auton-actions":"Auton. actions",
    "auton-pointsScored":"Auton. pts. scored",
    "auton-startTime":"Time left in auton. when play starts",
    "hang-duration":"Time to hang (if app.)",
    "hang-startTime":"Seconds left when hang starts",
    "hang-endTime":"Seconds left when hang ends",
    "hang-result":"Hang result",
    "hang-partnerHelp":"Partner help when hanging (if app.)",
    "robot-platformCubes":"# cubes platform holds (on avg.)",
    "robot-platformStars":"# stars platform holds (on avg.)",
    "robot-platformStability":"Sturdiness of platform",
    "robot-platformHolding":"How often objects fall off platform when robot turns",
    "robot-strafes":"Strafes",
    "robot-type":"Scoring method",
    "alliance":"Alliance in scouted match",
    "match":"Lasted scouted match",
    "team":"The team scouted (again)",
    "timestamp":"Ignore this value",
    "user":"Ignore this value"
}

function processResults (team,alliance,value) {
    console.log(team,alliance,value);
    var apiResponse = value;
    console.log(apiResponse);
    var currentTeamInfo;
    var propertyValue;
    output = '

' + alliance + ' - ' + team
            + '

Property	Value

';

        if (value !== null) {
            currentTeamInfo = value;

            for (var prop in value) {
                console.log(value);
                console.log("prop",prop);
                if (prop === "robot" || prop === "hang" || prop === "auton") {
                    for (var nestedProp in value[prop]) {
                        console.log("nestedProp",nestedProp);
                        propertyValue = cleanNames[prop + "-" + nestedProp];
                        output += '
' + propertyValue + '	' + value[prop][nestedProp] + '
';
                    }
                } else {
                    propertyValue = cleanNames[prop];
                    output += '
' + propertyValue + '	' + value[prop] + '
';
                }
            }

            output += '

';
        } else {
            output = '

' + alliance + ' - ' + team
                + '
info_outline No data available';
        }
        $('#match-team-info-tables').append(output);

    $('#match-info-data-loading').removeClass("is-active").addClass("hidden");

}

function processMatchTeams(value) {
    var match = value.results,
        partner,
        opponent1,
        opponent2;
    alert(match.matchnumber);
    //determine alliance and position on alliance
    if (match.red1 === queryTeam) {
        alliance = "red";
        alliancePosition = "red1";
    } else if (match.red2 === queryTeam) {
        alliance = "red";
        alliancePosition = "red2";
    } else if (match.blue1 === queryTeam) {
        alliance = "blue";
        alliancePosition = "blue1";
    } else if (match.blue2 === queryTeam) {
        alliance = "blue";
        alliancePosition = "blue2";
    }

    //determine partner for this match
    if (alliance === "red") {
        if (alliancePosition === "red1") {
            partner = match.red2;
        } else { //this team is red2, so partner is red1
            partner = match.red1;
        }
    } else if (alliance === "blue") {
        if (alliancePosition === "blue1") {
            partner = match.blue2;
        } else { //this team is blue2, so partner is blue1
            partner = match.blue1;
        }
    }

    if (alliance === "red") {
        opponent1 = match.blue1;
        opponent2 = match.blue2;
    } else {
        opponent1 = match.red1;
        opponent2 = match.red2;
    }

    //getTeamInfo(partner);
    //getTeamInfo(opponent1);
    //getTeamInfo(opponent2);
    console.log(alliance);
    console.log(alliancePosition);
}

function getTeamInfo(team) {
    //var url = "https://script.google.com/a/macros/woodward.edu/s/AKfycbxsKMe0cdyYScaJXipBoA2bFSY8Aj-jxlQqyS4aDOI/dev?prefix=processResults&type=getTeamInfo&id=1vrZQpvtiJvcyKdlULZk5HOyRU5ystAiMZ4y8rF6dJEg&team=" + team;
    console.log(team);
    console.log(url);
    //$('body').append('


<commit_before>function initOverLabels () {
  if (!document.getElementById) return;

  var labels, id, field;

  // Set focus and blur handlers to hide and show
  // LABELs with 'overlabel' class names.
  labels = document.getElementsByTagName('label');
  for (var i = 0; i < labels.length; i++) {

    if (labels[i].className == 'overlabel') {

      // Skip labels that do not have a named association
      // with another field.
      id = labels[i].htmlFor || labels[i].getAttribute('for');
      if (!id || !(field = document.getElementById(id))) {
        continue;
      }

      // Change the applied class to hover the label
      // over the form field.
      labels[i].className = 'overlabel-apply';

      // Hide any fields having an initial value.
      if (field.value !== '') {
        hideLabel(field.getAttribute('id'), true);
      }

      // Set handlers to show and hide labels.
      field.onfocus = function () {
        hideLabel(this.getAttribute('id'), true);
      };
      field.onblur = function () {
        if (this.value === '') {
          hideLabel(this.getAttribute('id'), false);
        }
      };

      // Handle clicks to LABEL elements (for Safari).
      labels[i].onclick = function () {
        var id, field;
        id = this.getAttribute('for');
        if (id && (field = document.getElementById(id))) {
          field.focus();
        }
      };

    }
  }
};

function hideLabel (field_id, hide) {
  var field_for;
  var labels = document.getElementsByTagName('label');
  for (var i = 0; i < labels.length; i++) {
    field_for = labels[i].htmlFor || labels[i].getAttribute('for');
    if (field_for == field_id) {
      labels[i].style.textIndent = (hide) ? '-1000px' : '0px';
      return true;
    }
  }
}

FastInit.addOnLoad(function(){
	initOverLabels();
});<commit_msg>fix for firefox<commit_after>function initOverLabels () {
  if (!document.getElementById) return;

  var labels, id, field;

  // Set focus and blur handlers to hide and show
  // LABELs with 'overlabel' class names.
  labels = document.getElementsByTagName('label');
  for (var i = 0; i < labels.length; i++) {

    if (labels[i].className == 'overlabel') {

      // Skip labels that do not have a named association
      // with another field.
      id = labels[i].htmlFor || labels[i].getAttribute('for');
      if (!id || !(field = document.getElementById(id))) {
        continue;
      }

      // Change the applied class to hover the label
      // over the form field.
      labels[i].className = 'overlabel-apply';

      // Hide any fields having an initial value.
      if (field.value !== '') {
        hideLabel(field.getAttribute('id'), true);
      }

      // Set handlers to show and hide labels.
      field.onfocus = function () {
        hideLabel(this.getAttribute('id'), true);
      };
      field.onblur = function () {
        if (this.value === '') {
          hideLabel(this.getAttribute('id'), false);
        }
      };

      // Handle clicks to LABEL elements (for Safari).
      labels[i].onclick = function () {
        var id, field;
        id = this.getAttribute('for');
        if (id && (field = document.getElementById(id))) {
          field.focus();
        }
      };

    }
  }
};

function hideLabel (field_id, hide) {
  var field_for;
  var labels = document.getElementsByTagName('label');
  for (var i = 0; i < labels.length; i++) {
    field_for = labels[i].htmlFor || labels[i].getAttribute('for');
    if (field_for == field_id) {
      labels[i].style.textIndent = (hide) ? '-10000px' : '0px';
      return true;
    }
  }
}

FastInit.addOnLoad(function(){
	initOverLabels();
});<|endoftext|>


<commit_before>var app = angular.module('scheduler',['ngRoute']);

app.config(['$routeProvider',function($routeProvider){
  $routeProvider.when('/test',{

  })
}]);

app.directive('onRenderFinished',function(){ //Directive to ensure right rendering of dateheaders
  return {
    restrict: 'A',
    link: function(scope,elem,attr){
      if(scope.$last === true)
      {
        $('.dateheader').css('position','static');
        $('.dateheader').scrollToFixed();
      }
    }
  }
});

/*
* Directive to populate group input.
*/
app.directive('groups',function($compile){
  return {
    restrict: 'E',
    link: function(scope,elem,attrs,schoolDays){
      scope.schoolDays = schoolDays;
    },
    controller: function($scope,$http)
    {

      $scope.groupselected = function(){ //Triggers getLessons-function of LessonsController.
        $scope.lessons.lessons = [];
        console.log('groups:groupselected');
        $scope.use_sample_data = false;
        $scope.lessons.getLessons($scope.lessons.selectedgroup,null);
      };

      this.initialize = function(){
        $http.get(rooturl + '/groups').success(function(data,status,headers,config){
            if(status === 200)
            {
                $scope.lessons.groups = data;
                $scope.lessons.selectedgroup = data[0];
                console.log($scope.lessons.selectedgroup);
            }
        });
      }
      this.initialize();
    },
    templateUrl: rooturl + '/angular-templates/groups.html',
  };
});
app.directive('schoolDays',function($compile){
  return {
    template: "<ng-include src='getTemplate()'></ng-include>",

    controller: function($scope)
    {
      $(window).scroll(function() {
         if(($(window).scrollTop() + $(window).height()) > ($(document).height() - 100)) {
           console.log($scope.lessons.lessons.length);
           if(!$scope.fetching_lessons_unfinished && $scope.lessons.lessons.length > 0)
           {
               $scope.lessons.getLessons($scope.selectedgroup,moment($scope.lessons.lessons[$scope.lessons.lessons.length-1].date).add(2,'days').format('YYYY-MM-DD'));
           }
         }
      });
    },
  }
});
app.controller('LessonsController',function($scope,$http){ //This controller will be replaced by directive.

  var scope = this;
  this.hours = [8,9,10,11,12,13,14,15,16,17,18,19,20];
  this.lessons = [];
  this.groups = [];
  this.selectedgroup = '';
  this.rowheight = 150;
  this.minuteheight = this.rowheight/60.0;
  this.lessonsareaheight = this.hours.length * this.rowheight - $('.dateheader').height();
  this.fetching_lessons_unfinished = true; //To prevent fetching same week many times.
  var that = this;
  that.isWeekView = false;
  that.isDayView = true;
  $scope.use_sample_data = false;

  $scope.$watch('use_sample_data',function(){
    if($scope.use_sample_data)
    {
      scope.lessons = [];
      scope.lessons.length = 0;
      scope.getLessons();
    }
  });
  this.changeView = function(){
      if(that.isWeekView){
        that.isDayView = true;
        that.isWeekView = false;
      }
      else{
        that.isDayView = false;
        that.isWeekView = true;
      }
  }

  $scope.isNewWeek = function(index){
    return (parseInt(index) % 7) == 0;
  }

  $scope.getTemplate = function(){
    var rootURL = rooturl + '/angular-templates/';
    var templates = {
      week: rootURL + 'weekview.html',
      day: rootURL + 'dayview.html'
    }
    if(that.isDayView)
    {
      return templates.day;
    }
    return templates.week;
  }

  this.getLessons = function(group,selected_date){
      scope.fetching_lessons_unfinished = true;
      var url = "";
      if($scope.use_sample_data)
      {
        url = (selected_date) ? rooturl + '/lessons/json/sampledata/' + selected_date : rooturl + '/lessons/json/sampledata';
      }
      else{
        url = rooturl + '/lessons/json/group/' + group;
        if(selected_date)
        {
          url = url + '/' + selected_date;
        }
      }
      $http.get(url).success(function (data,status,headers,config){
          if(status === 200)
          {
              //Generating y-position and height of lessons regarding starting- and endingtime.
              for(var i=0;i<data.length;i++)
              {
                  for(var j=0;j<data[i].lessons.length;j++)
                  {
                      var start = data[i].lessons[j].start_time.split(":");
                      var y0 = parseInt(start[1])*scope.minuteheight+(parseInt(start[0])-scope.hours[0])*scope.rowheight;
                      var end = data[i].lessons[j].end_time.split(":");
                      var y1 = parseInt(end[1])*scope.minuteheight + (parseInt(end[0])-scope.hours[0])*scope.rowheight;

                      data[i].lessons[j].top = y0;
                      data[i].lessons[j].height = y1-y0;
                      if(data[i].lessons[j].lecturer instanceof Array){//For many lecturers.
                        data[i].lessons[j].lecturer = data[i].lessons[j].lecturer.join(",");
                      }
                  }
              }
              $.merge(scope.lessons,data);
              console.log(scope.lessons[0].lessons[0]);
          }
          scope.fetching_lessons_unfinished = false;
      });
  };
});
<commit_msg>Fix to prevent fetching a week multiple times.<commit_after>var app = angular.module('scheduler',['ngRoute']);

app.config(['$routeProvider',function($routeProvider){
  $routeProvider.when('/test',{

  })
}]);

app.directive('onRenderFinished',function(){ //Directive to ensure right rendering of dateheaders
  return {
    restrict: 'A',
    link: function(scope,elem,attr){
      if(scope.$last === true)
      {
        $('.dateheader').css('position','static');
        $('.dateheader').scrollToFixed();
      }
    }
  }
});

/*
* Directive to populate group input.
*/
app.directive('groups',function($compile){
  return {
    restrict: 'E',
    link: function(scope,elem,attrs,schoolDays){
      scope.schoolDays = schoolDays;
    },
    controller: function($scope,$http)
    {

      $scope.groupselected = function(){ //Triggers getLessons-function of LessonsController.
        $scope.lessons.lessons = [];
        console.log('groups:groupselected');
        $scope.use_sample_data = false;
        $scope.lessons.getLessons($scope.lessons.selectedgroup,null);
      };

      this.initialize = function(){
        $http.get(rooturl + '/groups').success(function(data,status,headers,config){
            if(status === 200)
            {
                $scope.lessons.groups = data;
                $scope.lessons.selectedgroup = data[0];
                console.log($scope.lessons.selectedgroup);
            }
        });
      }
      this.initialize();
    },
    templateUrl: rooturl + '/angular-templates/groups.html',
  };
});
app.directive('schoolDays',function($compile){
  return {
    template: "<ng-include src='getTemplate()'></ng-include>",

    controller: function($scope)
    {
      $(window).scroll(function() {
         if(($(window).scrollTop() + $(window).height()) > ($(document).height() - 100)) {
           console.log($scope.fetching_lessons_unfinished);
           if(!$scope.fetching_lessons_unfinished && $scope.lessons.lessons.length > 0)
           {
               $scope.getLessons($scope.selectedgroup,moment($scope.lessons.lessons[$scope.lessons.lessons.length-1].date).add(2,'days').format('YYYY-MM-DD'));
           }
         }
      });
    },
  }
});
app.controller('LessonsController',function($scope,$http){ //This controller will be replaced by directive.

  var scope = this;
  this.hours = [8,9,10,11,12,13,14,15,16,17,18,19,20];
  this.lessons = [];
  this.groups = [];
  this.selectedgroup = '';
  this.rowheight = 150;
  this.minuteheight = this.rowheight/60.0;
  this.lessonsareaheight = this.hours.length * this.rowheight - $('.dateheader').height();
  $scope.fetching_lessons_unfinished = false; //To prevent fetching same week many times.

  scope.isWeekView = false;
  scope.isDayView = true;
  $scope.use_sample_data = false;

  $scope.$watch('use_sample_data',function(){
    if($scope.use_sample_data)
    {
      scope.lessons = [];
      scope.lessons.length = 0;
      $scope.getLessons();
    }
  });
  this.changeView = function(){
      if(scope.isWeekView){
        scope.isDayView = true;
        scope.isWeekView = false;
      }
      else{
        scope.isDayView = false;
        scope.isWeekView = true;
      }
  }

  $scope.isNewWeek = function(index){
    return (parseInt(index) % 7) == 0;
  }

  $scope.getTemplate = function(){
    var rootURL = rooturl + '/angular-templates/';
    var templates = {
      week: rootURL + 'weekview.html',
      day: rootURL + 'dayview.html'
    }
    if(scope.isDayView)
    {
      return templates.day;
    }
    return templates.week;
  }

  $scope.getLessons = function(group,selected_date){
      $scope.fetching_lessons_unfinished = true;
      console.log("asoijdaiosjdasioj");
      var url = "";
      if($scope.use_sample_data)
      {
        url = (selected_date) ? rooturl + '/lessons/json/sampledata/' + selected_date : rooturl + '/lessons/json/sampledata';
      }
      else{
        url = rooturl + '/lessons/json/group/' + group;
        if(selected_date)
        {
          url = url + '/' + selected_date;
        }
      }
      $http.get(url).success(function (data,status,headers,config){
          if(status === 200)
          {
              //Generating y-position and height of lessons regarding starting- and endingtime.
              for(var i=0;i<data.length;i++)
              {
                  for(var j=0;j<data[i].lessons.length;j++)
                  {
                      var start = data[i].lessons[j].start_time.split(":");
                      var y0 = parseInt(start[1])*scope.minuteheight+(parseInt(start[0])-scope.hours[0])*scope.rowheight;
                      var end = data[i].lessons[j].end_time.split(":");
                      var y1 = parseInt(end[1])*scope.minuteheight + (parseInt(end[0])-scope.hours[0])*scope.rowheight;

                      data[i].lessons[j].top = y0;
                      data[i].lessons[j].height = y1-y0;
                      if(data[i].lessons[j].lecturer instanceof Array){//For many lecturers.
                        data[i].lessons[j].lecturer = data[i].lessons[j].lecturer.join(",");
                      }
                  }
              }
              $.merge(scope.lessons,data);
              console.log(scope.lessons[0].lessons[0]);
          }
          $scope.fetching_lessons_unfinished = false;
      });
  };
});
<|endoftext|>


<commit_before>import 'babel-polyfill';
import fs from 'fs';
import readline from 'readline';
import program from 'commander';
import { observer as globalObserver } from '../../common/utils/observer';
import { version } from '../../../package.json';
import { createInterpreter } from './CliTools';

const log = (...args) => console.log(`${new Date().toLocaleTimeString()}:`, ...args); // eslint-disable-line no-console

process.on('unhandledRejection', e => log('Unhandled Rejection:', e));

setInterval(() => {}, 2147483647); // Keep node alive

let filename;

program
    .version(version)
    .usage('[filename]')
    .arguments('[filename]')
    .action(fn => {
        filename = fn;
    })
    .parse(process.argv);

const lineReader = readline.createInterface({
    input: filename ? fs.createReadStream(filename) : process.stdin,
});

let code = '';

const interpreter = createInterpreter();

globalObserver.register('Error', e => log(e));

globalObserver.register('Notify', ({ className, message }) => log(`${className.toUpperCase()}: ${message}`));

lineReader
    .on('line', line => {
        code += `${line}\n`;
    })
    .on('error', e => log(e))
    .on('close', () =>
        interpreter
            .run(code)
            .then(v => log(v.data))
            .catch(e => log(e))
    );
<commit_msg>Remove undefined version from CLI<commit_after>import 'babel-polyfill';
import fs from 'fs';
import readline from 'readline';
import program from 'commander';
import { observer as globalObserver } from '../../common/utils/observer';
import { createInterpreter } from './CliTools';

const log = (...args) => console.log(`${new Date().toLocaleTimeString()}:`, ...args); // eslint-disable-line no-console

process.on('unhandledRejection', e => log('Unhandled Rejection:', e));

setInterval(() => {}, 2147483647); // Keep node alive

let filename;

program
    .usage('[filename]')
    .arguments('[filename]')
    .action(fn => {
        filename = fn;
    })
    .parse(process.argv);

const lineReader = readline.createInterface({
    input: filename ? fs.createReadStream(filename) : process.stdin,
});

let code = '';

const interpreter = createInterpreter();

globalObserver.register('Error', e => log(e));

globalObserver.register('Notify', ({ className, message }) => log(`${className.toUpperCase()}: ${message}`));

lineReader
    .on('line', line => {
        code += `${line}\n`;
    })
    .on('error', e => log(e))
    .on('close', () =>
        interpreter
            .run(code)
            .then(v => log(v.data))
            .catch(e => log(e))
    );
<|endoftext|>


<commit_before>$(function() {
    window.likeTalk = function (elem, id){
		let $elem = $(elem);
		let like = $elem.attr('data-like');
		if(like) {
			// User want to no more like this talk
			_unlikeIcon($elem);
			_removeLike(id);
		}
		else {
			// User click on Like
			_likeIcon($elem);
			_addLike(id);
		}
	}

	// initialiez Liked Talk
	window.initLikedTalks = function () {
		let likes = _getLikes();
		for (var i = 0; i < likes.length; i++) {
			_likeIcon($('[data-talk=' + likes[i] + ']'))
		}
	}

	function _likeIcon($elem){
		let $svg = $elem.find('[data-fa-i2svg]')
        .toggleClass('far')
		.toggleClass('fas');
		$elem.attr('data-like', true);
	}

	function _unlikeIcon($elem){
		let $svg = $elem.find('[data-fa-i2svg]');
		$svg.attr('data-prefix', 'far');
		$elem.attr('data-like', null);
	}

	/**
	 * Add a talk in liked talks
	 * @param {int} id ID of the talk
	 */
	function _addLike(id){
		let likes = _getLikes();
		likes.push(id);
		_setLikes(likes);

		$.ajax({
			url: '/like-talk/' + id,
			type: 'POST',
			success: function(result) {
				$('.js-talksFilter-like[data-talk=' + id + '] span').html(result)
			},
			error : function(result) {
			}
		});
	}

	/**
	 * Remove a talk from liked talks
	 * @param {int} id ID of the talk
	 */
	function _removeLike(id){
		let likes = _getLikes();
		let index = likes.indexOf(id);
		if (index > -1) {
			likes.splice(index, 1);
		}
		_setLikes(likes);

		$.ajax({
			url: '/unlike-talk/' + id,
			type: 'POST',
			success: function(result) {
				$('.js-talksFilter-like[data-talk=' + id + '] span').html(result)
			},
			error : function(result) {
			}
		});
	}

	/**
	 * Return array of ID talks liked by the user.
	 * (The information is saved in the local storage of the user)
	 */
	function _getLikes(){
		if (window.localStorage) {
			let likes = JSON.parse(localStorage.getItem('RivieraDEV-2018-Likes'));
			if(!likes){
				// Initialize value
				likes = [];
				_setLikes(likes);
			}
			return likes;
		}
		return [];
	}

	/**
	 * Save in the local storage an array of ID talks liked by the user
	 * @param {array} likes
	 */
	function _setLikes(likes){
		if (window.localStorage) {
			localStorage.setItem('RivieraDEV-2018-Likes', JSON.stringify(likes));
		}
	}

});<commit_msg>Some fixes after review<commit_after>$(function() {
    window.likeTalk = function (elem, id){
		let $elem = $(elem);
		let like = $elem.attr('data-like');
		if(like) {
			// The user doesn't want to like this talk anymore
			_unlikeIcon($elem);
			_removeLike(id);
		}
		else {
			// The user likes the talk
			_likeIcon($elem);
			_addLike(id);
		}
	}

	// Initialize Liked Talks
	window.initLikedTalks = function () {
		let likes = _getLikes();
		for (var i = 0; i < likes.length; i++) {
			_likeIcon($('[data-talk=' + likes[i] + ']'))
		}
	}

	function _likeIcon($elem){
		let $svg = $elem.find('[data-fa-i2svg]');
		$svg.attr('data-prefix', 'fas');
		$elem.attr('data-like', true);
	}

	function _unlikeIcon($elem){
		let $svg = $elem.find('[data-fa-i2svg]');
		$svg.attr('data-prefix', 'far');
		$elem.attr('data-like', null);
	}

	/**
	 * Add a talk in liked talks
	 * @param {int} id ID of the talk
	 */
	function _addLike(id){
		let likes = _getLikes();
		likes.push(id);
		_setLikes(likes);

		$.ajax({
			url: '/like-talk/' + id,
			type: 'POST',
			success: function(result) {
				$('.js-talksFilter-like[data-talk=' + id + '] span').html(result)
			},
			error : function(result) {
			}
		});
	}

	/**
	 * Remove a talk from liked talks
	 * @param {int} id ID of the talk
	 */
	function _removeLike(id){
		let likes = _getLikes();
		let index = likes.indexOf(id);
		if (index > -1) {
			likes.splice(index, 1);
		}
		_setLikes(likes);

		$.ajax({
			url: '/unlike-talk/' + id,
			type: 'POST',
			success: function(result) {
				$('.js-talksFilter-like[data-talk=' + id + '] span').html(result)
			},
			error : function(result) {
			}
		});
	}

	/**
	 * Return array of ID talks liked by the user.
	 * (The information is saved in the local storage of the user)
	 */
	function _getLikes(){
		if (window.localStorage) {
			let likes = JSON.parse(localStorage.getItem('RivieraDEV-2018-Likes'));
			if(!likes){
				// Initialize value
				likes = [];
				_setLikes(likes);
			}
			return likes;
		}
		return [];
	}

	/**
	 * Save in the local storage an array of ID talks liked by the user
	 * @param {array} likes
	 */
	function _setLikes(likes){
		if (window.localStorage) {
			localStorage.setItem('RivieraDEV-2018-Likes', JSON.stringify(likes));
		}
	}

});<|endoftext|>